java - java中的对象引用和类型转换

标签 java

class A{
    int foo=10;
}
class B extends A{
    int foo=10;
}
class Test{
    public static void main(String [] args){
         A a=new B();
         System.out.println(a.foo);
         //System.out.println(a.getClass());
     }
}

在本例中输出10。如果我没记错的话,这是因为 a 变量的类型为 A 并且变量赋值是静态绑定(bind),而静态绑定(bind)是在编译时通过查看变量的类型。由于这里 a 的类型为 A,因此 Aint foo 被调用。但是当我打电话时

System.out.println(a.getClass());

然后这给出了类B,即a的类型为B。我对此很困惑。请向我解释一下 a 是什么类型以及 Aint foo 是如何打印的。 但是通过查看这段代码

class A{}

class B extends A{}

class Test{
    public static void main(String [] args){
        B b=new B();
        A a=b;
        B b1=(B)a; // compiles and run fine (a is of type B)
    }
}

这怎么可能?这里发生了什么事?第一个 bB 类型,然后在第二行 a 变成 A 类型,如 A a=.. 被写入,但 a.getClass() 表明它是 B 类型。如何?如果 aB 类型,那么为什么它在第一个示例中调用 Aint foo ?请解释这两个例子。

此外,类型转换是否会更改引用或执行任何其他操作?

最佳答案

要认识到的重要一点是,Java 只有原始变量类型和引用变量类型。这意味着当你写

A a =

a 只是对对象(或 null)的引用,而不是对象。

当你这样做时

A a = new B();

这里没有任何转换,没有完成任何工作,没有任何对象受到伤害或改变。<​​/p>

当您调用类的实例方法时,它会调用该对象的类的方法。

Object o = new B();
assert o.getClass() == B.class;

一个更长的例子

B b = new B();
A a = b;
assert a == b; // always true as they point to the same object.
assert b.getClass() == B.class;
// so it makes sense that since a == b
assert a.getClass() == B.class;

type casting change references or do any other stuff?

它更改引用的类型,但不会执行其他操作,例如更改对象的类型。

方法遵循继承,但是字段遵循引用的类型,因为字段不能被覆盖,只能隐藏。

B b=new B(); A x=b; B b1=(B)x; // compiles and run fine (x is of type b) in this line when x is of which type

正确,您将无法(B)x,除非x是对B的引用变量 x 是一个 A,这意味着它必须指向 A 对象或 A 的子类,例如B你可以写

B b = new B(); 
A x = b;
assert x == b; // they still point to the same object.
B b1 = (B) x;
assert b1 == b; // same object
assert x == b1; // same object.

没有创建新对象,也没有更改对象。

关于java - java中的对象引用和类型转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36029310/

相关文章:

java - activemq 和 Glassfish : InactivityIOException: Channel was inactive for too long

Java - BufferedWriter.write() 和 System.out.println() 的区别?

java - java中.equals和==的区别(内存内)

继承

java - 在同一 session 中更改实体管理器数据源

java - JTable 和 JButton

java - ArrayList中的对象正在改变

java - 使用 Java 连接到 MySQL

java - 在 ExpandableListView 中拥有多个 TextView 时遇到问题

java - 这与 Groovy 中的静态