在Java中,未命名类可以访问其外部类的成员,但是在不同的子类之间,未命名类的访问规则类似于其他成员一样。具体来说,未命名类只能访问其所在的子类中的成员,而无法访问其他子类的成员。
以下是一个示例代码,说明如何在不同的子类之间使用未命名类的访问规则:
public abstract class Parent {
private int parentVar = 0;
public void accessVars() {
// Accessing parentVar from an unnamed class in the same subclass
Object anonClass = new Object() {
public void accessParentVar() {
System.out.println("accessing parentVar: " + parentVar);
}
};
((Object) anonClass).accessParentVar(); // must cast to Object to call the method
}
// abstract method that will be implemented by both child classes
public abstract void childAccessVars();
}
public class ChildOne extends Parent {
private int childOneVar = 1;
@Override
public void childAccessVars() {
// Accessing childOneVar from an unnamed class in this subclass
Object anonClass = new Object() {
public void accessChildOneVar() {
System.out.println("accessing childOneVar: " + childOneVar);
}
};
((Object) anonClass).accessChildOneVar();
}
}
public class ChildTwo extends Parent {
private int childTwoVar = 2;
@Override
public void childAccessVars() {
// Accessing childTwoVar from an unnamed class in this subclass
Object anonClass = new Object() {
public void accessChildTwoVar() {
System.out.println("accessing childTwoVar: " + childTwoVar);
}
};
((Object) anonClass).accessChildTwoVar();
}
}
public class Main {
public static void main(String[] args) {
Parent child1 = new ChildOne();
Parent child2 = new ChildTwo();
child1.accessVars();
上一篇:不同子集的分类变量表格
下一篇:不同子模块分支的Git合并策略