一final关键字
在java中声明类、属性和方法时,可使用关键字final来修饰
运行截图
在java中声明类、属性和方法时,可使用关键字final来修饰
·final标记的类不能被继承
·final标记的方法不能被子类重写
·final标记的变量(成员或局部变量)即成为常量,只能赋值一次
二:构造函数并不具有多态性,它们实际上是static方法,只不过该static声明是隐式的。因此,构造函数不能够被override。
运行子类时会先运行完父类不带参数构造方法才会运行自己带参数构造方法(解释了输出结果:RoundGlyph1.draw(). radius = 0),被子类重写父类的方法,在父类中调用时会调用子类中的而非父类的。
package test;
class Glyph {
void draw() {
System.out.println("Glyph.draw()");
}
Glyph() {
System.out.println("Glyph() before draw()");
draw();
System.out.println("Glyph() after draw()");
}
}
class RoundGlyph extends Glyph {
private int radius = 1;
RoundGlyph(int r) {
radius = r;
System.out.println("RoundGlyph.RoundGlyph(). radius = " + radius);
}
void draw() {
System.out.println("RoundGlyph1.draw(). radius = " + radius);
}
}
public class Test18 {
public static void main(String[] args) {
new RoundGlyph(5);
}
}
运行截图
三:只有非private方法才可以被覆盖,但是还需要密切注意覆盖private方法的现象,这时虽然编译器不会报错,但是也不会按照我们所期望的来执行,即覆盖private方法对子类来说是一个新的方法而非重载方法。
package test;
class Glyph {
private void draw() {
System.out.println("Glyph.draw()");
}
Glyph() {
System.out.println("Glyph() before draw()");
draw();
System.out.println("Glyph() after draw()");
}
}
class RoundGlyph extends Glyph {
private int radius = 1;
RoundGlyph(int r) {
radius = r;
System.out.println("RoundGlyph.RoundGlyph(). radius = " + radius);
}
void draw(){
System.out.println("RoundGlyph1.draw(). radius = " + radius);
}
}
public class Test18 {
public static void main(String[] args) {
new RoundGlyph(5);
}
}
运行截图:发现父类构造方法中调用父类被子类重写的方法时不再运行子类的draw()方法,而运行自己的draw():
2. is-a关系和is-like-a关系
-
is-a关系属于纯继承,即只有在基类中已经建立的方法才可以在子类中被覆盖,如下图所示:
基类和子类有着完全相同的接口,这样向上转型时永远不需要知道正在处理的对象的确切类型,这通过多态来实现。 -
is-like-a关系:子类扩展了基类接口。它有着相同的基本接口,但是他还具有由额外方法实现的其他特性。
缺点就是子类中接口的扩展部分不能被基类访问,因此一旦向上转型,就不能调用那些新方法。