为什么引用子类对象的父类类型引用变量无法访问子类的方法 [英] Why parent class type reference variable having reference to child class object can't access child class's Methods

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

问题描述

由于此对象(在标题中声明)可以调用子类中的重写方法,所以为什么不能调用子类的其他方法? 我需要尽可能详细的答案,例如内存组织,JVM中的内部逻辑等.

Since this object(stated in title) can invoke overridden methods in child class, why it can't invoke other methods of child class? I need answer as detailed as possible like memory organization, internal logic in JVM etc.

下面的代码将使您清楚地了解我的问题.

below code will give you clear understanding of my question.

class A
{
  int x=10;
  public  A()
  {
    System.out.println("Constructor of class A called!!!");
  }

  public void sayGreetings()
  {
    System.out.println("accept hye from class A");
  }
}

class C extends A
{
  int x=30;//why this is not accessed by stated object.
  public C()
  {
    System.out.println("Constructor of Class C caled!!!");
  }
  public void sayGreetings()
  {
    System.out.println("accept hye from class C");
  }
  public void ssa()
  {
    System.out.println("Sat Sri Akal ji from class C");
  }
}

public class ParentClassTypeObject 
{
  public static void main(String[] args)
  {
    C cObj=new C();
    cObj.sayGreetings();
    cObj.ssa();
    A aCObj=new C();//this is let say stated object,main object
    aCObj.sayGreetings();/*here we invoked method will be child class's 
                         overriden method.*/
    //aCObj.ssa(); //why this line gives error

    System.out.println("x="+aCObj.x);
  }
}

推荐答案

由于接口,您所要写的对象就是您在编写时选择的对象:

Because the interface you have to the object is the one you chose when you wrote:

A aCObj = new C();

如果要通过aCObj变量访问C属性,请将其声明为C.

If you want access to the C properties via the aCObj variable, declare it as a C.

通过将其设置为A,您可以稍后编写此代码:

By making it an A, you make it possible to write this later:

aCObj = new A();

因此,由于变量可以指向AC,因此编译器限制您访问由A类型公开的接口定义的方法.

So since the variable can point to an A, or a C, the compiler restricts you to accessing the methods defined by the interface exposed by the A type.

您仍然可以访问这些方法的C定义,因为这是OOP(多态性)的要点之一.

You still access C's definition of those methods, because that's one of the main points of OOP (polymorphism).

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

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