第一题:
public class Demo {
public static void main(String[] args) {
Base b = new SubClass();
System.out.println(b.x);
System.out.println(b.method());
}
}
class Base {
int x = 2;
int method() {
return x;
}
}
class SubClass extends Base {
int x = 3;
int method() {
return x;
}
}
首先给出答案 2
3
解析:
#1. 一个类的引用变量只能指向它本身的成员变量和继承自父类的成员,所以b.x指向的就是父类的x。在这种情况下,可以通过修改变量名的方法来进行判断。
将父类Base中的x替换成str,然后你会发现在编译器中的打印语句System.out.println(b.?)这个?只能写str,不能写x。会出现编译错误。所以这个主方法中b.x就是指向父类的x.
#2.b.method之所以会调用子类的方法,注意重写的含义是“覆盖”,通过new出来的子类对象调用的方法就是子类重写的方法,所以会打印3.
第二题:
public class Test2 {
public static void main(String[] args) {
S2 s2 = new S2();
s2.display();
}
}
class S1 {
String s = "S1";
public void display() {
System.out.println(s);
}
}
class S2 extends S1 {
String s = "S2";
}
首先给出答案(S1)
解析:
首先第一步,修改变量名。
class S1{
String str="S1";
public void display(){
System.out.println(str);
}
}
当S2继承S1之后可以得到S1的全部成员,可以认为此时S2的成员有
String s="s2";
String str="S1";
public void display(){
System.out.println(str);
}
注意,S2类中没有重写diaplay()方法
所以这题就相当于直接拿走S2中通过继承得到的diplay()方法,而这个方法打印的值str变量,不是s.
第三题
public class Test {
public static void main(String[] args) {
Base d = new Derived();
d.display();
}
}
class Base {
int count = 2;
public void display() {
System.out.println(count);
show();
}
public void show() {
System.out.println("父类的show方法");
}
}
class Derived extends Base {
int count = 20;
public void show() {
System.out.println("子类的show方法");
}
}
答案:
2
子类的show方法
解析:
1.第一步依旧是修改变量名便于理解。
class Base {
int type = 2;
public void display() {
System.out.println(type);
show();
}
public void show() {
System.out.println("父类的show方法");
}
}
紧接着思考子类拥有那些成员?
class Derived extends Base {
int count = 20;
public void show() {
System.out.println("子类的show方法");
}
//*继承自父类的成员*
int type = 2;
public void display() {
System.out.println(type);
show();
}
//*注意,show()方法被覆盖了*
~~public void show() {
System.out.println("父类的show方法");~~
}
通过重写变量名,分析子类成员可以发现调用display()方法的时候,返回的是type的变量名,调用的show()方法就是子类中覆盖过的方法。