继承

Super

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

  2. super只能出现在子类构造方法或子类方法中

  3. super和this只能有一个出现在构造方法中

this 本身调用者这个对象

super 代表父类对象的应用

package oop.demo5;

public class Test {
  public static void main(String[] args) {
      Student student=new Student();
      student.setName("book");
      student.showName();
  }
package oop.demo5;

public class Person {
  public Person() {
      super();
      //隐藏代码,调用父类的无参构造
      System.out.println("父类无参");
  }

  private String name;

  public String getName() {
      return name;
  }

  public void setName(String name) {
      this.name = name;
  }
}
package oop.demo5;

public class Student extends Person{
  public Student() {
      System.out.println("子类无参");
  }

  private String name="name";
  public void showName(){
      System.out.println(this.name);
      System.out.println(super.getName());
      name="book2";
      System.out.println(this.name);
  }
}

重写

  1. 方法名,参数列表必须相同

  2. 修饰符,范围可以扩大,但不能缩小

  3. 异常,范围可以缩小,但不能扩大

package oop.demo6;

public class Demo6 {
  public static void main(String[] args) {
      B a=new A();
      A a1=new A();
      a.show();//A
      a1.show();//B
  }
}

class A extends B {
  public void show(){
      System.out.println("A");
  }
}
class B{
  public void show(){
      System.out.println("B");
  }

}
package oop.demo6;

public class Demo6_2 {
  public static void main(String[] args) {
      C a=new C();
      D a1=new C();
      a.show();//A
      a1.show();//B
  }
}

class C extends D {
  static public void show(){
      System.out.println("A");
  }
}
class D{
  static public void show(){
      System.out.println("B");
  }

}

 

posted @ 2021-10-08 17:29  clown-lan  阅读(24)  评论(0)    收藏  举报