问题抛出
我们在FriendshipGraph中继承ConcreteEdgesGraph,然后我们在其中调用ConcreteEdgesGraph的方法,为了加到自己的成员变量中,因此向FriendshipGrap中加入了成员变量:
private final Set vertices = new HashSet<>();
private final List
思考与解决
感觉应该是对继承的方法理解不够,通过学习得到:
通过老师在微信群中给出的问题思考this到底指向哪个变量或方法。
//这段代码中的主函数运行之后输出什么?
class T {
void foo() {this.bar();}
void bar() {System.out.println("T.bar");}
public static void main(String args[]) {
B b = new B();
b.foo();
}
}
class B extends T {
void foo() {super.foo(); }
void bar() {System.out.println("B.bar"); }
}
在这个例子中的输出是“B.bar”。
//当代码改动为以下时:
class T {
void foo() {this.bar();}
void bar() {System.out.println("T.bar");}
public static void main(String args[]) {
B b = new B();
b.foo();
}
}
class B extends T {
void foo() {super.foo(); }
void barr() {System.out.println("B.bar");//将不再是重写的方法
}
}
在这个改动后的例子中的输出是“T.bar”
再次尝试这个代码:
class A{
int num = 1;
void show() {
System.out.println(this.num);
}
}
public class B extends A{
int num = 2;
public static void main(String[] args) {
B b = new B();
b.show();
}
}
这段代码的运行结果为“1”。
我们的this指向的是当前对象。我们可以使用this来解决成员变量和参数重名的情况。Java中只有Method有多态的特征,可以被覆盖,而Field不可以被覆盖,如果Field重名,具体调用哪个,与引用类型有关。
结论
1.当使用子类对象调用方法使用同名变量,是按照方法来判断使用哪一个变量,调用父类的方法,使用的是父类中的变量,调用子类的方法,使用的是子类中的变量。
2.子类重写父类方法时,子类调用时使用的是子类的方法。