为什么我无法使用父类型访问子对象方法 [英] Why I cannot access Child Object method with Parent Type

查看:118
本文介绍了为什么我无法使用父类型访问子对象方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对象a2属于A类但引用了类C的对象。因此,a2应该能够访问m3()。但是,为什么不发生呢?如果在A类中定义了m3()方法,那么代码就可以正常运行了

object a2 is of type A but references an object of class C. So, a2 should be able to access m3(). But, why is it not happening? If m3() method had been defined in class A, then the code would run fine

class A {

   int var = 7;

   void m1() {
      System.out.println("A's m1 ,");
   }

   void m2() {
      System.out.println("A's m2 ,");
   }
}

class B extends A {

   void m1() {
      System.out.println("B's m1 ,");
   }
}

class C extends B {

   void m3() {
      System.out.println("c's m3 ," + (var + 6));
   }
}

class Mixed {

   public static void main(String[] args) {
      A a = new A();
      B b = new B();
      C c = new C();
      A a2 = new C();
      a2.m1();
      a2.m2();
      a2.m3();
   }
}


推荐答案

A a2=new C();

这意味着您只能访问Class A 和Class C 的实现,如果有任何重写。

That means you can access only the members of Class A and implementations of Class C, if any overridden.

现在m3不是<$的成员C $ C> A 。清楚?

这篇关于为什么我无法使用父类型访问子对象方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆