Method overriding vs abstract method - java

We use abstract method to implement it in a different sub classes for different scenarios.
Like abstract class Animal will have abstract method makeNoise(). Subclass Dog and Cat will implement this abstract method to print "bark" and "meow", respectively
But I want to know that how is it different than method overriding where we can use two classes with its own method makeNoise() for itself?
In both cases we instantiate the both sub classes to perform the actual task then how it would be efficient to use abstract method.

An abstract method is a contract which forces its immediate subclass to implement the behaviour of all abstract methods. Where as overriding is optional and is not always a necessity for the subclasses.
Efficiency of abstract method lies in the fact that they force the immediate subclass to provide implementation. Generally speaking go for abstract over overide in cases where you do not know what would be the common default implementation for all child classes.
For your example what if we donot know what is the common noise/sound that most of the animals make. We only know that all animals make noise. So better to go for abstract. If you knew the common/default noise that most of the animals make then you could provide that implementation in Animal class as non abstract and if needed its child classes can override it if they think they make a better noise :-)

Creating a common method that gets overridden in other classes defeats the purpose of abstract classes. They are designed so they CANNOT be used until a child class extends the abstract class to further complete it (Overriding).
If you don't make Animal abstract then like all other answers say, how will you fill in its purpose?

Related

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.

Abstraction clarification. Java

Hello I have just been learning about abstraction and was looking for a bit of clarification.
1 - Is the only reason for using an abstract method to be able to pass static type checking without actually having to implement the method? Is there any other reason why someone would want to make a method abstract?
2 - If you made an abstract method and had some code in it, how would you "add to" that code in the sub class implementation. Would you just carry on typing? I have only seen empty abstract methods in examples.
Thanks and sorry if these questions are a bit basic.
Abstract classes, like interfaces, allow you to specify a kind of contract between you (your class) and your user (the user of your class). The difference to interface is that you can also provide some behaviour, that is you can implement some methods and leave other methods empty, that is abstract.
An abstract method is always empty - that's what it means to be abstract. Subtypes of an abstract class can change behaviour of a method implemented in the abstract parent by implementing the method themselves. They can reuse the parent's code by calling the parent's method first - like you do with constructors.
At 1: abstract methods are a way to suggest to a programmer that extends your code, that "there should be a method like this implemented in your code". This may be used to pre-design interfaces in some bigger systems, for example.
At 2: yes. When implementing sub-classes of some abstract classes you are not restricted only to the methods and fields of your "parent" class.
1 - abstract classes are meant to be extended by a regular class. so by having abstract methods, it forces the implementation of the abstract method in the class extending the abstract class, however, it also gives control to the programmer on how it should be implemented. lets say the class Lion and class Dog both extend the class Animal. lets say Animal class has run() method. both lion and dog can run but the way they run, how fast they run is different. thus, by making run() abstract, you can define run() specifically to Lion and Dog classes.
2 - abstract methods can't have a method body or any code inside.
For example: abstract void run();
notice there are no starting and closing braces after run();

Java Collections: Interfaces and Abstract classes

All Collections implements interface Collection, these collection have specific abstract hierarchy e.g.
AbstractCollection -> AbstractList -> ArrayList
AbstractCollection -> AbstractSet -> HashSet
But there are also corresponding interfaces like Collection, List, Set. These interface seem to me kind of redundant.
Why are they here ? Is is just convention or is there a reason to just implement interface and not extend the abstract class.
The interfaces are there because it's good to be able to assign a type to a variable or parameter without imposing an implementation.
For instance if I create a persistent entity to use in Hibernate, and it has a collection of things, I want to assign a type of List or Set to that. Hibernate will swap out whatever list I initialize it to with its own, with some Hibernate-specific implementation that does lazy-loading or whatever else it needs to. The Hibernate developers may not want to be constrained by having to extend the abstract class.
The abstract class exists as a convenience for implementers. The interface is a contract used by clients.
Implementing an interface is much different from extending an abstract class.
Let's suppose that class Animal is an abstract class, and that Dog, Cat, Snake and Shark extend Animal.
The default Animal.move() implementation simply moves them.
But, interfaces allow us to further group-out similar animals, such as RunningAnimal, SwimmingAnimal.
So, if Dog extends Animal implements RunningAnimal, along the inherited move() he will also have to implement his own run(), which might find it's way in the overridden move() inherited from Animal. Does this make sense to you yet or do I need to clarify better / with some code? :)
Interfaces let you group similar functionality of different classes. "Clickable", "Sortable", "Serializable" ... They all encompass the members thru a shared functionality (so a list of clickables is more than a list of buttons) rather than a same purpose.
So, think about it like this
Cat extends Animal implements RunningAnimal, ClimbingAnimal -- inherits move() has to implement run() and climbTree()
Dog extends Animal implements RunningAnimal -- inherits move(), has to implement run()
Snake extends Animal -- likely overrides inherited move()
Shark extends Animal implements SwimmingAnimal -- likely overrides move(), has to implement swim()
Why not ? Abstract classes are made to simplify inheritance process. When you want to create your collection you don't have to do everything from scratch.
But of course no one tells you that you SHOULD inherit from AbstractCollection. You can write your implementation from scratch.
This is a common good practice for API's to have interfaces. And have distinction between implementations and interfaces.
An Interface is a contract made between users and implementers. An abstract base class is intended to be used as a common base to access a number of similarly-behaving objects.

Achieving multiple inheritance via interface

I am a beginner in interface concept.
when I surfing for the information about "Achieving multiple inheritance via interface", I came across this link.. Multiple inheritance
I have a same doubt as the programstudent had.
hi, Good Explanation very much helpful In the uml diagram for java
there is no connection to Animal from Bird and horse why? Is it
necessary to use the implement the same method in the derived class
and why
void birdNoise();
void horseNoise();
why in the Peagus class
public void horseNoise()
{
System.out.println("Horse Noise!");
}
public void birdNoise()
{
System.out.println("Bird Noise!");
}
why this must be there? Why "Remember, we must write each class's own implementation for each method in the interface. reason? Thank for this good explanation Thank you
In that post, they have used multiple inheritance in c++ and converted to interfaces in java.
1.what I thought about inheritance is having some methods in parent class, and whenever the same methods are needed in other class(es) too, then those class(es) will inherit the parent class and use it.
But in interface concept if each derived class(es) has to define its own implementation then what is the use of inheriting it?
2.If we have to provide own implementation then why not we define that method in the derived class(es) itself. What is the use of inheriting it?
Someone please explain.
Thanks in advance.
When I switched from c++ to java I had this same feeling but now that I been working with java for a while it all kinda makes sense.
1.what I thought about inheritance is having some methods in parent
class, and whenever the same methods are needed in other class(es)
too, then those class(es) will inherit the parent class and use it.
Like the original author did, you can still do multiple inheritance in java you just must use interfaces. Interfaces are like pure virtual classes in c++.
But in interface concept if each derived class(es) has to define its
own implementation then what is the use of inheriting it?
The reason you implement an interface in java is so that you guarantee that class has those methods. That way you can have a specific class implement a generic interface and then treat every specific class that implements that generic interface the same.
Java Design is a bit different then c++ design but after doing several java program's you will become just as good at using multiple interfaces as you are at using multiple inheritance.
Each subclass has to define it's own implementation because each subclass may perform the operation slightly differently. Consider the following example:
public interface animal {
//All implementers must define this method
void speak();
}
This interface states that any Animal MUST have a way to speak. Basically, any type of animal is going to be able to make a noise. We then have 2 subclass, or 2 different types of animals that we create.
public class Dog implements animal {
//Define how a Dog speaks
public void speak() {
System.out.println( "woof" );
}
}
We then define another animal, cat
public class Cat implements animal {
//Define how a Cat speaks
public void speak() {
System.out.println( "meow" );
}
}
In this example, both Cat and Dog are animals, and therefore must be able to speak due to our interface. However, everybody knows that cats and dogs make different sounds. By allowing each subclass to define how it 'speaks', we can give Dog and Cat their own respective sound when the speak() method is called, while ensuring they are both Animals.
In answer to your question more specifically, inheritance forces it's subclasses to have a specific method. In other words, an interface states that "all my subclasses will define each of these methods". What this allows us to do is to write code that deals with the methods in an interface without knowing the specific subclass. We can safely do that because we know that each subclass MUST have defined the method in the interface class. If only the subclasses that use the method defined it, then we would have no way of knowing for sure whether it is safe to call the method on all subclasses.
Just a note: If you do not want a subclass to define the method, you can simply define an empty method like this:
public class MuteAnimal implements animal {
//A MuteAnimal can't speak!
public void speak() { }
}
Inheritance is often useless without polymorphism. It is really not easy to explain it all just in few sentences. My advices would be to look at interfaces for defining behavior (something like can-do relationship), and concrete inheritence for is-a relationships.
In the center of everything as you may learn is something called Single Responsibility Principle. This means that one class has one responsibility, if you are having more of them, you separate the class.
If you take your example, even the Pegasus isn't both horse and bird at the same time 100% percent. It would inherit the horse, but implement specific characteristics of the birds, which would be defined in interfaces, like Flyable for instance. You can say that birds have one way of flying common to them all, so inherit them from Bird. Pegasus is a little different, so that custom logic can be defined after you implement the Flyable interface with method Fly.
Also, the example with horseNoise and birdNoise is little unrealistic, you want one method speak() which will due to internal class alhorithm perform certain action. What if that pegasus could talk? Would you have a method for each word?
Back to Flyable example, say you now have a video-game. Now you can have polimorphism for this: Lets say that in game earthquake happens. You want for each animal that can fly to go and fly. You have a collection of animals currently in game, so you write this:
foreach(Flyable flyableAnimal in animals)
flyableAnimal.Fly();
You just rely on polimorphism ...
These were just some random thoughts, you can find far better examples online, hope this helps ...
If class A inherits from class B, that effectively means two things:
Class A can implicitly use all methods and properties of class B, and need only define that functionality which is in fact unique to class A.
Code which expects an object of type B will accept an object of type A.
Those two features of inheritance are in some sense orthogonal; one can imagine places where either could be useful without the other. Although derived classes can only have one parent class from which they gain implicit access to methods and properties, they may define an arbitrary number of interfaces for which they are substitutable.
Note that while some people insist that interfaces form a "has-a" rather than "is-a" relationship, I think it's better to think of them as saying something "is __able" or "is a __er", the point being that interfaces don't just define abilities, but define substitutability (i.e. "is a") in terms of ability.

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