/* this调用本类成员 super调用父类成员 */ public class Super { public static void main(String[] args) { Zi z = new Zi(); z.method(); } } class Fu{ int num = 10; } class Zi extends Fu{ int num = 20; public void method(){ int num = 30; System.out.println(num);//30 System.out.println(this.num);//20 System.out.println(super.num);//10 } }
/* 方法重载(overload):在同一个类中,方法名相同,参数不同,与返回值无关 参数不同:类型不同,个数不同,顺序不同 方法重写(Override):在子父类当中,出现了方法声明一模一样的方法(方法名,参数,返回值都相同) 注意事项: 1.父类中私有方法不能被重写 2.子类重写父类方法时,被重写的方法访问权限必须大于父类 */ public class FangfaChongxie { } class Fu{ public void love(){ System.out.println("送花"); } } class Zi extends Fu{ @Override public void love() { super.love(); System.out.println("吃饭"); } }
/* java只支持单继承,不支持多继承。但支持多层继承。 */ public class JiCheng { public static void main(String[] args) { C c = new C(); c.show(); } } class A{ public void show(){ System.out.println("A"); } } class B extends A{ @Override public void show() { super.show(); System.out.println("B"); } } class C extends B{ @Override public void show() { super.show(); System.out.println("C"); } } 输出如下:
public class Person { private String name; private int age; public Person() { } public Person(String name, int age) { this.name = name; this.age = age; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
public class Student extends Person{ private double score; public Student() { } public Student(String name, int age, double score) { super(name, age); this.score = score; } public double getScore() { return score; } public void setScore(double score) { this.score = score; } public void study(){ System.out.println("学生姓名:" + super.getName() + ",年龄:" + super.getAge() + ",成绩:" + score); } }
package code.extends_demo05; public class Teacher extends Person{ public Teacher() { } public Teacher(String name, int age) { super(name, age); } public void teach(){ System.out.println("姓名:" + super.getName() + ",年龄:" + super.getAge() + "正在教学!"); } }
/* 处理Object类,在所有构造方法的第一行代码,都默认隐藏了一句话 super() 通过这句代码,访问父类的空参数构造方法 Java当中的所有类,都直接或间接的继承了Object类 */ public class ConstructorTest { public static void main(String[] args) { Teacher t = new Teacher("张三", 20); Student s = new Student("李四", 16, 60.0); t.teach(); s.study(); } }
/* super调用父类的省略规则: super.父类成员变量 | super.父类成员方法() ->被调用的变量和方法,在子类中若不存在,super.可以直接省略的 */ public class SuperTest { public static void main(String[] args) { Zi z = new Zi(); z.method(); } } class Fu{ int num = 10; public void show(){ System.out.println("Fu...show"); } } class Zi extends Fu{ public void method(){ System.out.println(num); show(); } } 输出如下: