在java中使用super关键字继承变量 [英] Inheriting a variable using super keyword in java

查看:70
本文介绍了在java中使用super关键字继承变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class Person
{
	String name;
	Person()
	{	
	}
	Person(String name)
	{
		this.name=name;
	}
}
class Employee extends Person
{
	void getdetails()
	{
		System.out.println("Name : "+super.name);
	}
}
class DoubtInSuper
{
	public static void main(String arr[])
	{
		Person p=new Person("Virat");
		Employee e=new Employee();
		e.getdetails();
	}
}





我的尝试:



以上程序的输出是 -

名称:null



What I have tried:

Output of the above Program is -
Name : null

推荐答案

麻烦的是你在这里创建了两个独立的实例: p 是一个实例,它是一个Person, e 是第二个单独的实例,以及它的'员工'。这两个实例没有以任何方式加入,因此 p 的情况不会发生在 e

想想看:你买了一辆车,把你的手机放在手套箱里。我给你搭乘我的梅赛德斯(延伸汽车,福特,布加迪和凯迪拉克等) - 您希望在我的手套箱中找到您的手机吗?
The trouble is that you have created two separate instances here: p is one instance, and it's a Person, e is a second separate instance, and its' an Employee. The two instances are not "joined" in any way, so what happens to p does not happen to e.
Think about it: you buy a Car, and put your mobile in the glove box. I give you a ride in my Mercedes (which extends Car, as does Ford, Bugatti, and Cadillac) - would you expect to find your mobile in my glove box?


这篇关于在java中使用super关键字继承变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆