1.被fnial修饰的方法不能被重写,常见的为修饰类,方法,变量
/* final可以修饰类,方法,变量 特点: final可以修饰类,该类不能被继承。 final可以修饰方法,该方法不能被重写。(覆盖,复写) final可以修饰变量,该变量不能被重新赋值。因为这个变量其实常量。 常量: A:字面值常量 "hello",10,true B:自定义常量 final int x = 10; */ //final class Fu //无法从最终Fu进行继承 class Fu { public int num = 10; public final int num2 = 20; /* public final void show() { } */ } class Zi extends Fu { // Zi中的show()无法覆盖Fu中的show() public void show() { num = 100; System.out.println(num); //无法为最终变量num2分配值 //num2 = 200; System.out.println(num2); } } class FinalDemo { public static void main(String[] args) { Zi z = new Zi(); z.show(); } }
A:被final修饰的变量只能赋值一次
/* final修饰变量的初始化时机 A:被final修饰的变量只能赋值一次。 B:在构造方法完毕前。(非静态的常量) */ class Demo { //int num = 10; //final int num2 = 20; int num; final int num2; { //num2 = 10; } public Demo() { num = 100; //无法为最终变量num2分配值 num2 = 200; }
} class FinalTest2 { public static void main(String[] args) { Demo d = new Demo(); System.out.println(d.num); System.out.println(d.num2); } }
多态:同一个对象(事物)在不同的时刻体现出来的不同的状态
多态的前提:
A:要有继承关系
B:要有方法重写
C:要有父类引用指向
/* 多态:同一个对象(事物),在不同时刻体现出来的不同状态。 多态的前提: A:要有继承关系。 B:要有方法重写。 其实没有也是可以的,但是如果没有这个就没有意义。 动物 d = new 猫(); d.show(); 动物 d = new 狗(); d.show(); C:要有父类引用指向子类对象。 父 f = new 子(); 用代码体现一下多态。 多态中的成员访问特点: A:成员变量 编译看左边,运行看左边。 B:构造方法 创建子类对象的时候,访问父类的构造方法,对父类的数据进行初始化。 C:成员方法 编译看左边,运行看右边。 D:静态方法 编译看左边,运行看左边。 (静态和类相关,算不上重写,所以,访问还是左边的) 由于成员方法存在方法重写,所以它运行看右边。 */ class Fu { public int num = 100; public void show() { System.out.println("show Fu"); } public static void function() { System.out.println("function Fu"); } } class Zi extends Fu { public int num = 1000; public int num2 = 200; public void show() { System.out.println("show Zi"); } public void method() { System.out.println("method zi"); } public static void function() { System.out.println("function Zi"); } } class DuoTaiDemo { public static void main(String[] args) { //要有父类引用指向子类对象。 //父 f = new 子(); Fu f = new Zi(); System.out.println(f.num); //找不到符号 //System.out.println(f.num2); f.show(); //找不到符号 //f.method(); f.function(); } }
多态实例:
/* 不同地方饮食文化不同的案例 */ class Person { public void eat() { System.out.println("吃饭"); } } class SouthPerson extends Person { public void eat() { System.out.println("炒菜,吃米饭"); } public void jingShang() { System.out.println("经商"); } } class NorthPerson extends Person { public void eat() { System.out.println("炖菜,吃馒头"); } public void yanJiu() { System.out.println("研究"); } } class DuoTaiTest2 { public static void main(String[] args) { //测试 //南方人 Person p = new SouthPerson(); p.eat(); System.out.println("-------------"); SouthPerson sp = (SouthPerson)p; sp.eat(); sp.jingShang(); System.out.println("-------------"); //北方人 p = new NorthPerson(); p.eat(); System.out.println("-------------"); NorthPerson np = (NorthPerson)p; np.eat(); np.yanJiu(); } }