java继承示例
package day07; class Fu { int num = 5; } class Zi extends Fu { int num =7; void show() { int num =9; System.out.println(num); } } public class Extends { public static void main(String[] args) { Zi zi = new Zi(); zi.show(); } }
9//自己有就不去找
package day07; class Fu { int num = 5; } class Zi extends Fu { int num =7; void show() { int num =9; System.out.println(this.num); } } public class Extends { public static void main(String[] args) { Zi zi = new Zi(); zi.show(); } }
7
package day07; class Fu { int num = 5; } class Zi extends Fu { int num =7; void show() { int num =9; System.out.println(super.num); } } public class Extends { public static void main(String[] args) { Zi zi = new Zi(); zi.show(); } }
5
super代表的是父类,this代表的是本类对象的引用,super代表父类所属空间
注意:子类父类中通常不会出现同名属性,父类中既然已经定义了num属性,子类就没有必要定义该属性
子类无法覆父类中的show方法,因为类型不一样
package day07; class Fu { public static void show() { System.out.println("run show1"); } public void show2() { System.out.println("haha1"); } } class Zi extends Fu { public static void show() { System.out.println("run show2"); } public void show2() { System.out.println("haha2"); } } public class Extends { public static void main(String[] args) { Fu f = new Zi();//注意这个地方对象的创建,以及结果,静态方法以及成员变量和普通方法的区别 f.show(); f.show2(); } }
run show1
haha2
对比:
package day07; class Fu { public static void show() { System.out.println("run show1"); } public void show2() { System.out.println("haha1"); } } class Zi extends Fu { public static void show() { System.out.println("run show2"); } public void show2() { System.out.println("haha2"); } } public class Extends { public static void main(String[] args) { Zi z = new Zi();//注意这个地方对象的创建,以及结果,静态方法以及成员变量和普通方法的区别 z.show(); z.show2(); } }
run show2
haha2
覆盖的时候注意:
1、子类覆盖父类的时候保证覆盖方法的权限大于等于被覆盖函数的权限
2、覆盖方法有静态修士的时候,静态只能覆盖静态,或者被静态覆盖