Java中的this和super与JS的this和super

Java的this 表示new实例化的时候当前的对象,使用this可以调用本类中的属性,使用this可以调用构造方法

没有构造方法系统生成默认的无参数构造方法,有构造方法的时候系统不会生成默认的构造方法

public class People {

	// 定义属性 
	private String name; // 实例化对象的时候,默认值是null
	private int age; // 实例化对象的时候,默认值是0
	
	/**
	 * 默认的构造方法
	 */
	public People(){
		System.out.println("默认构造方法");
	}
	
	/**
	 * 有参数的构造方法
	 * @param name2
	 * @param age2
	 */
	People(String name,int age){
		this();// 调用无参数的构造方法
		System.out.println("调用的是有参数的构造方法");
		this.name=name;
		this.age=age;
	}
	

Java的super在继承中,能继承私有属性但是不能继承私有方法

super调用父类属性与方法

super()调用父类无参的构造方法,super(name,age)调用父类有参的构造方法,可以父类的私有属性作为父类有参构造方法的参数使用,不然没法构造。

 public class Animal {

	private String name; // 名字
	private int age; // 年龄
	
	/**
	 * 无参父类构造方法
	 */
	public Animal(){
		System.out.println("无参父类构造方法");
	}
	
public class Cat extends Animal{

	private String address;
	
	
	
	public String getAddress() {
		return address;
	}

	public void setAddress(String address) {
		this.address = address;
	}

	/**
	 * 子类无参构造方法
	 */
	public Cat(){
		super();
		System.out.println("子类无参构造方法");
	}
	
	/**
	 * 子类有参数构造方法
	 * @param name
	 * @param age
	 */
	public Cat(String name,int age,String address){
		super(name,age);
		this.address=address;
		System.out.println("子类有参数构造方法");
	}
	
	
	/**
	 * 重写父类的say方法
	 */
	public void say(){
		super.say();
        super.a;
		System.out.println("我是一只猫,我叫:"+this.getName()+",我的年龄是:"+this.getAge()+",我的地址是:"+this.getAddress());
	}

猜你喜欢

转载自blog.csdn.net/qq_35029061/article/details/81256556