如何在java中从子类对象调用重写的方法
有没有办法从类c中创建的类b对象调用类a中的如何在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
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();
}
}