[英]How can a subclass make a variable private when it is protected in superclass?
What is the purpose of subclass to 'privatize' a variable which is protected in superclass? 子类“私有化”一个受超类保护的变量的目的是什么? For example:- 例如:-
abstract public class Creature{
protected String name;
abstract public String getName();
abstract public void setName(String newName);
}
public class Girafee extends Creature {
private String name;
public Girafee() {
}
@Override
public String getName() {
return this.name;
}
@Override
public void setName(String newName) {
this.name = newName;
}
}
You didn't privatize the variable; 你没有将变量私有化; you created the subclass's own variable with the same name. 您创建了具有相同名称的子类自己的变量。 Now your class has two variables with the same simple name and both are accessible: 现在,您的类有两个具有相同简单名称的变量,并且都可以访问:
this.name
vs. 与
((Creature)this).name
They both are completely different instance members. 它们都是完全不同的实例成员。
As per the definition in code , You can access super class variable in child classes and preventing child classes variable to access from out side of its class. 根据代码中的定义,您可以访问子类中的超类变量,并防止子类变量从其类的外部访问。
It's just to confuse people.Though you can, you should avoid having parent/child variables with same name. 这只是让人迷惑。虽然你可以,但你应该避免使用同名的父/子变量。
Your program could also be read as: name
attribute of a creature
is not the same as name
attribute of giraffe
. 你的程序也可以被解读为: name
一个属性creature
是不一样的name
的属性giraffe
。 It's just that they have the same spelling ! 只是他们有相同的拼写!
Well, your examples also points to certain nitty-gitty of data hiding. 那么,你的例子也指出了数据隐藏的某些细节。
Any use of the derived class member name will always refer to the member defined as part of the derived class. 对派生类成员名称的任何使用将始终引用定义为派生类的一部分的成员。 To refer to the base class member, you must qualify it with the keyword super. 要引用基类成员,必须使用关键字super对其进行限定。
public class Base {
protected String s = "Hello Base";
public void get() {
System.out.println("Base string:" + s);
}
public static void main(String[] args) {
Base b = new Base();
b.get();
Derived d = new Derived();
d.get();
((Base) d).get();
Base der = new Derived();
der.get();
}
} }
class Derived extends Base {
protected String s = "Hello Derived";
@Override
public void get() {
System.out.println("Derived String: " + s);
}
} }
Output of the Program: 该计划的产出:
Base string:Hello Base
Derived String: Hello Derived
Derived String: Hello Derived
Derived String: Hello Derived
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.