Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在java中从子类对象调用重写的方法_Java_Oop_Inheritance - Fatal编程技术网

如何在java中从子类对象调用重写的方法

如何在java中从子类对象调用重写的方法,java,oop,inheritance,Java,Oop,Inheritance,有没有办法从类c中创建的类b对象调用类a中的test() 只能在类b的test()方法中执行此操作,如下所示 class b extends a { void test(){ super.test(); System.out.println("in b"); } } 在Java中,默认情况下,所有非静态私有方法都是虚拟。因此,除非修改b#test,否则无法从b实例调用a#test。唯一的方法是使用a: public class c{ public sta

有没有办法从类c中创建的类b对象调用类a中的
test()


只能在类
b
test()方法中执行此操作,如下所示

class b extends a {
   void test(){
     super.test();
     System.out.println("in b");
   }
}

在Java中,默认情况下,所有非
静态私有
方法都是
虚拟
。因此,除非修改
b#test
,否则无法从
b
实例调用
a#test
。唯一的方法是使用
a

public class c{
    public static void main(String[] args) {
        b refb = new b();
        // code to call test() in class a
        //this is the only way you have in Java
        a refA = new a();
        a.test();
    }
}

super关键字,但是那将是从b内部进行的。在java中不能这样做。谢谢,但我不想更改类b的代码,有没有方法从类b的对象refb调用c@Jayadeep; 这违反了封装。你不能那样做。可能是你做了一些错误。@ abimalangugasthaAn,在C++或C语言中,你可以把这个方法作为非<代码>虚拟< /代码>。看看我的答案。@ LuiggimimZZ:我不熟悉C语言或C++。但是,在java中,我们不能这样做。
public class c{
    public static void main(String[] args) {
        b refb = new b();
        // code to call test() in class a
        //this is the only way you have in Java
        a refA = new a();
        a.test();
    }
}