【问题标题】:can we not access the anonymous class data members if they are not declared in parent one?如果匿名类数据成员没有在父类中声明,我们可以不访问它们吗?
【发布时间】:2019-04-08 01:14:38
【问题描述】:
class Parent{
  String h;
  Parent(String s){
    h = s;
  }
}
public class Child{ 
public static void main(String args[]){
   Parent p = new Parent("fcghj"){          // anonymous class
            private int y = 9;
  };
  System.out.println(p.h);
  System.out.println(p.y);              // error
}
}

错误显示:在 Parent 中找不到符号 y

如果y没有在Parent类中声明,有什么方法可以在匿名类之外访问?

我们是否只能为了匿名类中的重载、隐藏和覆盖而声明父类中存在的那些字段和方法?

【问题讨论】:

  • 1.如您所见,不,您无法从外部访问 y 。 2. 如您所见,编译器允许您声明 y,并且 y 不会重载、覆盖或隐藏任何内容。
  • @JBNizet : 只是好奇,既然我们创建了一个对象p,我们不应该能够使用该对象访问y吗?
  • 否,因为变量的声明类型是Parent,而Parent没有任何名为y的成员字段。这不仅限于匿名类。如果使用Object p = new Point(1, 2),则不能使用p.x和p.y,因为变量p的声明类型是Object,而不是Point。
  • 谢谢。但只是想,因为我们正在创建 Parent 本身的对象(通过匿名类),所以我觉得可以访问它。

标签: java oop anonymous-class


【解决方案1】:

匿名代码保持匿名如果没有赋值,也可以把它看成简单的块,至于初始化块你不希望得到外面的值:

public class Child { 

  {          // initialize block
            int y = 9;
  }
public static void main(String args[]){
   Parent p = new Parent("fcghj");
  System.out.println(p.h);
  System.out.println(y);              // error
}

您可以更改/添加带有 int 参数的 Parent 构造函数以便以后使用它

class Parent{
  String h;
  int y;
  Parent(String s, int y){
    h = s;
    this.y = y;
  }

【讨论】:

    猜你喜欢
    • 2014-09-30
    • 2019-04-08
    • 2014-08-26
    • 1970-01-01
    • 2018-08-25
    • 2017-04-11
    • 2020-12-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多