java学习笔记36

面向对象

super详解

子类调用父类的方法与属性

package oopzong.oop.oop4;

public class Application {
   public static void main(String[] args) {
       Student student = new Student();
       student.test("父慈子孝");

  }
}


public class Person {
  protected String name = "woshinidie";
}


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

   public void test(String name){
       System.out.println(name);
       System.out.println(this.name);
       System.out.println(super.name);
  }

}

父慈子孝
woshinier
woshinidie

 

package oopzong.oop.oop4;

public class Application {
   public static void main(String[] args) {
       Student student = new Student();
       student.test1();

  }
}



public class Person {

  public void print(){
      System.out.println("Person");
  }
}



public class Student extends Person {
   public void print(){
       System.out.println("Student");
  }
   public void test1(){
      print();
      this.print();
      super.print();
  }

}

Student
Student
Person

 

super构造器的调用

package oopzong.oop.oop4;

public class Application {
   public static void main(String[] args) {
       Student student = new Student();
  }
}


public class Person {

   public Person() {
       System.out.println("Person无参执行了");
  }//必须要有无参构造,如果父类没有子类也无法写,父类是有参构造,子类也只能调用有参构造
}



public class Student extends Person {

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

Person无参执行了
Student无参执行了

super注意点:

1.super调用父类的构造方法,必须在构造方法的第一个

2.super必须只能出现在子类的方法或者构造方法中!

3.super 和 this 不能同时调用构造方法!

 

对比 this:

代表的对象不同:

this: 本身调用着这个对象

super:代表父类对象的应用

前提

this:没有继承也可以使用

super:只能在继承条件下才可以使用

构造方法

this();本类的构造

super();父类的构造

posted @ 2022-10-16 13:55  新人用户  阅读(21)  评论(0)    收藏  举报