[英]How to access parent class variable in child class inside a child method?
I have a class 我上课了
public class A {
private String name;
public void setName(String name){
this.name = name;
}
public string getName(){return name;}
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append(name).append(", ");
return builder.toString();
}
}
I have a child class B that extends A and I have to access name from A in toString method in B. I have written the following code but not sure if this a good practice? 我有一个扩展A的子类B,我必须在B中的toString方法中访问A中的名称。我已经编写了以下代码但不确定这是否是一个好习惯?
public class B extends A {
private String gender;
public void setGender(String gender){
this.gender = gender;
}
public string getGender(){return gender;}
@Override
public String toString() {
c = new A();
StringBuilder builder = new StringBuilder();
builder.append(c.getName()).append(", ");
builder.append(gender).append(", ");
return builder.toString();
}
}
EDIT: If I cannot access private String name in class B, do I have to @Override setName()
by using super.setName(name)
? 编辑:如果我不能访问类B中的私有String名称,我是否必须使用
super.setName(name)
来@Override setName()
super.setName(name)
? In that case how different it is from using class B without extending class A if I dont want to use any of the objects of A? 在那种情况下,如果我不想使用A的任何对象,那么在不扩展A类的情况下使用B类有何不同?
I just started using JAVA to modify a service. 我刚开始使用JAVA来修改服务。
When you inherit a class, you also inherit all the public and protected methods and variables from the inherited. 继承类时,还会继承继承的所有公共和受保护方法和变量。 So you can just do
所以你可以做到
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append(this.getName()).append(", ");
builder.append(this.getGender()).append(", ");
return builder.toString();
}
simply by calling getName()
in your toString method or super.getName()
只需在toString方法或
super.getName()
调用getName()
即可
like: 喜欢:
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append(getName()).append(", ");
builder.append(gender).append(", ");
return builder.toString();
}
Never forget the old adage: You don't inherit your parent's privates. 永远不要忘记古老的格言: 你不会继承父母的私生子。
If you want B
to have access to A.name
, you have a couple of options: 如果您希望
B
有权访问A.name
,您有几个选择:
name
to be either public
(bad) or protected
(better) in A
. A
中将name
更改为public
(坏)或protected
(更好)。 name
through A
's setters and getters, eg this.getName()
A
的setter和getter访问name
,例如this.getName()
What you've currently done just returns the default value of A.name
and not the value of name that actually belongs to your instance of B
. 您当前所做的只是返回默认值
A.name
而不是实际属于您的B
实例的名称值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.