Java 转型 super的用法回顾

来源:互联网 发布:网络刺客ii使用教程 编辑:程序博客网 时间:2024/04/30 06:23
class Person{String name;int age;public  Person(){System.out.println("Person 的无参数构造函数");}public Person(String name,int age){this.name=name;this.age=age;System.out.println("Person 有参数的构造函数");}void intorduce(){System.out.println("我的名字叫:"+name+","+"我的年龄是:"+age);}}//1.intorduce()就是重写或者复写父类的方法(override) 1>在子类和父类中函数名和参数以及返回类型完全相同,称之为函数的复写。//2. super的用法:1>调用父类的方法 2.调用父类的构造方法。class Student extends Person{String adress;public Student(){    super();//子类必须要调用父类的构造函数super(),不写super(), 系统会自动的编写这句话。为什么这么写?答:子类继承父类,但是不能继承父类的构造函数。可能存在重复代码,为了解决重复代码,所以必须要调用父类的构造函数super()由此而来。super()必须是构造函数的第一句。System.out.println("Student 无参数的构造函数");}public Student(String name,int age,String adress){//this.name=name;//this.age=age;super(name,age);this.adress=adress;}void intorduce(){System.out.println("我的家在:"+adress);super.intorduce();//调用父类的方法,避免重复代码。}void read(){System.out.println("-------------读书");}}class Test{public static void main(String args[]){Student student=new Student("张三",44,"北京");Person person=student;//向上转型。==Person person=new Student();//person.adress="上海";一个引用能够调用那些成员(变量或者是函数),取决于引用的类型。person.intorduce();//之所以能调用是因为子类复写了父类的方法。实际上是父类的方法。//person.read();一个引用能够调用哪一个方法,取决于这个引用所指向的对象。//-----------------------------------------------------------向下转型Student s1=new Student();Person person=student;Student s2=(Student)person;}}