Skip to content

Latest commit

 

History

History
105 lines (75 loc) · 3.7 KB

File metadata and controls

105 lines (75 loc) · 3.7 KB

Abstract Classes and More on 'final' Keyword

Abstract Class

An abstract class is a class that is declared abstract using the abstract keyword. It may or may not include abstract methods. Abstract classes cannot be instantiated, but they can be subclassed.

Sometimes you will need to define a superclass that declares the structure of a given abstraction without providing a complete implementation of every method. That is, sometimes you will want to create a superclass that only defines a generalized form that will be shared by all of its subclasses, leaving it to each subclass to fill in the details. Such a class determines the nature of the methods that the subclasses must implement.

To declare an abstract class, use this general form:

abstract class ClassName

An abstract class can have an abstract method as well as concrete methods. Abstract methods have no implementation in the superclass. It is the responsibility of the subclass to implement the method. Abstract method in superclass can be declared using this general form:

abstract return_type name(parameter_list);
//abstract parent class
abstract class Animal{
   //abstract method
   public abstract void sound();
}
//Dog class extends Animal class
public class Dog extends Animal{

   public void sound(){
	System.out.println("Woof");
   }
   public static void main(String args[]){
	Animal obj = new Dog();
	obj.sound();
   }
}
Output
Woof

Using 'final' Keyword with Inheritance

While method overriding is one of Java’s most powerful features, there will be times when you will want to prevent it from occurring. To disallow a method from being overridden, specify final as a modifier at the start of its declaration. Methods declared as final cannot be overridden.

class A {
   final void meth() {
      System.out.println("This is a final method.");
   }
}
class B extends A {
   void meth() { // ERROR! Can't override.
      System.out.println("Illegal!");
   }
}

Because meth() is declared as final, it cannot be overridden in B. If you attempt to do so, a compile-time error will result.

Using final to Prevent Inheritance

Sometimes you will want to prevent a class from being inherited. To do this, precede the class declaration with final. Declaring a class as final implicitly declares all of its methods as final, too. As you might expect, it is illegal to declare a class as both abstract and final since an abstract class is incomplete by itself and relies upon its subclasses to provide complete implementations.

final class A {
   //...
}
// The following class is illegal.
class B extends A { // ERROR! Can't subclass A
   //...
}

External Resources

Readings

Youtube Videos

More Examples and Practice Questions

Provided in the last chapter of current section.