this与super的引用

this与super的引用

this

关键字this的两种形势
this

  1. 当类中有多个构造方法时,解释引用变量与参数之间的模糊性。
  2. 当类中有多个构造方法时,用this作为参数传递给另外一个方法。
    下面是this使用的两种情况:
public class BirthDate
{
	private int month = 4;
	private int day = 17;
	private int year = 2020;
	public BirthDate(int y,int m,int d)
	{
		this.year = y;                           // this解释参数的模糊性
		this.month = m;
		this.day = d;
	}
	public BirthDate(BirthDay date)
	{
		this.day = date.day;                     // this解释参数的模糊性
		this.month = date.month;
		this.year = date.year;
	}
	public BirthDate addDays(int add_days)    // 构造方法用this作为参数调用
	{
		BirthDate otherDate = new BirthDate(this);
		otherDate.day = otherDay.day + add_days;
		return otherDate;
	}
}

super

关键字super用于两种情况:

  1. 获取父类中的变量数据和调用父类中的方法。
  2. 直接调用父类的构造方法。
    下面是super使用的情况:
    TestUniversityStudent.java
class Student
{
	string name,department;
	Student(String name,String deparment)       // 定义构造方法
	{
		this.name = name;        //解释参数的模糊性
		this.department = department;
	}
}

class UniversityStudent extends Student   // student的子类
{
	String university;
	UniversityStudent(String name,String deparment,String university)
	{
		super(name,department);    // 直接调用父类的构造方法
		this.umiversity = university   //获取父类变量
	}
}

public class TestUniversityStudent
{
	public static void main(String args[])
	{
		UniversityStudent s = new UniversityStudent("赵四","计算机科学与技术","华南农业大学珠江学院");
		System.out.println("名字"+s.nam+"系"+s.department+"大学"+s.university);
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值