子类方法调用函数时使用的成员变量问题

问题抛出

我们在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.子类重写父类方法时,子类调用时使用的是子类的方法。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值