how to make a class abstract in java code example
Example 1: abstract class in java
Sometimes we may come across a situation where we cannot provide
implementation to all the methods in a class. We want to leave the
implementation to a class that extends it. In such case we declare a class
as abstract.To make a class abstract we use key word abstract.
Any class that contains one or more abstract methods is declared as abstract.
If we don’t declare class as abstract which contains abstract methods we get
compile time error.
1)Abstract classes cannot be instantiated
2)An abstarct classes contains abstract method, concrete methods or both.
3)Any class which extends abstarct class must override all methods of abstract
class
4)An abstarct class can contain either 0 or more abstract method.
Example 2: how to create an abstract method in java
abstract class Scratch{
abstract public void hello();
abstract String randNum();
}
interface Other{
public void bye();
String randDouble();
}
Example 3: how to use an abstract class in java
interface methods{
public void hey();
public void bye();
}
abstract class other implements methods{
public void hey(){
System.out.println("Hey");
}
}
class scratch implements methods {
public void hey(){
System.out.println("Hey");
}
public void bye() {
System.out.println("Hey");
}
}
Example 4: can abstract class have non abstract methods in java
abstract class AbstractDemo {
private int i = 0;
public void display() {
System.out.print("Welcome to Tutorials Point");
}
}
public class InheritedClassDemo extends AbstractDemo {
public static void main(String args[]) {
AbstractDemo demo = new InheritedClassDemo();
demo.display();
}
}