Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why do we need abstract classes in Java? [closed]

Why do we need abstract classes in Java? If you're never going to make it into an object, why have it in the first place? How do you use it? Why is it there? I'm wondering the same thing with abstract methods. I find it seems like a similar concept to having a super class with NO subclasses that could ever matter to be made.

like image 980
user3314801 Avatar asked Feb 28 '14 04:02

user3314801


People also ask

Why do you need abstract class in Java?

Java Abstract class can implement interfaces without even providing the implementation of interface methods. Java Abstract class is used to provide common method implementation to all the subclasses or to provide default implementation. We can run abstract class in java like any other class if it has main() method.

Why do we need abstract classes?

The short answer: An abstract class allows you to create functionality that subclasses can implement or override. An interface only allows you to define functionality, not implement it. And whereas a class can extend only one abstract class, it can take advantage of multiple interfaces.

Why do we need abstract class without abstract method?

An abstract class can extend only one class or one abstract class at a time. Declaring a class as abstract with no abstract methods means that we don't allow it to be instantiated on its own. An abstract class used in Java signifies that we can't create an object of the class directly.

What is the use of abstract class without abstract method in Java?

Abstract class without abstract method means you can create object of that abstract class. See my Example. If you write one abstract method inside abstract class then it will not compile. Which means if you create abstract class without abstract method then you can create Object of that Abstract Class.


1 Answers

An abstract class can be used as a type of template for other classes. The abstract class will hold common functionality for all classes that extend it.

For example:

Abstract Class Animal 

All animals move and breathe and reproduce so these can be put into the Animal Class.

Now

 Concrete Class Dog, Cat etc.

Have these base functions already provided.

like image 185
Scary Wombat Avatar answered Oct 11 '22 11:10

Scary Wombat