What is abstract classs?
- An abstract class in Java is a class that cannot be instantiated(you cannot create an object of it directly). It is used as a blueprint for other classes.) and is meant to be extended by subclasses.
- It is declared using the abstract keyword.
- It can have both abstract methods (no body) and concrete methods (with body), Can have Constructor, Can have Variables & Fields, Can have Static Methods, final methods
Key Rules to Remember :
- abstract class cannot be instantiated.
- abstract class can have 0 or more abstract methods.
- If a class has even one abstract method it must be declared abstract.
- Subclass must override all abstract methods or be declared abstract itself.
- abstract + final = not allowed(because it can't be extended)
- abstract + private method = not allowed(because it can't be extended).
- abstract class can extend another abstract class.
- abstract class can implement an interface without implementing its methods.
- Constructors are allowed (called during subclass object creation).
Example :
public abstract class ATM {
ATM()
{
System.out.println("ATM constructor called");
}
public abstract void withdraw();
public abstract void withdraw(int a,int b);
public void deposit(){
System.out.println("ATM deposit method called");
}
}
public class SBI extends ATM{
SBI()
{
System.out.println("SBI constructor called");
}
public void withdraw(){
System.out.println("SBI withdraw method called");
}
public void withdraw(int a,int b){
System.out.println("SBI withdraw method called with parameters: " + a + " and " + b);
}
public static void main(String[] args) {
SBI sbi = new SBI();
sbi.withdraw();
sbi.withdraw(1,2);
sbi.deposit();
}
}
output :
ATM constructor called
SBI constructor called
SBI withdraw method called
SBI withdraw method called with parameters: 1 and 2
ATM deposit method called
Top comments (0)