Is it useful to have an abstract class without Abstract methods? [duplicate] - java

I am now studying a java and I'm at the part of Abstract.
I read sorta strange part to me that there is an abstract class
which does not include any abstarct method.
Why do they use this kind of class?

To prevent instantiation of that class and use it only as a base class. Child classes can use the general methods defined in the abstract class.
For example it doesn't make sense to create an instance of AbstractVehicle. But All vehicles can reuse a common registerMileage(int) method.

A common reason to do this is to have the abstract class provide exploding implementations of the abstract methods as a convenience to subclasses who don't have to implement all the abstract methods, just those they want to - the remaining ones will still explode but it won't matter if those execution paths aren't exercised.
HttpServlet is an example of this pattern in action. It has default implementations for all methods that handle the different request types, but they all throw an exception. The subclass must override these if they want to do something meaningful. It's OK to leave some handler methods not overridden as long as they are never called.

Yes, we can have abstract class without any abstract method.
Best example of abstract class without any abstract method is HttpServlet

If this class extends another abstract class and don't have implementation of inherited abstract methods.

This class contains some common logic for all its inheritors, but itself does not represent usable entity (in terms of particular application)

These type of classes are used for a implement a general logic which can be implemented by other classes. Making it abstract prevents from instantiating it. But other classes can inherit the class and its methods.

Say you have a set of related classes, but no related (shared) code, yet. If we make all of these classes extend a base class with no abstract methods, that then if we wan't all of these classes to have an identical method/feature in the future, that can be done in one shot by putting it in the base class. So code is not repeated and it reflects in all child classes by including it in just one place.

Another example for having such class is when you implement creation helpers. These classes are used to ease the client in the creation of objects, which are related in topic but decoupled depending on the need. By nature, the methods of this creator classes are all static and they can be seen as utility classes as well.Obviously, instatntation of this classes is futile and hence the abstractkeyword.
To mention a recent example I met was the Sftpclass from org.springframework.integration.dsl.sftp which is basically an easy way to require objects (e.g: adapters, gateways) from the sftp api.

I develop a abstract class to prevent instantiation of that class and use it only as a base class. because, These type of classes are used for a implement a general logic which can be implemented by other classes. Sometimes, I have a default implementation for every method in abstract class. In the manner, it doesn't force the sub-class to override all of method, but also it implement everyone that is need.It means implicitly you have to override at least one method to make scene using this abstract class.

I can't think of any good reason to use it. It could be used as "marker" but an interface would be a better choice.

Abstract class without abstract method means you can create object of that abstract class.
See my Example.
abstract class Example{
void display(){
System.out.println("Hi I am Abstract Class.");
}
}
class ExampleDemo
{
public static void main(String[] args)
{
Example ob = new Example(){};
ob.display();
}
}
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.

Related

How to declare abstract method in non-abstract class

I want to declare a couple of abstract methods (so the implementation is required in the classes that inherit from this one) to fit my situation, which is:
I am making a puzzles solver program. So far I have 3 packages:
games.puzzles
games.puzzles.rivercrossing
games.puzzles.rivercrossing.wolfgoatcabbage
I don't want to get too specific but in the games.puzzles.rivercrossing package I have two classes that represent a bank and a state: GenericBank and GenericState.
Now, they define some behavior, but there are some methods that the classes that inherit from these must have, like move() to move one element from one bank to the other or isPermitted() and isFinal() to check the states.
For example, in the last package I have the WolfGoatCabbageGame class and it must have its own Bank and State classes which will inherit from the generic ones. These particular Bank and State classes must implement the methods I mentioned above, for example in the Wolf, Goat and Cabbage game, to check if the goat and the wolf are not in the same bank, etc.
So initially I declared the generic classes as abstract, and these methods to be implemented abstract as well:
public abstract class GenericBank {
// more members ...
public abstract boolean move(Element element, GenericBank dst);
// more members...
}
public abstract class GenericState {
// more members...
public abstract boolean isPermitted(GenericBank bank);
public abstract boolean isFinal(GenericBank bank);
// more members...
}
And this looked like it'd work until I found out I had to instantiate GenericBank and GenericState objects, which of course can't be done if these classes are abstract.
So I had to remove the abstract qualifier from the classes.
So... what can I do? How can I declare abstract methods (or achieve the same behavior) in a non-abstract class?
How to declare abstract method in non-abstract class?
Answer: You can't. It's kind of the definition of abstract. It's the same reason you can't instantiate an object as an abstract class.
Either:
A) You need to use Interfaces
B) Leave the methods empty in the parent class:
//technically this needs to return a value, but it doesn't need to *do* anything
public boolean isPermitted(GenericBank bank){ return false; }
C) Refactor your code so that you aren't instantiating abstract objects. I cannot advise how to do this as you haven't provided any code regarding this.
You could replace the abstract methods with empty methods that do nothing and return the default value of their respective return type (and, if necessary, make it part of the generic classes contract, that subclasses must override these methods).
Alternatively, you could keep your abstract Generic*-classes and add Null*-classes with abovementioned empty implementations, following the Null object pattern.
You cannot declare abstract methods in a non-abstract class, final dot.
That would simply defile the concept of abstract methods.
What you can do is have your class hierarchy implement interfaces dictating the required methods to implement.
If you found your formerly abstract classes were actually better designed as concrete classes, do convert them to concrete classes and implement the methods, even with a default, general implementation.
You can then fine-tune the overrides in your child classes.
Remove the abstract qualifier and add a empty body, or throwing some runtime exception.
Or instantiate these generic classes as anonymous sub classes
You cannot, the very definition of an abstract class is that it has abstract methods.
What you can do, is define default behaviour, that can be overruled by subclasses.
However, I would carefully consider your class hierarchy before doing this. The fact that you need to instantiate some classes before their actual implementations are known, suggests that your design may need re-thinking.
If you're going to re-design, you will want to look at the time of instantiation - and underlying that, the reasons for instantiating.
Right now, you want to use some of the common behaviour of a class, before the actual instance of that class is known.
It goes a bit beyond the scope of answering the question, but: consider explaining the design of the code to a friend. Or to a rubber duck. This may help you to find a fresh approach.
You can use Virtual instead!
internal class ClassA
{
public void Print()
{
Console.WriteLine("A");
PrintVirtual();
Console.WriteLine("--------------------------------------------------");
}
protected virtual void PrintVirtual()
{
Console.WriteLine("Virtual");
}
}
internal class ClassB : ClassA
{
protected override void PrintVirtual()
{
Console.WriteLine("B");
}
}
internal class ClassC : ClassA
{
protected override void PrintVirtual()
{
Console.WriteLine("C");
base.PrintVirtual();
}
}
and you can run the test
new ClassA().Print();
new ClassB().Print();
new ClassC().Print();

Why do we create an abstract class even though all the methods of that class are defined?

Why do we create abstract classes even though all methods of that class are already defined?
If the answer is to stop the programmer from creating an object of that class, couldn't we achieve the same thing by using a private constructor?
A class being abstract only prevents that particular class from being instantiated. Child classes may still allow instantiation.
A class with no non-private constructors prevents subclassing as well as public instantiation.
From the above you can see that these two things serve two different purposes. A class may have either—or even both properties.
The idea of the Abstract class is a common base for a number of other classes..
Think of "Animals".. You cannot create something called 'Animal'..
You have Cats and Dogs and Rabbits that 'Are' animals.
You have a abstract class called "Animal" and then you have a class called Cat that extends Animal, or Dog that extends Animal... but you do not instantiate the class "Animal" directly as its only a common base.
The design pattern of creating a class as abstract even though all methods are defined is used when the abstract class has "do nothing" or exception-throwing implementations of the methods.
We can see this in action in the HttpServlet class, which has implementations for each of the web methods (doGet(), doPost(), doPut() and doDelete()) that throw a ServletException and which a subclass must override if they want a class that does something useful for a particular web method.
Any web methods not overridden with a working implementation will explode by default.
Abstract classes show that this class in itself will not be used independently and some other concrete classes should extend it to make complete sense.
While preventing using private constructor will inhabit subclassing.
Abstract classes with no abstract methods maybe a mistake of the developer.
In Abstract class you can define the constants which are common to many class
If you have a class which only contains static methods, the you can do it abstract, as there's no need of instantiating it. I can think about utility or helper classes at least.
Specifically regarding the use of abstract vs. hiding the constructor: The abstract keyword more clearly states the architectural intent of the programmer. It's better practice.
The fact that they've provided default implementations of all the methods is a separate question.

abstract classes ,constructor and interface

I'm really confused, and I've read a TON of questions on this topic and I have not been able to pinpoint anything specifically that an interface can do that an abstract class cannot do.
A class can implement multiple interfaces, but it cannot implement multiple abstract classes.
Interface itself cannot do anything. It just defines kind of contract between the class(es) that provide some functionality and the caller.
Abstract class is the class that defined as abstract. If class has at least one abstract method (i.e. method without implementation) it must be defined as abstract. But abstract class can contain implementations as well.
Interface cannot contain implementation. Only abstract methods and constants (static final fields).
Class can implement several interfaces and extend only one class (including abstract class).
I hope this helps.
Abstract class can also contain function implementation rather than just defining the functions that have to be implemented by inheriting classes
Abstract classes are partially implemented classes, that will be extended by concrete classes(non-abstract), to be implemented.
Example:
This example does not mean that the sub classes must implement those methods(as it happens when implementing an interface). You can declare a subclass abstract, and the implementation will be done later by annother sub-sub-class. (For example: Boat can have subclasses "SpeedBoat" and FisshingBoat, and the may implement honk() in different ways)
The interface are the eyes of class to the outside world. What classes can do is declared in the interface, but implemented in the class.
A class can implement many interfaces, but can extend only one class.
See this little example of interfaces:
As you can see when we use interfaces we can have a lot of flexibility. Some Enemies can do things that some Heroes can do too(DarkKnight can throw arrows).
I hope you now feel the difference between the abstract classes and interfaces.
Remember this about interfaces and Abstract classes:
Interfaces dont have variables, just non implemented methods(abstract methods implicitly)
Classes that implement interfaces must have all the methods of the interface in its body
One class can extend only one class but implement more than one interface
If a class has an abstract method, it must bee declared as abstract.
Abstract classes can implement interfaces
Interfaces can extend other interfaces(more than one)
I dont know if i forget something, i hope this information helps.
An abstract class can everything that a Interface can do. However inverse of this is not correct.
Abstract class can contain abstract methods, abstract property as well as other members (just like normal class).
Interface can only contain abstract methods, properties but we don’t need to put abstract and public keyword. All the methods and properties defined in Interface are by default public and abstract.
We can see abstract class contains private members also we can put some methods with implementation also. But in case of interface only methods and properties allowed
Interface and abstract class almost both are same the major difference is using interface we are not able to define the body of the method but using abstract class we can define the body of the method inside the abstract class or while implementing it.
e.g
Interface abc()
{
string xyz();
}
abstract abc()
{
string xyz()
{
// define body
}
}
or
abstract abc()
{
string xyz();
}
An abstract class is a class - it defines all or part of an implementation of some behaviour for a class of objects, but with some extension points for concrete subclasses to provide.
An interface is a type - it defines the set of operations which are provided by any class implementing the interface.
You're almost asking whether there is anything that a candidate can do that the job description can't. Creating an abstract class says 'here is a template for some implementation'. Creating an interface says 'I expect an object to provide these capabilities'. You can use virtual methods in an abstract class to implement some aspects of a type, but the intention is different.

what is the advantage of interface over abstract classes?

In Java, abstract classes give the ability to define both concrete and abstract methods whereas interfaces only give the ability to implement abstract methods.
I believe overriding methods in subclasses/implementations is possible in both cases, therefore, what is the real advantage of one over the other (interfaces vs abstract classes in Java)?
Interfaces are for when you want to say "I don't care how you do it, but here's what you need to get done."
Abstract classes are for when you want to say "I know what you should do, and I know how you should do it in some/many of the cases."
Abstract classes have some serious drawbacks. For example:
class House {
}
class Boat {
}
class HouseBoat extends /* Uh oh!! */ {
// don't get me started on Farmer's Insurance "Autoboathome" which is also a helicopter
}
You can get through via an interface:
interface Liveable {
}
interface Floatable {
}
class HouseBoat implements Liveable, Floatable {
}
Now, abstract classes are also very useful. For example, consider the AbstractCollection class. It defines the default behavior for very common methods to all Collections, like isEmpty() and contains(Object). You can override these behaviors if you want to, but... is the behavior for determining if a collection is empty really likely to change? Typically it's going to be size == 0. (But it can make a big difference! Sometimes size is expensive to calculate, but determining whether something is empty or not is as easy as looking at the first element.)
And since it won't change often, is it really worth the developer's time to implement that method every... single... time... for every method in that "solved" category? Not to mention when you need to make a change to it, you're going to have code duplication and missed bugs if you had to re-implement it everywhere.
Interfaces are useful because Java doesn't have multiple inheritance (but you can implement as many interfaces as you like).
Abstract classes are useful when you need concrete behaviour from the base class.
The facts are-
Java doesn't support multiple inheritance
Multiple interfaces can be implemented
Few methods in an abstract class may be implemented
These facts can be used to tilt the advantage in favor of interfaces or abstract classes.
If there are more than one behavior that a class must share with other classes, interfaces win.
If a method definition has to be shared/ overridden with other classes, abstract classes win.
An class may implement several interfaces, whereas it may only extend one class (abstract or concrete), because Java does not support multiple inheritance.
In OOP (mostly independent of a concrete language) abstract classes are a re-use mechanism for the class hierarchy for behaviour and structure which isn't complete on its own.
Interfaces are mechanism for specification of requirements on a module (e.g. class) independently of the concrete implementation.
All other differences are technical details, important is different usage.
You dont override an interface. You implement it.
Writing an interface gives implementors the ability to implement your interface and also other interfaces in addition to inheriting from a base class.
Abstract classes can be partially or fully implemented.Marking a class abstract just prevents you from instantiating an object of that type.
-Method without any implementation is abstract method,whenever a class contains one or more abstract method,then it must be declared as a abstract class
-Interface is fully abstract which cannot have constructor,instance and static blocks,and it contains only two types of members
1.public abstract method
2.public-static-final variable
*Both cannot be instantiated but reference can be created.
*Which one suits better depends on the application
-Interfaces are useful because Java classes will not support multiple inheritance but interfaces do.
-Abstract classes are useful when you need concrete behavior from the base class.
The main advantages of interface over abstract class is to overcome the occurrence of diamond
problem and achieve multiple inheritance.
In java there is no solution provided for diamond problem using classes.For this reason multiple inheritance is block using classes in java.
So to achieve multiple inheritance we use interface .
class Animal
{ void move(){} }
class Bird
{ void move(){fly} }
class Fish
{ void move(){swim} }
Now, if class Animal is abstract class like
Animal a;
a= new Bird(); or a = new Fish()
Here, abstraction works well, but if there are 100 objects like Animal a[100];
You can not write new Bird().move or new Fish().move 100 times
Use interface and write a[i].move. It will differentiate as bird or fish and that move() will be invoked
Second it supports multiple inheritance as class A can implements as many interfaces.
Amazing answers!!
I too want to put my opinion on Interface.
As the name says it is interface which means it will provide interface between two classes.
It help a class or interface hold multiple behavior at the same time.
Who ever having the interface can access the behavior of the class agreed with the interface.
interface teacher
{
//methods related to teacher
}
interface student
{
//methods related to student
}
interface employee
{
//methods related to employee
}
class Person:teacher,student,employee
{
//definition of all the methods in teacher,student, employee interface
//and method for person
}
Now here which ever class is having teacher interface will have access to only teacher behavior of Person.
Similarly the class or module having student interface will have access to only student behavior of person.
Using abstract class, it is not at all possible.
Hope this will add some additional points. :)
Happy coding!!.

What is the main advantage of making a class abstract

Why do we declare a class as abstract? I know it cannot be instantiated, but why give a special keyword for it. Even a 'normal' class will work just as well and can be easily subclassed. so what is the main advantage of making a class abstract?
In abstract class you can implement some method and can make some abstract all your client will have to implement it also. you can provide some common functionality , also you can have some inherited fields and some of the skeleton method here
An abstract class can have abstract methods and "concrete" methods.
The "concrete" methods can use the abstract methods, and can be sure that they are (correct) impelmented at runtime. Because every (not abstract) subclass has to implement them. (And ther will be no instance of the abstract class itselfe).
So it is all about savety! - It makes sure that the programmer who want to subclass an abstract class must implement the abstract method(s).
If you do this only with a normal class then the class, corresponding to the abstract class, would have the (abstract) methods with an empty Implementation, and only a notic to the programmer that he has to override this method.
Of course you can use the concept of abstract classes for other thinks, like create not instanciable classes, but that is not the main point.
I think you misunderstand the point of abstract classes: they provide a partial implementation of some functionality, but not a complete implementation.
You suggested that abstract classes were redundant because you can define incomplete methods using public void methodname(){} -- which is certainly ok. However, let's say your clients inherit from a class defined in such a way, how do they know which methods to override? What happens if they forget to override a method? Now their derived class has an incomplete definition -- you don't want that.
The abstract keyword forces clients to provide implementations for certain methods, otherwise the code won't even compile. In other words, it provides a compile-time guarantee that classes you use or create are fully implemented.
Declaring the class abstract prevents any code from instantiating the class.
This enforces the design guideline to make non-leaf classes abstract.
It allows you to add abstract methods to your superclass (and implementations to the subclasses) later, without affecting any existing clients.
The abstract keyword works even if the non-leaf class does not currently have any abstract methods.
Just a real life example. I have a GUI abstract class that is the parent for all my GUI components. Lets call this AbstractSuperClass. Each of my components that extend AbstractSuperClass need their own implementation of the save function. So the nice thing about making my super class abstract is that I can have an array of type AbstractSuperClass that can hold all of my GUI components. I can then loop over that array and call the save function knowing that each GUI component has its own save method. Since the class is abstract, it forces my subclasses to provide a implementation of the save function.
This is especially useful because when we open up our APIto other programmers, they dont get the source. They just extend the AbstractSuperClass and must provide a save implementation.
It's useful if you want to have a group of classes that inherit the same logical functions.
But in the same time, the class only implements the basic logic, and doesn't contain any real functionality.
You should see it as a skeleton class.
For example, I once made a class with these specifications :
Controls the process of executing a command on another thread, and relays events of that process.
The class itself didn't have any functionality by itself (didn't implement the actual work() function)
So the result is an abstract class, that can be inherited, that already has a built in thread control, which all you need to do is just implement the work() method.
If your class has some default behavior and you want some other behavior to be implemented by the extending classes then you use abstract classes. They cannot be initialized, you can think of abstract classes as a template for the extending classes.
Abstract classes can also call the abstract methods which in result calls extending object's method. Anyways there are lot's of discussions about when to use abstract classes, when to prefer it over an interface. Make a google search, it is an epic discussion :) interfaces vs abstract classes.
You would declare a class as abstract if it makes little to no sense to create an instance of it (you would create instances of subclasses).
public abstract class Shape {
public double calculateArea();
}
public class Square : Shape {
private double side;
double calculateArea() {
return side*side;
}
}
public class Circle: Shape {
private double radius;
double calculateArea() {
return 3.1415 * radius * radius;
}
}
public class MainClass() {
public static void Main() {
Shape myShape = new Square();
system.out.print(myShape.calculateArea());
myShape = new Circle();
}
}
It makes no sense to create an instance of Shape because it doesn't mean anything concrete, its an abstract concept. However, you can have variable of type Shape which allows you to program around the common base-type (though it could be argued that an interface might be better in this situation).
Generally, if there is inheritance, as in a super domain class, with common methods and common implementations in subclasses then look into going with an abstract class, which is not that often, but I do use it.
If you just go with Abstract classes just because there is inheritance, you can run into problems if the code changes a lot. This is detailed very well in the example here: Interfaces vs Abstract Classes in Java, for the different types of domain objects of motors. One of them required a dual powered motor, instead of a specific single type, like asolar powered or battery powered motor. This required multiple subclass implementation methods from both motor types to be used in a single subclass and that is where abstract classes can get messy.
To sum it all up, as a rule you want to define behaviors (what the objects will do) with interfaces and not in Abstract classes. In my thinking, the main advantage for Abstract classes is when the focus from the use case is on an implementation hierarchy and code reuse from subclasses.

Categories