Object Oriented Programming

Abstract Methods and Classes in Java

Abstract methods, similar to methods within an interface, are declared without any implementation. They are declared with the purpose of having the child class provide implementation. They must be declared within an abstract class.

A class declared abstract may or may not include abstract methods. They are created with the purpose of being a super class.


Syntax
modifier abstract class className {
    //declare fields
    //declare methods
    abstract dataType methodName();
}

modifier class childClass extends className {
    dataType methodName(){}
}

Notes

Abstract classes and methods are declared with the 'abstract' keyword. Abstract classes can only be extended, and cannot be directly instantiated.

Abstract classes provide a little more than interfaces. Interfaces do not include fields and super class methods that get inherited, whereas abstract classes do. This means that an abstract class is more closely related to a class which extends it, than an interface is to a class that implements it.


Example
public abstract class Animal {
    String name;  
    abstract String sound(); //all classes that implement Animal must have a sound method
} 
 
public class Cat extends Animal {  
    public Cat() {
        this.name = "Garfield";        
    }    
    public String sound(){ //implemented sound method from the abstract class & method
        return "Meow!";
    }
} 

< Interfaces   |   Anonymous Class >

© 2019 SyntaxDB. All Rights Reserved.