【问题标题】:The Object class is the parent class of all the classes in java by defaultObject类默认是java中所有类的父类
【发布时间】:2023-03-28 15:06:01
【问题描述】:

为什么引用类型对象 o 不能访问变量 a。它显示错误无法解决或不是字段。

public class test2 {
int a;

public static void main(String args[]) {
    Object o = new test2();
    test2 t = new test2();
    t.a = 0;
    o.a = 10;


}
}

【问题讨论】:

标签: java


【解决方案1】:

基本上,您会混淆引用类型和实例(对象)类型。

在您的程序中,o 是类型为Object 的引用变量,因此o 将只能访问Object 类中的方法和变量。 另外,ttest2 类型的引用变量,所以t 可以访问test2 的类成员。您可以查看here了解更多详情。

简而言之,引用类型决定了您可以访问类的哪些成员。

此外,请查看以下流行的继承类以了解上述概念:

public class Animal {
   public String foodtype;
   //other members
}

public class Dog extends Animal {
   public String name;
   //other members
}

public class Test {

   public static void main(String[] args) {
        Animal a = new Dog();//'a' can access Anmial class members only
        a.foodtype = "meat"; //ok
        a.name = "puppy"; //compiler error

        Dog d = new Dog();//'d' can access both Animal and Dog class members
        d.foodtype = "meat"; //ok
        d.name = "puppy";//ok
   }
}

【讨论】:

    【解决方案2】:

    在 Java 中,您不能仅通过分配字段来创建字段。您还必须在代码中声明它们:

    public class test2 {
        int a;
        ...
    }
    

    即使这样,如果你将一个变量声明为一个对象,那是一个真正的“test2”实例,你仍然无法在不先强制转换的情况下访问字段“a”。

    Object o = new test2();
    o.a = 5  // compile error
    test2 t = (test2)o;
    t.a = 5 // ok. Will compile fine
    

    Java 编译器使事情变得相当简单,这意味着它不会很难判断“o”是否真的是一个 test2,它只是使用声明的类来确定哪些字段和方法是可访问的。

    【讨论】:

      猜你喜欢
      • 2013-06-15
      • 2015-01-31
      • 1970-01-01
      • 2016-10-01
      • 2021-10-21
      • 1970-01-01
      • 2012-05-03
      • 2015-11-14
      相关资源
      最近更新 更多