当前位置: 技术问答>java相关
关于 abstract class
来源: 互联网 发布时间:2015-08-11
本文导语: thinking in java 讲述建构式中存在着poymorphism method方法时, 有下面这个例子。 abstract class Glyph { abstract void draw(); Glyph() { System.out.println("Glyph() before draw()"); draw(); System.out.println("Glyph() after draw()"); } } class R...
thinking in java 讲述建构式中存在着poymorphism method方法时,
有下面这个例子。
abstract class Glyph {
abstract void draw();
Glyph() {
System.out.println("Glyph() before draw()");
draw();
System.out.println("Glyph() after draw()");
}
}
class RoundGlyph extends Glyph {
int radius = 1;
RoundGlyph(int r) {
radius = r;
System.out.println(
"RoundGlyph.RoundGlyph(), radius = "
+ radius);
}
void draw()
System.out.println(
"RoundGlyph.draw(), radius = " + radius);
}
}
public class PolyConstructors {
public static void main(String[] args) {
new RoundGlyph(5);
}
}
RoundGlyph extends Glyph,在RoundGlyph呼叫自身的建构式之前
会先呼叫Glyph的建构式。
可是Glyph是abstract,抽象类没法产生实际的物件,那怎么可以呼叫Glyph()??
有下面这个例子。
abstract class Glyph {
abstract void draw();
Glyph() {
System.out.println("Glyph() before draw()");
draw();
System.out.println("Glyph() after draw()");
}
}
class RoundGlyph extends Glyph {
int radius = 1;
RoundGlyph(int r) {
radius = r;
System.out.println(
"RoundGlyph.RoundGlyph(), radius = "
+ radius);
}
void draw()
System.out.println(
"RoundGlyph.draw(), radius = " + radius);
}
}
public class PolyConstructors {
public static void main(String[] args) {
new RoundGlyph(5);
}
}
RoundGlyph extends Glyph,在RoundGlyph呼叫自身的建构式之前
会先呼叫Glyph的建构式。
可是Glyph是abstract,抽象类没法产生实际的物件,那怎么可以呼叫Glyph()??
|
虽然Glyph是abstract,但Glyph()没有声明为abstract,是可以直接调用的。
|
RoundGlyph 继承了Glyph,但没有覆盖Glyph的构造方法,也就是说,
RoundGlyph还有一个默认的,但不是显性的构造方法:
RoundGlyph(){
System.out.println("Glyph() before draw()");
draw();
System.out.println("Glyph() after draw()");
}
RoundGlyph还有一个默认的,但不是显性的构造方法:
RoundGlyph(){
System.out.println("Glyph() before draw()");
draw();
System.out.println("Glyph() after draw()");
}