Abstract Class
Hey guys, today i’m going to mention about abstraction and abstract classes in Java.
Before we mention abstract classes let’s first mention abstraction.
What is abstraction ?
Means hiding the method implementations and showing only the functionality of the program.
We can use abstraction by creating interfaces and abstract classes in Java.
What is an abstract class ?
A class that can’t be instantiated and can’t create objects from it. Can have abstract and non-abstract methods. We are creating a class but we can’t create objects of that class, why do we need it ?
Why do we need abstract classes ?
We can use the abstract class as a template for the other classes and implement the abstract methods in the other subclasses.
Create an abstract class
To create an abstract class in Java we need to write “abstract” keyword before the “class” keyword.
Let’s create a student boy and girl example, in this example student class is going to be the abstract class and boys and girls classes are going to extend the student class.
public abstract class Student{
}
class Boys extends Student{
}
class Girls extends Student{
}
class Test{
}
We can create a method for student class but instead i am going to create an abstract method.
By putting “abstract” keyword before the return type we can create abstract method and abstract methods does not have curly brackets they have semicolon instead.
As you can see we created an abstract method but we are getting an error, it says the abstract method should be implemented in the subclasses, so we are going to do that.
public abstract class Student{
public abstract void msg();
}
class Boys extends Student{
@Override
public void msg() {
System.out.println("I'm a male student.");
}
}
class Girls extends Student{
@Override
public void msg() {
System.out.println("I'm a female student.");
}
}
class Test{
}
We overrode the abstract method for each subclass. We could also make the subclasses abstract to get rid of the error but the point of using abstraction would not be efficient in that way.
Let’s add more things to the code.
public abstract class Student{
public abstract void msg();
public void msg2(int age) {
System.out.println("I am "+age);
}
}
class Boys extends Student{
@Override
public void msg() {
System.out.println("I'm a male student.");
}
}
class Girls extends Student{
@Override
public void msg() {
System.out.println("I'm a female student.");
}
}
class Test{
public static void main(String[] args) {
Boys boy=new Boys();
Girls girl=new Girls();
boy.msg();
girl.msg();
girl.msg2(21);
boy.msg2(22);
}
}
In this code i added a non-abstract method into an abstract class, and since boys and girls classes are subclass of the student class we can call that method from their objects as well.
And the output is going to be this:
That was all from me today, have fun and keep learning, see you on the next writing.