我可以通过基类类型引用访问子类方法吗? [英] Can I access a subclass method through a base class-typed reference?

查看:439
本文介绍了我可以通过基类类型引用访问子类方法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是我正在努力解决但无法解决问题的代码:我能否真正在Java中执行以下操作..如果是,请帮助了解我如何,如果没有为什么? ......看看下面的代码......

Below is the piece of code I am trying to work on but unable to sort out the issue: "Can I really do the below in Java.. If yes please help to know me "How" and if no "Why?" "... Have a look at the code below...

class Base{

      public void func(){

            System.out.println("In Base Class func method !!");         
      };
}

class Derived extends Base{

      public void func(){   // Method Overriding

            System.out.println("In Derived Class func method"); 
      }

      public void func2(){  // How to access this by Base class reference

            System.out.println("In Derived Class func2 method");
      }  
}

class InheritDemo{

      public static void main(String [] args){

            Base B= new Derived();
            B.func2();   // <--- Can I access this ??? This is the issue...
      }
}

提前致谢! !等待一些有用的答案:) ...

Thanks in advance!!!! Waiting for some helpful answers :) ...

推荐答案

简短又甜蜜?不,你不能..如何 Base 知道扩展类中有哪些函数/方法?

short and sweet? No you cant.. How must Base know what functions/methods are present in the extended class?

编辑:

通过explict / type cast,这可以实现,因为编译器会在转换对象时知道你在做什么 Base 派生

By explict/type casting, this may be achieved, as the compiler takes it you know what you are doing when casting the object Base to Derived:

if (B instanceof Derived) {//make sure it is an instance of the child class before casting
((Derived) B).func2();
}

这篇关于我可以通过基类类型引用访问子类方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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