Java 如何通过子类访问父类变量
我正在尝试重新构建一种面向对象的方法来进行移动验证,由开发人员自行决定。我提出的概念是允许接口操作类。如果类实现了接口,那么将执行verify方法 我面临的问题是,因为我只习惯于用弱类型语言(PHP)编程,如何从扩展当前类的类中获取受保护的变量Java 如何通过子类访问父类变量,java,oop,inheritance,Java,Oop,Inheritance,我正在尝试重新构建一种面向对象的方法来进行移动验证,由开发人员自行决定。我提出的概念是允许接口操作类。如果类实现了接口,那么将执行verify方法 我面临的问题是,因为我只习惯于用弱类型语言(PHP)编程,如何从扩展当前类的类中获取受保护的变量 _areaCodes.stream().forEach(o -> { try { int prefix = Integer.parseInt(this._mobileNumber.charAt(0), this._mobil
_areaCodes.stream().forEach(o -> {
try {
int prefix = Integer.parseInt(this._mobileNumber.charAt(0), this._mobileNumber.charAt(1));
} catch (Exception e) {}
});
这行代码现在给了我一个错误
_mobileNumber无法解析或不是字段
这是我的完整代码,这是我用PHP编写的相同概念,我正试图用Java实现它
import java.util.ArrayList;
interface Verification
{
public void initVerification();
}
class AreaCode
{
private int _code;
private String _country;
public AreaCode(int code, String country)
{
this._code = code;
this._country = country;
}
public int getAreaCode() { return this._code; }
public String getAreaCountry() { return this._country; }
}
class VerificationHandler
{
private ArrayList<AreaCode> _areaCodes = new ArrayList<AreaCode>() {{
this.add(new AreaCode(44, "UNITED KINGDOM"));
this.add(new AreaCode(91, "INDIA"));
}};
public void initVerification()
{
if(this instanceof Verification) {
this.verify();
}
}
protected void verify()
{
_areaCodes.stream().forEach(o -> {
try {
int prefix = Integer.parseInt(this._mobileNumber.charAt(0), this._mobileNumber.charAt(1));
} catch (Exception e) {}
});
}
}
class Main extends VerificationHandler implements Verification {
protected String _mobileNumber = "+447435217761";
}
public class Hack1337 { public static void main(String[] args) { new Main(); } }
只有类
B
的实例或B
的子类可以直接访问B
实例变量(除非将A
强制转换为B
,这是一种不好的做法)
您可以通过重写getB()
,为类A
提供对该值的只读访问权限:
您还可能希望将getB()
方法抽象为类A
(这意味着将类A
抽象化):
只有当
A
的不同子类在getB()
中返回不同的内容时,这才有意义。否则,您也可以将b
变量移动到基类A
感觉我在读C代码,字段不是多态的。如果希望getB()
在子类中返回新值,请在子类中重写它以返回该值。另一方面,\u areaCodes.stream().forEach
只能是\u areaCodes.forEach
。创建流只是为了调用forEach是多余的。@Pshemo感谢您提供的信息!我该怎么做?我意识到Java比我习惯的(来自PHP背景)强类型,所以我认为它不会像使用this
那么简单,我是否必须使用this.getClass.getSubClass()?
@Aomine我很欣赏这些信息,我认为我最初的想法是使用filter()
但最终使用了forEach()
,只是忘了删除流()
,但感谢您指出它在不同语言之间有多么不同,非常感谢您的回答,我现在将尝试实现它!我会尽快标记的。
class A { public String getB() { return this.b; } }
class B extends A { protected String b = 'A should get this'; }
B b = new B().getB();
class B extends A
{
protected String b = 'A should get this';
@Override
public String getB() {
return this.b;
}
}
abstract class A
{
public abstract String getB();
}