📜  Java |类和对象|问题4

📅  最后修改于: 2021-06-28 23:43:25             🧑  作者: Mango

class demo
{
    int a, b;
      
    demo()
    {
        a = 10;
        b = 20;
    }
      
    public void print()
    {
        System.out.println ("a = " + a + " b = " + b + "\n");
    }
}
  
class Test
{
  
    public static void main(String[] args)
    {
        demo obj1 = new demo();
        demo obj2 = obj1;
  
        obj1.a += 1;
        obj1.b += 1;
  
        System.out.println ("values of obj1 : ");
        obj1.print();
        System.out.println ("values of obj2 : ");
        obj2.print();
  
    }
}

(一)编译错误
(B)

values of obj1: 
a = 11 b = 21
values of obj2: 
a = 11 b = 21

(C)

values of obj1: 
a = 11 b = 21
values of obj2: 
a = 10 b = 20

(D)

values of obj1: 
a = 11 b = 20
values of obj2: 
a = 10 b = 21

(E)运行时错误答案: (B)
说明:将obj2分配给obj1会使obj2成为对obj1的引用。因此,obj1中的任何更改也将反映在obj2中。
这个问题的测验
如果您在以上帖子中发现任何错误,请在下面发表评论