Loading

Java学习笔记-关键字super

概述

1.super能出现在实例方法和构造方法中,不能使用在静态方法中
2.super的语法: "super."、"super()","super."大部分情况下是可以省略的
3.super() 只能出现在构造方法的第一行 ,表示通过当前的构造方法去调用"父类"中的构造方法,目的是:创建子类对象的时候,先初始化父类型的特征
4.重要结论:
当一个构造方法第一行:

  • 既没有this(),又没有super()的话,默认会有一个super(),表示当前子类的构造方法调用父类的无参数构造方法
  • 子类调用构造方法,一定会先调用父类的构造方法,如果没有显式的写出super(),默认也会调用父类的无参数构造方法,所以,要保证父类的无参数构造方法存在!

例子:

public class SuperTest{
	public static void main(String[] atgs){
		new B();
	}
}
class A{
	public A(){
		System.out.println("A类无参数构造方法");
	}
	
	public A(int i){
		System.out.println("A类有参数构造方法");
	}
	
}
class B extends A{
	//虽然没有super(),但是B类有参数构造方法中有super(),
	//所以子类执行构造方法之前,一定会先执行父类的构造方法
	public B(){
		this("lisi");
		System.out.println("B类无参数构造方法");
	}
	
	public B(String name){
		//super();
		System.out.println("B类有参数构造方法");
	}
}

super.什么时候不能省略?

父中有,子中又有,如果想在子中访问“父的特征”,super.不能省略
java通过this. 和 super. 区分父类和子类的属性.

例子:

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

class Customer{
	String name;
	
	public Customer(){};
	public Customer(String name){
		this.name = name;
	}
}

class Vip extends Customer{
	//假设子类也有一个同名属性,在java中是允许的
	String name;   
	int age;
	
	public Vip(){};
	public Vip(String name){
		super(name);
		//this.name = null;
	}
	public void shopping(){
		System.out.println(this.name + "is shopping");
		System.out.println(super.name + "is shopping");
		System.out.println(name + "is shopping");	
	}
}

内存图:

super 不是引用

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

public class SuperTest{
	
	public void doSome(){
		//this是一个引用
		System.out.println(this);
	
		//编译错误:需要'.'
		System.out.println(super);
	}	
	public static void main(String[] args){
		SuperTest st = new SuperTest();
		st.doSome();
	}
}

super.不仅可以访问属性,也可以访问方法

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

class Cat extends Animal{
	//方法覆盖
	public void move(){
		System.out.println("Cat move!");
	}
	
	public void yiDong(){
		this.move();
		move();
		super.move();
	}
}

public class SuperTest{
	public static void main(String[] args){
		Cat c = new Cat();
		c.yiDong();
	}
}

posted @ 2020-04-15 12:18  Krocz  阅读(146)  评论(0编辑  收藏  举报