[英]Call method of abstract super class without using sub class object
Suppose there is an abstract Super class with only one method which has default implementation.假设有一个抽象的 Super 类,它只有一个具有默认实现的方法。 Now, sub class is extending super class and it overrides the method of super class.
现在,子类正在扩展超类并覆盖超类的方法。
How to call method of super class without using sub class object?如何在不使用子类对象的情况下调用超类的方法?
public abstract class SuperClass
{
public void test()
{
System.out.println("SuperClass test method called");
}
}
public class SubClass extends SuperClass
{
public void test()
{
System.out.println("SubClass test method called");
}
}
public class CallAbstract
{
public static void main(String[] args)
{
//How to Call abtract SuperClass test method without using sub class object?
}
}
Using another anonymous class you could do:使用另一个匿名类,您可以执行以下操作:
public class CallAbstract
{
public static void main(String[] args)
{
(new BaseClass(){ }).test();
}
}
You need another Subclass that does not overwrite the test()
method.您需要另一个不覆盖
test()
方法的子类。
public class OtherSubClass extends BaseClass {
}
And in your main
method:在你的
main
方法中:
OtherSubClass osc = new OtherSubClass();
osc.test();
or use an anonymous class, like Edwin Dalorzo suggests.或者使用匿名类,就像 Edwin Dalorzo 建议的那样。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.