Home > Java > javaTutorial > body text

How to use the super keyword in Java

WBOY
Release: 2023-05-12 08:28:05
forward
929 people have browsed it

How to use the super keyword in Java

super

super is a keyword, all lowercase.
Super and this are compared and studied. Both "this/super." appears in instance methods, and "this/super()" appears in constructors.
this:
( 1) This can appear in instance methods and constructors.
        (2) The syntax of this is: "this.", "this()"
          (3) This cannot be used in static methods.
          (4) this. This can be omitted in most cases.
(5) this. When can you not omit? It cannot be omitted when distinguishing between local variables and instance variables.

public void setName(String name){
                    this.name = name;
                }
Copy after login

(6) this() can only appear in the first line of the construction method. It uses the current construction method to call other construction methods in "this class" for the purpose of: code reuse!

super:
(1) super can appear in instance methods and constructors.
              (2) The syntax of super is: "super.", "super()"
                (3) Super cannot be used in static methods.
            (4) super. In most cases it can be omitted.
(5) Super. When can't you omit?
              (6) super() can only appear in the first line of the constructor method. It calls the constructor method in the "parent class" through the current constructor method. The purpose is: when creating a subclass object, initialize it first Parent type characteristics.

super()
means calling the constructor of the parent class through the constructor of the subclass.
Simulate this scenario in the real world: if you want to have a son, you need to have a father first.
Important conclusion: When the first line of a constructor method:
There is neither this() nor super(), there will be a super() by default; The constructor calls the parent class's parameterless constructor.
So must ensure that the number of non -parameter constructor of the parent class exists.
Note: this() and super() cannot coexist, they can only appear in the first line of the constructor. No matter how hard you try, the construction method of the parent class will definitely be executed. (100%)

Initial understanding of super

Example 1: Both parent and subclasses are parameterless constructs

public class Test01{
	public static void main(String[] args){
		//根据无参构造方法创建对象,肯定会调用无参构造方法!
        //只要对象创建出来就会调用构造方法,并且先调用父类的构造方法,在调用子类的构造方法
		new B(); 
	}
}

class A{
	public A(){ //无参构造方法
		System.out.println("调用A的无参构造方法!");
	}
}
class B extends A{
	public B(){ //无参构造方法
		//super();//默认这里有一个super()通过子类调用父类的无参构造方法;可省略!
		System.out.println("调用B的无参构造方法!");
	}
}
//结果:我们只创建B对象;结果确实先调用A类的构造方法,才调用B类的构造方法
/*
	调用A的无参构造方法!
	调用B的无参构造方法!
*/
Copy after login

Example 2: The parent class is a parameterized construct, and the subclass is a parameterless construct

The parent class is a parameterized construct, and the subclass is a parameterless construct; if you want a subclass To call the constructor of the parent class, you must write the super keyword and bring the corresponding parameters; only then will the parameterized constructor of the parent class be called!

public class Test01{
	public static void main(String[] args){
		//根据无参构造方法创建对象,肯定会调用无参构造方法!
		new B();
	}
}

class A{
	// 一个类如果没有手动提供任何构造方法,系统会默认提供一个无参数构造方法。
	// 一个类如果手动提供了一个构造方法,那么无参数构造系统将不再提供。
	public A(int i){ //有参构造方法
		System.out.println("调用A的有参构造方法!");
	}
}
class B extends A{
	public B(){ //无参构造方法
		// 父类是有参构造方法,此时默认是是super()就会有问题,
           因为super()只能调用父类无参的无参构造方法
		// 所以此时的super就不能省略;并且写上时要写上参数,
            调用父类的有参构造方法,例如:super(100)
		super(100);
		System.out.println("调用B的无参构造方法!");
	}
}
//结果:我们只创建B对象;结果确实先调用A类的构造方法,才调用B类的构造方法
/*
	调用A的有参构造方法!
	调用B的无参构造方法!
*/
Copy after login

Example 3: this() and super() cannot coexist (key points to understand)

public class Test01{
	public static void main(String[] args){
		//根据无参构造方法创建对象,肯定会调用无参构造方法!
		new B();
	}
}

class A{ //默认继承Object类,class A extends Object
	// 建议手动的将一个类的无参数构造方法写出来。
	public A(){ //无参构造方法
		//这里也默认有super(),调用的是Object的无参构造方法
		System.out.println("调用A的无参构造方法!");
	}
	public A(int i){ //有参构造方法
		//这里也默认有super(),调用的是Object的无参构造方法
		System.out.println("调用A的有参构造方法!");
	}
}
class B extends A{
	public B(){ //无参构造方法
        //通过this去调用B的有参构造方法;而B的有参构造方法默认也有super()!
		this("张三"); 
		System.out.println("调用B的无参构造方法!");
	}
	public B(String name){ //有参构造方法
		//默认也有super(),去调用A的无参构造
		System.out.println("调用B的有参构造方法!");
	}
}
//最终结果
/*
调用A的无参构造方法!
调用B的有参构造方法!
调用B的无参构造方法!
*/
Copy after login

Example 4: Understanding the matryoshka example

In the java language, no matter what object it is, the parameterless constructor of the ancestor's Object class will definitely be executed
. (The parameterless constructor of the Object class is at the "top of the stack")

Characteristics of the top of the stack: it is called last, but execution ends first. Last in, first out principle. Everyone should note:

When writing code in the future, it is recommended that you write the parameterless construction method of a class manually.

If the parameterless constructor is lost, it may affect the "construction of subclass objects".

is the process of pushing and popping the stack: the method that goes in first will be pushed to the bottom of the stack and comes out last; the method that goes in last will be pushed to the top of the stack and comes out first; and because of the super() keyword The reason is that the final parent class must be at the top of the stack and come out first

public class SuperTest02{
	public static void main(String[] args){
		new C();

	}
}
//----------对于父类A实际上也会调用老祖宗Object类的无参构造
/*
class Object{
	public Object(){	
	}
}
*/

class A { //class A extends Object
	public A(){ //-------最后调用的;最先结束!
		System.out.println("1"); //1
	}
}

class B extends A{
	public B(){
		System.out.println("2"); 
	}
	public B(String name){
		//super();默认有
		System.out.println("3"); // 2
	}
}

class C extends B{
	public C(){ // -------最先调用的;最后结束!
		this("zhangsan");
		System.out.println("4");//5
	}
	public C(String name){
		this(name, 20);
		System.out.println("5");//4
	}
	public C(String name, int age){
		super(name);
		System.out.println("6");//3
	}
}
Copy after login

Usage of super (actual parameter)

Use at the right time: super(actual parameter list);

Note: During the execution of the constructor method, a series of calls are made to the constructor method of the parent class, and the constructor method of the parent class continues to call the constructor method of its parent class, but in fact Only one of the above objects is created! Thinking: What does "super(actual parameter)" do?
   

The function of super (actual parameter) is

: Initialize the parent type characteristics of the current object. It does not create new objects. In fact, only 1 object is created.
What does the super keyword stand for? (1) The super keyword represents the parent type characteristics of the "current object"!

(2)我继承了我父亲的一部分特征:
例如:眼睛、皮肤等;super代表的就是“眼睛、皮肤等”。
“眼睛、皮肤等”虽然是继承了父亲的,但这部分是在我身上呢。

public class SuperTest03{
	public static void main(String[] args){

		CreditAccount ca1 = new CreditAccount(); //调用无参构造
		System.out.println(ca1.getActno() + "," +
        ca1.getBalance() + "," + ca1.getCredit()); //null,0.0,0.0

		CreditAccount ca2 = new CreditAccount("1111", 10000.0, 0.999);//调用有参构造
		System.out.println(ca2.getActno() + "," + 
        ca2.getBalance() + "," + ca2.getCredit()); //1111,10000.0,0.999

	}
}

// 账户
class Account extends Object{
	// 属性
	private String actno;
	private double balance;

	// 构造方法
	public Account(){ //对于无参构造,默认会调用super();并且给实列变量赋上缺省初始值
		//super();
		//this.actno = null;
		//this.balance = 0.0;
	}
	public Account(String actno, double balance){
		// super();
		this.actno = actno;
		this.balance = balance;
	}

	// setter and getter
	public void setActno(String actno){
		this.actno = actno;
	}
	public String getActno(){
		return actno;
	}
	public void setBalance(double balance){
		this.balance = balance;
	}
	public double getBalance(){
		return balance;
	}
}

// 信用账户
class CreditAccount extends Account{

	// 属性:信誉度(诚信值)
	// 子类特有的一个特征,父类没有。
	private double credit;

//重点在这里-------------------------------写上有参构造方法
	// 分析以下程序是否存在编译错误????
	public CreditAccount(String actno, double balance, double credit){

		// 直接访问不行,继承过来的私有的属性,只能通过setter和getter方法进行访问
		/*
		this.actno = actno;
		this.balance = balance;
		*/

		// 以上两行代码在恰当的位置,正好可以使用:super(actno, balance);
		// 通过子类的构造方法调用父类的构造方法。
		super(actno, balance); //调用父类的构造方法
		this.credit = credit;
	}


	// 提供无参数的构造方法
	public CreditAccount(){ //对于无参构造,默认会调用super();并且给实列变量赋上缺省初始值

		//super();
		//this.credit = 0.0;
	}

	// setter and getter方法
	public void setCredit(double credit){
		this.credit = credit;
	}
	public double getCredit(){
		return credit;
	}
	
}
Copy after login

内存图(重点掌握)

对于这个内存图,我们要先理解:

(1)要创建CreditAccount对象,调用无参构造方法,默认有super()会调用它的父类Account;Account的无参构造又默认有super()会调用它的父类Object;

(2)根据栈的特点:后进先出,先开辟Object空间、然后开辟Account空间并把里面的实例变量actno和balance进行初始化、最终才开辟CreditAccount对象的空间并把实例变量credit进行初始化;并且有this指向当前对象的地址;有super指向当前对象的父类特征!

How to use the super keyword in Java

super.使用

this表示当前对象。
super表示的是当前对象的父类型特征。(super是this指向的那个对象中的一块空间。)

super和this都不能出现在静态方法中!

public class SuperTest04{
	public static void main(String[] args){
		Vip v = new Vip("张三");
		v.shopping();
	}
}
class Customer{
	String name;
	public Customer(){}
	public Customer(String name){
		super();
		this.name = name;
	}
}
class Vip extends Customer{
	public Vip(){}
	public Vip(String name){
		super(name);
	}
	// super和this都不能出现在静态方法中。
	public void shopping(){
		// this表示当前对象。
		System.out.println(this.name + "正在购物!");
		// super表示的是当前对象的父类型特征。(super是this指向的那个对象中的一块空间。)
		System.out.println(super.name + "正在购物!");
		System.out.println(name + "正在购物!");
	}
}
Copy after login

内存图

this实际上包含着super;this不能使用在static里,所以super更不能!

How to use the super keyword in Java

super.什么时候不能省略(掌握)

“this.”和“super.”大部分情况下都是可以省略的。
this. 什么时候不能省略?

 public void setName(String name){
            this.name = name;
        }
Copy after login

super. 什么时候不能省略
java中允许在子类中出现和父类一样的同名变量/同名属性。
父中有,子中又有,如果想在子中访问“父的特征”,super. 不能省略。

java是怎么来区分子类和父类的同名属性的?
this.name:当前对象的name属性
super.name:当前对象的父类型特征中的name属性。

public class SuperTest05{
	public static void main(String[] args){
		Vip v = new Vip("张三");
		v.shopping();
	}
}

class Customer {
	String name; //-----------------父类中也有name
	public Customer(){}
	public Customer(String name){
		super();
		this.name = name;
	}

	public void doSome(){
		System.out.println(this.name + " do some!");
		System.out.println(name + " do some!");
		//错误: 找不到符号-----Object里面没有name
		//System.out.println(super.name + " do some!");
	}
}

class Vip extends Customer{

	// 假设子类也有一个同名属性
	// java中允许在子类中出现和父类一样的同名变量/同名属性。
	String name; //-----------------子类中也有name

	public Vip(){
	}
	public Vip(String name){
		super(name); //给父类初始化了,子类并没有进行初始化是null
		// this.name = null;
	}
	public void shopping(){
		/*
			java是怎么来区分子类和父类的同名属性的?
				this.name:当前对象的name属性
				super.name:当前对象的父类型特征中的name属性。
		*/
        //----默认访问的是当前对象的name;加super访问的是父类的name
		System.out.println(this.name + "正在购物!"); // null 正在购物
		System.out.println(super.name + "正在购物!"); // 张三正在购物
		System.out.println(name + "正在购物!"); //null 正在购物
	}
}
Copy after login

内存图

How to use the super keyword in Java

super使用时后面必须有一个.

this输出“引用”的时候,会自动调用引用的toString()方法;而super使用后面必须跟一个.,但是super.不是引用,不会自动调用toString()方法!

super 不是引用。super也不保存内存地址,super也不指向任何对象。
super 只是代表当前对象内部的那一块父类型的特征。

this和super都不能使用在static静态方法中。

public class SuperTest06 {

	// 实例方法
	public void doSome(){
		System.out.println(this);//实际上调用的是this.toString()方法
		// 输出“引用”的时候,会自动调用引用的toString()方法。
		//System.out.println(this.toString());

		//编译错误: 需要'.'
		//System.out.println(super);
	}

// this和super不能使用在static静态方法中。
	/*
	public static void doOther(){
		System.out.println(this);
		System.out.println(super.xxx);
	}
	*/

	// 静态方法,主方法
	public static void main(String[] args){
		SuperTest06 st = new SuperTest06();
		st.doSome();

	}
}
Copy after login

使用super调用父类方法

在父和子中有同名的属性,或者说有相同的方法,
如果此时想在子类中访问父中的数据,必须使用“super.”加以区分。

super.属性名 【访问父类的属性】;super.方法名(实参) 【访问父类的方法】;在子类的实例属性/方法当中调用父类的实例属性/方法
super(实参) 【调用父类的构造方法】

public class SuperTest07{
	public static void main(String[] args){
		/*
			Cat move!
			Cat move!
			Animal move!
		*/
		Cat c = new Cat();
		c.yiDong();
	}
}

class Animal{
	public void move(){ //父中有
		System.out.println("Animal move!");
	}
}

class Cat extends Animal{
	// 对move进行重写。
	public void move(){ //子中也有
		System.out.println("Cat move!");
	}

	// 在子类的实例方法当中调用父类的实例方法
	public void yiDong(){
		this.move();//Cat move!---调用自己的
		move();//Cat move!---调用自己的
		// super. 不仅可以访问属性,也可以访问方法。
		super.move();//Animal move!---调用父类的
	}
}
Copy after login

最后小结:super关键字

super can appear in instance methods and constructors.
The syntax of super is: "super.", "super()"
Super cannot be used in static methods.
super. Can be omitted in most cases.
super. When can’t it be omitted?
If there are attributes with the same name in the parent class and the subclass, or the same method, if you want to access the parent class in the subclass, super. cannot be omitted.

super() can only appear in the first line of the constructor method, and uses the current constructor method to call the constructor method in the "parent class" for the purpose of: Create a subclass When using an object, first initialize the parent type characteristics.
Use of super:
                                                                                                  using     using     using                                 ’ ‐ ’ s ’ s ‐ ‐ ‐ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ​ ‐ ​ ​ ​ ​ ​ ​ ​ ​ ​  )super(actual parameter)

[Call the constructor of the parent class]

The above is the detailed content of How to use the super keyword in Java. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!