简体   繁体   English

不使用子类对象调用抽象超类的方法

[英]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.

相关问题 在超类中调用方法使用子类的对象如何工作? - calling method in super class using object of sub class how it work? 在java中的超类上调用抽象方法是否有效 - Is it valid to call an abstract method on the super class in java 使用抽象类和super() - Using Abstract Class and super() 在没有子类化抽象类的情况下模拟对抽象类的公共方法的调用,优先使用mockito - Mocking a call on a public method of an abstract class without subclassing the abstract Class, using mockito prefererably 如果我们已经有子类的超类,我们如何调用超类方法? - How do we call a super class method if we already have a super class of sub class? 超抽象类的具体方法 - Concrete method in super class-abstract class 如何使用超类调用泛型方法 - How to call a generic method using super class 如何确保从子类(Java)中的方法在抽象超类中调用某些方法 - How to ensure a certain methods gets called in abstract super-class from method in sub-class (Java) 使用重写的抽象方法从超类访问私有变量 - Accessing private variables from a super class using an overridden abstract method 应该使用super还是在子类中使用this来访问Abstract超类中的受保护字段? - Should protected fields in an Abstract super class be accessed using super or this in sub-classes?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM