继承和super的使用及注意

//父类
package oop.demo06;

public class Person {
    protected String name="daxing";
    public Person() {
        System.out.println("Person无参执行了");
    }
    public void print(){
        System.out.println("Person");
    }
    //private修饰的无法被继承
    //注意:           父类如果没有无参构造,则子类也不能有无参构造;否则会报错

}

//子类
package oop.demo06;

public class Student extends Person {
    private String name="bigstar";

    public Student() {
        //这里隐藏代码:super();调用了父类的无参构造
        super();//调用父类的无参构造,必须要子啊子类的构造无参构造的第一行
        System.out.println("Student无参执行了");

    }

    public void print(){
        System.out.println("Student");
    }
    public void test1(){
        print();//在main函数中调用时输出当前类print方法打印 Student
        this.print();//在main函数中调用时输出当前类print方法打印 Student
        super.print();//。。。。。输出父类print方法打印的Person
    }



    public void test(String name){
        System.out.println(name);//输出传递的参数“大鑫”
        System.out.println(this.name);//输出这个类的 bigstar
        System.out.println(super.name);//输出父类的 daxing

    }

}

//测试的执行代码
package oop.demo06;

public class Application {
    //this 和 super关键字的用法

    public static void main(String[] args) {
        Student student = new Student();
//        student.test("大鑫");
//        student.test1();
    }
}

//笔记和注意
super注意点:
        1.super调用父类的构造方法,必须在构造方法的第一行
        2.super只能出现在子类的方法或子类的构造方法中
        3.super和this不能同时调用构造方法

对比this:
       代表的对象不同:
              this:本身调用者这个对象
              super:代表父类对象的应用
       前提:
              this:没有继承也可以使用
              super:只能在继承条件下才可以使用
       构造方法:
              this:本类的构造
              super:父类的构造

       注意点:
           父类如果没有无参构造,则子类也不能有无参构造;否则会报错

 

posted @ 2022-02-04 16:02  狂神大鑫  阅读(49)  评论(0)    收藏  举报