JAVA进阶版:super

文章目录

(1) super1

  • 1.super不是引用类型,super中存储的不是内存地址,super指向的不是父类对象。
  • 2.super代表的是当前子类对象中的父类型特征。
  • 3.什么时候使用super?
    –子类和父类中都有某个数据,例如,子类和父类中都有name这个属性。
    –如果要再子类中访问父类中的name属性,需要使用super.
  • 4.super可以用在什么地方?
    –super可以用在成员方法中,super. 不能用在静态方法中
    –super可以用在构造方法中,super();
package javase.jingjie.Super;
public class Manger extends Employee {
	String name="李四";
	//子类将父类中的work方法重写
	public void work() {
		System.out.println("经理在工作!");
	}
	//成员方法
	public void m1() {
		this.work();//经理在工作!,引用.调用work
		work();//经理在工作!
		super.work();//员工在工作!,在子类中访问父类中的方法
		System.out.println(this.name);//李四
		System.out.println(name);//李四
		System.out.println(super.name);//张三,在子类中访问父类中的name属性。
	}
	/*静态方法不能用,super和this都不能用在静态方法中
	 * public static void m2() { 
	 * System.out.println(super.name);
	 *  }
	 */
}
结果:经理在工作!
经理在工作!
员工在工作!
李四
李四
张三

Employee

package javase.jingjie.Super;
public class Employee {
	String name="张三";
	public void work() {
		System.out.println("员工在工作!");
	}
}
package javase.jingjie.Super;
public class Test01 {
	public static void main(String[] args) {
		Manger c=new Manger();
		c.m1();
	}
}

(2) super2

  • 1.super关键词用在构造方法中:语法是 super(实参);
  • 2.作用:构造方法不能被继承,但是可以通过子类的构造方法去调用父类的构造方法;
  • 3.语法规则:一个构造方法第一行如果没有this(…),也没有显示的去调用super(…),系统会默认调用无参super();
  • 4.注意:–super(…)的调用只能放在构造方法的第一行;
    –super(…)和this(…)不能共存;
    –super(…)也是一种构造方法,调用了父类中的构造方法,但不会创建父类对象;
    –在java语言中只要创建Java对象,那么object中的无参构造方法一定会执行。
  • 5.单例模式缺点:单例模式的类型没有子类,无法被继承。
package javase.jingjie.Super02;
public class DebitAccount extends Account {
	private double debit;
	/*
	 * public DebitAccount() { 
	 * super();//这可以省略 ,调用父类Account中的无参数构造方法
	 * }
	 */
	/* public DebitAccount() {} */	
	//创建子类DebitAccount()无参构造方法,而此方法包含的super(实参)就是调用父类Account有参构造方法
	public DebitAccount() {
		super("001",120.3);//调用父类Account中的有参数构造方法
	}
	//setter and getter
	public double getDebit() {
		return debit;
	}
	public void setDebit(double debit) {
		this.debit = debit;
	}	
}
package javase.jingjie.Super02;

public class Account {
	private String actno;
	private double balance;
	//构造方法
	public Account() {
		System.out.println("Account的无参数构造方法执行!");
	}
	public Account(String actno, double balance) {
		this.actno = actno;
		this.balance = balance;
		System.out.println(actno+" "+balance);
	}
	//setter and getter
	public String getActno() {
		return actno;
	}
	public void setActno(String actno) {
		this.actno = actno;
	}
	public double getBalance() {
		return balance;
	}
	public void setBalance(double balance) {
		this.balance = balance;
	}
}
package javase.jingjie.Super02;

public class Test02 {
	public static void main(String[] args) {
		DebitAccount da=new DebitAccount();
	}
}
发布了71 篇原创文章 · 获赞 10 · 访问量 3412

猜你喜欢

转载自blog.csdn.net/JH39456194/article/details/104083255