使用父类方法一定要用super吗(写给新人)

今天,在群里有人问(估计是新手)。答案,不一定。只有当子类重写了父类的方法时,如果需要用到父类的方法时,才要用super,表明这个方法时父类的方法不是子类的方法。不理解?上代码:

Father类

public class Father {
	
	public String str = "父类变量";
	
	public String strOnly = "父类变量,子类没有同名变量";
	
	public void printf(String str){
		System.out.println(str+"这是父类的方法");
	}
	
	public void printfOnly(String str){
		System.out.println("这是父类的方法,子类没有重写的方法====>"+str);
	}
}

Son类:

public class Son extends Father{

	public String str = "子类变量";
	
	
	public void printf(String str){
		
		System.out.println(str+"这是子类的方法");
	}
	
	public void test() {
		printf("什么都不使用=======>");
		this.printf("使用this=======>");
		super.printf("使用super=======>");
		printfOnly("子类没重写,就会调用父类的方法");
		
		System.out.println("str is ===========>"+str);
		System.out.println("super.str is ===========>"+super.str);
		System.out.println("子类没有同名变量,就会去找父类的变量 ===========>"+strOnly);
	}
	
	public static void main(String[] args) {
		 Son son = new Son();
		 son.test();	 
	}
	
}

运行结果:

什么都不使用=======>这是子类的方法
使用this=======>这是子类的方法
使用super=======>这是父类的方法
这是父类的方法,子类没有重写的方法====>子类没重写,就会调用父类的方法
str is ===========>子类变量
super.str is ===========>父类变量
子类没有同名变量,就会去找父类的变量 ===========>父类变量,子类没有同名变量


子类重写printf方法,如果需要调用父类的方法就要加super,否则,默认调用子类的方法。对于变量也是一样。


评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值