B obj2 = new B(); obj2.i = 1; obj2.j = 2; A r; r = obj2; r.display();
时间: 2024-02-15 21:32:26 浏览: 98
obj2mat.rar_.obj文件_obj_obj matlab_obj 转mat_obj格式文件
5星 · 资源好评率100%
Assuming that class A and class B are defined as follows:
```
class A {
public int i;
public void display() {
System.out.println("i = " + i);
}
}
class B extends A {
public int j;
public void display() {
System.out.println("i = " + i + ", j = " + j);
}
}
```
The output of the code will be "i = 1, j = 2".
Explanation:
- An object of class B is created and its fields i and j are initialized to 1 and 2 respectively.
- A new reference variable r of type A is declared.
- The object of class B is assigned to r. This is possible because class B extends class A, so a B object can be treated as an A object (this is called upcasting).
- The display method of class B is invoked through the reference variable r. Since r refers to a B object, the overridden display method in class B is called and it prints both i and j fields.
阅读全文