Abstraction clarification. Java - 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();

Related

Class which extends abstract class

I have a problem, i have abstract class which implements interface, and one more class which extends this first abstract class, but i got an error it says that i my second class must inherit methods from interface, and i dont want that, i also can change it to abstract class too, but then i can't call constructor from that class in some third class, how can i fix this?
I searched for answer on internet but couldnt find it, and i dont understand abstract classes rly good so i can't solve it.Please help
(p.s. sorry for my english, it is really bad)
Edit:
I have an assignment where it is requiered that my second class needs to extend abstract class, and i am implementing interface because they also gave me main class in which they are making object from constructor in my second class and then they are using it with type of interface, i dont know if this makes any sense, code is pretty long, but i will give some lines: Here is my main class
(NationalTeam bulgaria = new NationalTeam("Bulgaria", Formation.F352, "Bulgaria");
nationalManager.setManagingTeam(bulgaria);) (bulgaria must be type of interface),
also here is my constructor from second class which extends abstract class:(public NationalTeam(String name,Formation formation,String country){
super(name,formation);
this.country=country;
})
Abstract class:Abstract classes may have abstract methods which means methods are methods without implementations.
when you are extending a abstract class A, methods of class A must be implemented by your subclass lets say B unless you make your child class B an anstract class.
You need to think how want to design the system not how compiler forces you.
If design says second class should be abstract then do it and then ultimately implement your abstract methods in your implementation.
On the other way, if second class is your implementation not abstract, the you have to provide implementation to make object of it
my second class must inherit methods from interface, and i dont want that
Really? Then why did you declare the interface in the first place? Why the abstract class needs to implement the interface?
Interfaces are supposed to be a higher level of abstraction. It is a contract between the client code and the library. It creates a interface between the client code and the library. It's like saying "I have the abilities to do the things the interface requires me to do". And you say you don't want to?
So there are two good ways and one bad way to fix this:
Good
Don't extend the abstract class. Because if you do, it probably does not make sense.
The abstract class don't extend the interface.
Bad (This is really really bad)
Add the methods in the interface and leave the body blank or return a random value. Again, don't do this if you don't have to.

Method overriding vs abstract method

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?

Add methods to classes without breaking implementations

Let say I have 2 classes called class Cow ad class Pig.
They both implements interface Animal.
For the interface there are only 2 methods called public void eat() and public void speak().
All is fine. But while this seems good making use of interfaces, I thought that if I ever needed to add method(s) to this interface, implementation would break, namely I would need to go implement the new methods in these classes, which breaks the "close-open principle".
So I thought of, in addition to interface, I would make use of abstract class as well, should it be needed that I needed to add new method(s) in the future.
So, for example, public class Cow extends ... implements Animal.
It sounds like a good plan (if it is not, please correct me).
But the problem is, what if these classes extend already some other class? In such case, I could not extend 2 classes.
So my question is:
Is there a pattern where I could declare a common interface of
related classes while withholding the ability to add new methods in
the future that doesn't break the "closed-open principle" and doesn't
break implementations?
With Java 8 there are default methods
public interface Animal {
void eat();
void speak();
default void sleep(){}
}
Now your Animal must override eat and speak but may choose to override sleep.
Pre Java 8 using a abstract class was the usual way to protect against having to implement every interface method. As you noted, this doesn't work with multiple inheritance so cannot be used to solve all cases.
P.S. don't declare interface methods public, this is the default visibility for all interface members.
In Java 8, interfaces can define default methods for this purpose.

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