super

1、 在继承中

super关键字可用来实现对父类成员的访问,用来引用当前对象的父类

class Animal {
  void eat() {
    System.out.println("animal : eat");
  }
}
 
class Dog extends Animal {
  void eat() {
    System.out.println("dog : eat");
  }
  void eatTest() {
    this.eat();   // this 调用自己的方法
    super.eat();  // super 调用父类方法
  }
}
 
public class Test {
  public static void main(String[] args) {
    Animal a = new Animal();
    a.eat();//animal:eat
    Dog d = new Dog();
    d.eatTest();//dog:eat            animal:eat
  }
}

2、在构造器中

如下代码中

 class A{
	public A(){
		System.out.println("A");
	}
}
 class B extends A{
	public B(String str) {
		System.out.println("B");
	}
}
class C extends B{
	public C(String str) {
		System.out.println("this is C");
	}
}
public class Contest001 {
	public static void main(String[] args) {
		C c=new C("hello");
	}
}

在这里public C(String str)会报错:

Implicit super constructor B() is undefined. Must explicitly invoke another

意为找不到B()构造器,必须显式调用另一个。即不能构造类B的实例,没有找到合适的构造器。
这是JAVA编译器的一种机制。当继承存在时,在生成子类的实例时,子类会自动的去调动父类的无参数构造器。
这时需要使用super语法,在类C的构造器中加上super(str),明确告诉编译器,调用的是父类中带有参数的构造器。

 class A{
	public A(){
		System.out.println("A");
	}
}
 class B extends A{
	public B(String str) {
		System.out.println("B");
	}
}
class C extends B{
	public C(String str) {
		super(str);
		System.out.println("this is C");
	}
}
public class Contest001 {
	
	public static void main(String[] args) {
		C c=new C("hello");
	}
}

在这里插入图片描述
由此可见,在某些情况下子类的构造器中必须要有super语法。
如果不指定子类调用构造器的形式,编译器会自动寻找父类中默认的构造器,以实现继承的上溯

3、在构造方法中

在构造器的使用中,如果没有自定义构造器,编译器会自动添加一个默认的空构造,但如果有自定义构造器,编译器将不会提供默认的空构造器,这时需要自定义一个空的构造器,构造器中写super();即可使用空构造和除有参数构造器外的其他方法。

class Animal {
	private String name;
	private int id;
	  void eat() {
	    System.out.println("animal : eat");
	  }
	  public Animal(String name,int id) {
		  this.name=name;
		  this.id=id;	  
	  }
	  public Animal() {
		  super();
	  }
	  void print() {
		  System.out.println("name:  "+name+"    id:  "+id);
	  }
	}
	 
	class Dog extends Animal {
		public Dog(String name,int id) {
		super(name,id);
		}
	  void eat() {
	    System.out.println("dog : eat");
	  }
	  void eatTest() {
	    this.eat();   // this 调用自己的方法
	    super.eat();  // super 调用父类方法
	  }
	 public Dog() {
		  super();
	  }
	}
	public class Contest001 {
	  public static void main(String[] args) {
	    Animal a = new Animal();
	    Animal b=new Animal("animal",1);
	    b.print();//name:  animal    id:  1
	    a.eat();//animal:eat
	    Dog c=new Dog("dog ",2);
	    c.print();//name:  dog     id:  2
	    Dog d = new Dog();
	    d.eatTest();//dog:eat            animal:eat
	  }
	}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值