简体   繁体   English

如何在不派生抽象类的情况下直接调用抽象类的非抽象方法?

[英]How to call a non abstract method of an abstract class directly without deriving the abstract class?

I have an abstract class which contains a non abstract method as follows. 我有一个抽象类,其中包含一个非抽象方法,如下所示。

abstract class myClass {     
    public void myNonAbstractMethod()
    {
        //some logic goes here...
    }   
}

Now my question is, is it possible to call myNonAbstractMethod() directly without deriving myClass ? 现在我的问题是,是否可以在不派生myClass情况下直接调用myNonAbstractMethod()

No, as abstract class can not be instantiated by itself. 不,因为abstract class本身不能实例化。 You have to derive from it in order to be able to construct an instance. 必须从中派生才能构造实例。

 public abstract class Base {

   public void BaseMethod() {
   }
 }

 var bs = new Base();  //FAIL TO COPMILE

but.. 但..

 public class Derived : Base {

 }

 var bs = new Derived ();  //OK
 bs.BaseMethod(); //OK 

You cannot instantiate an abstract class meaning you aren't able to call an instance method directly from it. 您无法实例化抽象类,这意味着您无法直接从中调用实例方法。

You can make the method static if you really don't want to derive it, but a subclass would be best. 如果你真的不想派生它,你可以使方法成为static ,但子类最好。

public class Test {
    public static void main(String[] args) {
         System.out.println(SomeTest.size());
    }
}

abstract class SomeTest {
    public static int size() {
        return 5;
    }
}

Output: 输出:

5

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM