Abstract class

- A class with the abstract keyword is known as an abstract class.
- It can have abstract and non-abstract methods which means with and without methods.
- It needs to be extended and its method can be implemented.
- It cannot be instantiated.
- It can have constructors, static methods, and final methods which will force the subclass not to change the body of the method.
- An abstract  class can have an abstract and non-abstract method

Program

abstract class Details {
    abstract void info();
}
//implementation is provided by others i.e. unknown by end user 
class Student extends Details {
    void info() {
        System.out.println("In class student");
    }
}
class Employee extends Details {
    void info() {
        System.out.println("In class employee");
    }
}
public class Test1 {
    public static void main(String args[]) {
        Details s = new Employee();// object is provided through method 
        s.info();
    }
}

 

Output:

In class employee

 

Use case demonstrating non-abstract method

A non-abstract method is also called a concrete method. An abstract method cannot be used in an interface and it must have an implementation which means a method body the below example illustrates the use of  abstract and non-abstract methods in a class

//Example of an abstract class that has abstract and non-abstract methods 
abstract class Bike {
    Bike() {
        System.out.println("Bike is started");
    }
    abstract void run();
    void changeGear() {
        System.out.println("Gear changed");
    }
}
//Creating a Child class which inherits Abstract class 
class Honda extends Bike {
    void run() {
        System.out.println("Running safely..");
    }
}
//Creating a Test class which calls abstract and non-abstract methods 
public class TestAbstraction {
    public static void main(String args[]) {
        Bike obj = new Honda();
        obj.run();
        obj.changeGear();
    }
}

 

Output:

Bike is started
Running safely..
Gear changed
 

Related Tutorials

Map