Sunday, January 24, 2016

Topic 24: Abstract classes in Java

  • Sometimes we require that certain methods be overridden by subclasses by specifying the abstract type modifier. These methods are sometimes referred to as subclasser responsibility because they have no implementation specified in the superclass. Thus, a subclass must override them—it cannot simply use the version defined in the superclass. To declare an abstract method, use this general form:

abstract type name(parameter-list);

No method body is present.

  • Any class that contains one or more abstract methods must also be declared abstract. 

  •  To declare a class abstract, we simply use the abstract keyword in front of the class keyword at the beginning of the class declaration. 

  • There can be no objects of an abstract class. That is, an abstract class cannot be directly instantiated with the new operator. 

  • We cannot declare abstract constructors, or abstract static methods. 

  • Any subclass of an abstract class must either implement all of the abstract methods in the superclass, or be itself declared abstract.

// A Simple demonstration of abstract.
abstract class A
{
abstract void callme();


// concrete methods are still allowed in abstract classes
void callmetoo()
{
System .out.println("This is a concrete method.");
}
}

class B extends A
{
void callme()
{
System.out.println("B's implementation of callme.");
}
}

//Inside class containing main()
B b = new B(); //cannot create object instance for class A
b.callme();
b.callmetoo();


It must be possible to create a reference to an abstract class so that it can be used to point to a subclass object.



Click for NEXT article.


Please feel free to correct me by commenting your suggestions and feedback.

No comments:

Post a Comment