简体   繁体   中英

why abstract class can have a instance method?

We know if a class has an abstract method it will be abstract . It can't get an instance. But why can have an instance method? Does it have any meaning?

public abstract class AbsClass
{
    public abstract void GetA();

    public void Getb()
    { }
}

Not every method in an abstract class has to be abstract - when you derive from the class, the derived classes will inherit the non-abstract methods from the base class. It's extremely common to want to provide functionality in the base class that is common to all the derived classes (in fact, it's good programming practice to pull shared functionality up to the base class to avoid duplicating code in the various derived classes). It's also extremely common to want to provide "default" functionality in the base class that can then be overridden by individual derived classes.

The fact that you can't instantiate the base class itself doesn't matter - the non-abstract methods from the base class are called on instances of (non-abstract) derived classes.

Yes, it has a meaning.

It will be available for use in any derived class that does not explicitly implement it itself.

Example of a derived class:

public abstract class AbsClass
{
    public abstract void GetA();

    public void Getb()
    { }
}

public class DerivedClass : AbsClass
{

}

The following code will execute the abstract class's Getb() code:

var derivedClass = new DerivedClass();
derivedClass.Getb();

(Note that in the example above, the code wouldn't compile unless your derived class implemented GetA(), as it's declared as abstract, and therefore must be implemented in any concrete derived class)

The method will be the implementation for a concrete class that derives from AbsClass . Abstract means you can't create an instance of the class, not that it can't have any methods with implementation. You can also have instance data members in an abstract class.

As an example:

public class MyAbsClass : AbsClass
{
}

MyAbsClass mine = new MyAbsClass();
mine.Getb();  //This would call the implementation in AbsClass

If AbsClass were an interface , however, no implementation would be allowed.

Yes, it is perfectly well defined. It can't be invoked until you have an instance, which in turn indicates that you must have a concrete sub-type, but once you do the method is perfectly usable, for example:

AbsClass foo = new ConcreteClass();
foo.Getb();

Or indeed:

ConcreteClass foo = new ConcreteClass();
foo.Getb();

(since the sub-type inherits any types defined on base-types)

It is quite common for such methods to themselves use the abstract or virtual methods of the type - or indeed to be virtual .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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