staticmethod staticmethod - 9 days ago 6
Java Question

Why should I use the "abstract" keyword?

I am a Java beginner and I'm learning about abstract classes and methods. My teacher showed me this example:

abstract class Person{
public abstract void talk();
}

class Teacher extends Person{
public void talk(){
System.out.println("I'm a teacher");
}
}

class Student extends Person{
public void talk(){
System.out.println("I'm a student");
}
}


I think I understand it. Basically an abstract method can't do nothing until it is inherited and overriden. And also it is used when all the subclasses must implement it but not in the same way. But I thought to myself: "This should also work!"

class Person{
public void talk(){
//nothing here!!
}
}

class Teacher extends Person{
public void talk(){ //overrides
System.out.println("I'm a teacher");
}
}


class Student extends Person{
public void talk(){ //overrides
System.out.println("I'm a student");
}
}


And in fact, it works.

So here goes my question: Why having abstract methods if you can write empty methods or even not write them at all? Am I missing something?

Also, I need someone to explain in which context should I use abstract class fields in my classes. I see them eveywhere in the Java API but they don't make sense for me

Answer

In your example, without abstract, someone can create an object for the class Person i.e., you are NOT restricting the instantiation of the Person class whereas if you use abstract the object for Person can't be created until someone inherits the Person and implement the abstract methods.

Also, in the Object Oriented Programming, when you say abstract you are ONLY specifying the contract of the class by leaving out the implementation to the sub classes i.e., you will tell WHAT behaviour (methods) a Person should have, but NOT HOW those behaviours are and those behaviours (methods) are actually implemented by subclasses like Teacher, Student, etc.. classes.

In simple terms, abstract class specifies what methods should be there (i.e., also called as general contracts) and the subclasses will provide the actual implementations for those methods.

In Java, you can also corelate the similar concept with interface as well.

I recommend you to have a look at here and understand more on this basic and critical subject.