class_8:java继承
package jicheng.hcc.java;class Person{int age;String address;String name;public void eat(){System.out.println("人吃饭");}public void drink(){System.out.println("人喝水");} public void printInfo(){System.out.println("name= " + name);}}
class Student extends Person{public void goshcool(){System.out.println("学生上学");}
}public class Test {public static void main(String[] args) {Person p = new Person();p.eat();p.drink();Student s = new Student();s.eat();s.drink();s.name = "hcc";s.printInfo();}
}
super关键字:调用父类的构造,或者调用父类的同名函数,当名字相同时,默认调用子类的
this是对该类进行解引用,super是对父类进行解引用
super()//父类构造
super.age//父类变量
package jicheng.hcc.java;class Person{int age;String address;String name;public void eat(){System.out.println("人吃饭");}public void drink(){System.out.println("人喝水");} public void printInfo(){System.out.println("name= " + name);}Person(String address,String name){this.address = address;this.name = name;System.out.println("父类构造方法被调用");}
}
class Student extends Person{Student(String address,String name){super(address,name);//调用父类的构造方法初始化System.out.println("子类构造方法被调用");}public void goshcool(){System.out.println("学生上学");} public void eat(){super.eat();//调用父类的eatSystem.out.println("学生吃饭");}
}public class Test {public static void main(String[] args) {Person p = new Person("18号","hcc");p.eat();p.drink();p.printInfo();Student s = new Student("19号","wang");s.eat();s.drink();s.printInfo();s.eat();}
}
继承权限:私有变量不可以继承