how to achieve polymorphism in java [closed] - java

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
i can't understand the following program, how to achieve polymorphism in this coding, please explain in simple way...because i am not strong knowledge in java...
class Animal
{
eat() //here this class has one method
}
class Dog extends Animals
{}
class Cat extends Animals
{}
class Wolf extends Animals
{}
class MyMain
{
public static void main(String args[])
{
Animals[] A=new Animals[3];
A[0]=new Dog(); //parent object reference is used to refer child object
A[1]=new Cat();
A[2]=new Wolf();
for(int i=0;i<3;i++)
A[i].eat();
}
please anybody explain this
which book i have to study for improve knowledge in java?

Polymorphism in simple terms
Polymorphism means "Many forms or shapes", which is a phenomenon where objects behave differently although they are closely related. In the following example we have Cat, Dog and Wolf which are all Animal therefore are related but they perform "makesound" differently. In Java the fact that they are related is denoted by Inheritance, the behavior is denoted by a Method and this phenomenon is called Polymorphism.
Polymorphism using your example
I would declare makesound() instead of eat() since it explains it clearly:
class Animal
{
// This method will be overridden by Dog, Wolf and Cat classes.
makesound(){
System.out.println("make sound"); }
}
class Dog extends Animals
{
makesound()
{System.out.println("Bau");}
}
class Cat extends Animals
{
makesound(){System.out.println("Miao");}
}
class Wolf extends Animals
{
makesound(){System.out.println("Uuuu");}
}
class MyMain
{
public static void main(String args[])
{
/* This is where polymorphism happens, although A[0],A[1],A[2] are all Animals,
at run-time we realize that A[0] is infact dog, A[1] is cat and A[2] is wolf
so when call makesound on these objects, the method behaves differently so the
name polymorphism.*/
Animals[] A=new Animals[3];
A[0]=new Dog();
A[1]=new Cat();
A[2]=new Wolf();
for(int i=0;i<3;i++)
A[i].makesound();
}
On a sidenote before you try to understand what polymorphism, please read what method overriding is: http://docs.oracle.com/javase/tutorial/java/IandI/override.html

Polymorphism is the property of different members of a given hierarchy to have different implementation of a given method. In this case to demonstrate polymorphism you need to provide different implementations of eat(or some other method that you add to the base class Animal) for the different child classes.

From Java Tutorial:
The dictionary definition of polymorphism refers to a principle in biology in which an organism or species can have many different forms or stages. This principle can also be applied to object-oriented programming and languages like the Java language. Subclasses of a class can define their own unique behaviors and yet share some of the same functionality of the parent class.
All the subclasses of Animals will share the method eat(), then when you declare your array:
Animals[] A = new Animals[3];
and you initialize its elements:
A[0] = new Dog();
A[1] = new Cat();
A[2] = new Wolf();
you will be able to call the method eat() on each of these objects because of polymorphism.

A example for polymorphism in this case would be:
class Dog extends Animals {
#Override
void eat() {
System.out.printf("Dog eats a bone");
}
}
class Cat extends Animals {
#Override
void eat() {
System.out.printf("Cat eats a mouse");
}
}
class Wolf extends Animals {
#Override
void eat() {
System.out.printf("Wolf eat a living animal");
}
}
Now you just have to call .eat() on your Array of Animals and see the magic happen.
See OracleDocs - Polymorphism for further information about this.

All of these class definitions:
class Dog extends Animals
{}
class Cat extends Animals
{}
class Wolf extends Animals
{}
define new classes that are subclasses of the Animals class.
The dictionary definition of polymorphism refers to a principle in biology in which an organism or species can have many different forms or stages. This principle can also be applied to object-oriented programming and languages like the Java language. Subclasses of a class can define their own unique behaviors and yet share some of the same functionality of the parent class.
As illustrated in the picture above, subclasses inherit some features of the base class and inside them you have access to both the subclass and subclass features(that are visible to subclass).
Some advantages of polymorphism:
Same interface could be used for creating methods with different implementations
Reduces the volume of work in terms of distinguishing and handling various objects
Supports building extensible systems
Complete implementation can be replaced by using same method signatures

Polymorphism can be explained better if you use an interface (because it can not be instantiated):
interface Animal {
void makeSomeNoise();
}
class Cow implements Animal {
public void makeSomeNoise() {
System.out.println("Moo!");
}
}
class Fox implements Animal {
public void makeSomeNoise() {
System.out.println("Ring-ding-ding-ding-dingeringeding!");
}
}
This shows that an animal can not make any noise, but a cow and a fox can. But they make different noises. This is the "principle in biology in which an organism or species can have many different forms or stages". Basically one thing can many different faces.
If you now declare your array like:
Animal[] animals = new Animal[2];
animals[0] = new Cow();
animals[1] = new Fox();
And then let them make some noise with:
animals[0].makeSomeNoise();
animals[1].makeSomeNoise();
You would get following output:
Moo!
Ring-ding-ding-ding-dingeringeding!
So you have two animals but they make different noises.

Related

General question about interfaces in Java [duplicate]

This question already has answers here:
What does it mean to "program to an interface"?
(33 answers)
Closed 3 years ago.
I'm just getting started with interfaces and I cannot grasp the concept.
class Client {
IServer x = new Server();
void m() {
x.p();
}
}
interface IServer {
void n();
void p();
}
class Server implements IServer{
public void n() {
System.out.println("Methode n");
}
public void p() {
System.out.println("Methode p");
}
}
So client should be able to use the methods provided by server through the interface IServer.
Is IServer x = new server(); correct? The examples that I found (https://www.w3schools.com/java/java_interface.asp) all build interfaces and then the main class calls the other class without using the interface.
Thank you for your help, I guess I'm just missing something obvious here...
A good explanation of how interfaces work and why they're used can be done with the following example. Let's say we have a zoo object with animals. We want all the animals to be able to make a noise depending on what animal they are. We start with the following class:
public class Zoo {
private List<Animal> animals;
public Zoo() {
animals = new ArrayList<>();
}
public void addAnimal(Animal animal) {
animals.add(animal);
}
public void roar() {
for(Animal a : animals) {
a.makeNoise();
}
}
}
This is basically just an object containing a list of animals and we can add animals to this list. When we call the method roar we want all the animals to make their own noise and print it to the console. Now this is where interfaces are useful, since we know we will have multiple types of animals we can specify what a basic "animal" can do, these are generic traits that describe that they can do something but not how. For instance, a box and a human can both move, but a human can move on its own and a box cannot. Or maybe a human can move up stairs but a dog cannot. Knowing this, we create a basic interface describing that an animal can make a noise:
public interface Animal {
void makeNoise();
}
This will allow us to create as many animals as we want, while forcing them to implement our defined functionalities. So now, we can create some animals:
public class Cat implements Animal {
private String name;
public Cat(String name) {
this.name = name;
}
#Override
public void makeNoise() {
System.out.println(name + "said Meow");
}
}
public class Dog implements Animal {
#Override
public void makeNoise() {
System.out.println("Woof");
}
}
As you can see, we can give both classes their own functionality, while still enforcing both classes to at least be able to make their respective noise. In this case a cat can have a name, while a dog cannot. This means that we can now fill our Zoo with any animal we want, and since they all have the same overlaying interface we don't have to, for instance, create more than one Collection to store each type of animal. We can just throw them all on one big pile based on their interface and we can call the proper method through the interface:
public void run() {
Zoo zoo = new Zoo();
zoo.addAnimal(new Cat("Bob"));
zoo.addAnimal(new Dog());
zoo.addAnimal(new Cat("William"));
zoo.roar();
}
As far as types are concerned. It works like it does in real life. Following our example, a dog is an Animal, but an animal is not necessarily a dog. Since our code in this case (when it's inside the zoo) only knows that it has Animals, but not what specific types, it only allows us access to the functionalities defined in the interface.
This means that, we are allowed to do stuff like:
Animal a = new Dog();
Dog b = new Dog();
Animal c = new Cat("Bob");
Cat d = new Cat("Wilbert");
But not:
Animal a = new Dog();
Dog b = a;
Since, as soon as we assign a and say "you're of type animal" it doesn't know if the data inside a is actually a dog or not.
A better documentation is the official at https://docs.oracle.com/javase/tutorial/java/IandI/createinterface.html
There are a number of situations in software engineering when it is important for disparate groups of programmers to agree to a "contract" that spells out how their software interacts. Each group should be able to write their code without any knowledge of how the other group's code is written. Generally speaking, interfaces are such contracts.
With an Interface, you can enforce a Class to have a particular behavior, defined inside the Interface, BUT implemented inside the class that implement that Interface.
And also, if you know that an object Dog implements the Interface Run and that Interface declare the method run() {}, you can safely invoke the method run on the object Dog, because it contains the method implementation:
Interface Run
{
public void run();
}
class Dog implements Run
{
public void run()
{
// the dog is running
}
}
Dog dog = new Dog();
dog.run();

Creating an object where the class name on the left and right sides are different [duplicate]

This question already has answers here:
What does it mean to "program to an interface"?
(33 answers)
Closed 6 years ago.
I have seen a few references of instantiating a new object as follows, especially when using Inheritance.
Cat cat = new Animal();
However, I do not know what this concept is called. and so, I'm unable to read up on it.
I have two questions.
What is this concept called?
How is this possible, that, you can
hold/refer to an object using a type that is different from it's
original class?
In object oriented programming world, this concept is called as inheritance.
It is possible to assign a child's object to parent's reference. Err, too techie, eh? So take it this way, a Cat is a kind of Animal, but the reverse is not necessarily true.
So, an Animal can be a Cat, Dog, or whatever, because cats and dogs do have properties of an animal. This is also called generalization and specialization. An Animal is a generalized category, but a Cat is a specialized category of Animals.
There are a lot of resources available on the Internet. Have a look and learn about the Object Oriented Programming paradigm. Good luck!
The basic concept in play here is inheritance. A good place to start reading about it is https://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html
Your example is reversed — it should be
Animal animal = new Cat();
This is because the Cat class would be a specific kind of Animal — having everything needed to make an Animal object, plus some extras.
In code, this could look something like:
public class Test
{
public static class Animal
{
protected String sound;
public String getSound() { return sound; }
public Animal() { sound = ""; }
}
public static class Cat extends Animal
{
public Cat() { super(); sound = "meow"; }
}
public static void main(String[] args) {
Animal animal = new Cat();
System.out.println(animal.getSound());
}
}
And the result would be
meow
because the Cat object has the getSound() method from the parent Animal, but was created with its own constructor and set the data appropriately.

Polymorphism in java: Why do we set parent reference to child object?

I want to understand the use-case of setting a parent reference to a child object.
Example: Dog class extends Animal class. (No interfaces, mind it)
I would normally create an object of Dog like this:
Dog obj = new Dog();
Now, since Dog is a subclass of Animal it already has access to all of Animal's methods and variables. Then, what difference does this make:
Animal obj = new Dog();
Please provide a proper use-case with an code snippet of its use. No theoretical articles about 'Polymorphism' or 'Coding to interfaces' please!
Code:
public class Polymorphism {
public static void main(String[] args){
Animal obj1 = new Dog();
Dog obj2 = new Dog();
obj1.shout(); //output is bark..
obj2.shout(); //output is bark..
}
}
class Animal{
public void shout(){
System.out.println("Parent animal's shout");
}
}
class Dog extends Animal{
public void shout(){
System.out.println("bark..");
}
}
class Lion extends Animal{
public void shout(){
System.out.println("roar..");
}
}
class Horse extends Animal{
public void shout(){
System.out.println("neigh");
}
}
Output is the same for both the cases. Then why do we set parent reference to child object?
Let me code some time.
List<String> list = new ArrayList<String>;
list.doThis();
list.doThat();
Oh wait ..I'm gone mad. I want to use LinkedList instead of ArrayList
List<String> list = new LinkedList<String>;
list.doThis();
list.doThat();
Yup, I have to change only declaration part. No need to touch all of my code. Thanks to programming to interfaces and with super classes.
This is an implementation of a principle which says -
Program to an interface, not to an implementation.
As an example, if you design a method to accept a reference of type Animal, then in future you can easily pass an= Cat implementation to it (provided of course that the Cat is a sub-type of Animal.
Which means -
public void doSomethingWithAnimal(Animal animal) {
// perform some action with/on animal
}
is much more flexible than -
public void doSomethingWithAnimal(Dog d) {
// your code
}
because for the first method, you can easily do something like -
doSomethingWithAnimal(new Cat());
if you ever decide to create new Cat type, inheriting from Animal.
Think generally, you will know java casting/oop concept.
Dog is a type of Animal so you can assign it to an animal.
But you can't assign Animal to a Dog. Because it can be any other animal like Cat. If you are sure the object is Dog, you can caste that to Animal. If the Animal is of type Dog then you cannot magically cast to a Goat.
Although there are some good answers (among the "meh" ones), it seems like none was acceptable for you. Maybe they are too theoretical or contain details that you are not interested in. So another try:
For the example that you described, it does not matter. If you really only have a two-line method like
void doit()
{
Animal x = new Dog();
x.shout();
}
then you could also have written
void doit()
{
Dog x = new Dog();
x.shout();
}
and this would not have a direct disadvantage.
One could even generalize this statement: For a reference that is only used locally, it does not matter. When you declare the reference in the method, and only use this reference in this method, and do not pass it to other methods, then there is no direct advantage in declaring it as Animal instead of as Dog. You can to both.
But...
even if you are not interested in this, I can't omit it:
... using the parent type is part of a best practice:
You should always use the least specific type that is sufficient for what you want to do
This has various technical reasons, regarding abstraction, generalization, flexibility, the application of polymorphism, and one could even go so far to call it a sort of "type hygiene".
And this explicitly also refers to the case where the reference is only used locally: If you don't want to call methods that are specific for the type Dog, but only want to call methods from the Animal class, then you should make this clear by declaring the variable as an Animal - simply because that's the least specific type that you need. So there is an indirect advantage of using the type Animal in these cases - namely that it is clear that the following code will only use methods of the Animal class, and none of the Dog class.
One could continue and go very far with further justifications, use case examples and technical details here. But for this, you may refer to the other answers, or some intermediate or advanced texbooks and tutorials.
Okay. I think I got my answer.
public class Polymorphism {
public static void main(String[] args){
Animal obj1 = new Horse();
Horse obj2 = new Horse();
obj1.shout(); //output is neigh..
obj2.shout(); //output is neigh..
obj1.winRaces(); /*But this is not allowed and throws compile time error,
even though the object is of Animal type.*/
}
}
class Animal{
public void shout(){
System.out.println("Parent animal's shout");
}
}
class Horse extends Animal{
public void shout(){
System.out.println("neigh..");
}
public void winRaces(){
System.out.println("won race..");
}
}
So, when we use parent reference for child class object, we cannot access any specific methods in child class (that are not present in parent class) using that object.
This would be when you want the code that you're writing to work against the Animal interface instead of the Dog implementation. Creating an object in this way makes your code more robust in the long term.
I frequently use:
List<Object> aList = new ArrayList<>();
This is important when defining class level variables, because you want your whole object to work even if you change an unimportant detail later.
When you start with such a simple example, you can't see any benefits because you have tightly coupled the variable to the actual type of object it will hold.
Polymorphism comes into its own only when you consider method declarations where the parameter is of the least specific type needed by the method's implementation: then you can call it with any subtype and the method will know what to do with it, even though it has no knowledge of the actual object type. That's the essence of Liskov substitutability of types.
So imagine you have a method
int getAge(Animal a) {
return Days.toYears(currentDate() - a.dateOfBirth());
}
The method will work against any Animal, even those you defined after defining the method.
But, if you happen to understand the above, yet ask specifically why one would write
Animal a = new Dog();
then it still often makes sense: you promise up-front that you won't refer to any dog-specific aspects of the instance. Typically you'll see
List<String> strings = new ArrayList<>();
and in this case we know that the rest of the code doesn't rely on the specific choice of ArrayList as list implementation. This is a much smaller difference than the one decribed above, but it's a combination of brevity, safety, and custom which makes it stick.
Looking at the question:-
Polymorphism in java: Why do we set parent reference to child object?
In a method like below(Factory Pattern):-
public Animal doSomething(String str){
if(str.equals("dog")){
return new Dog();
}
else if(str.equals("cat")){
return new Cat();
}
else {
return new Animal();
}
}
You get a type of Animal and actual object of either Dog or Cat so calling a method of Animal will call the method overridden in actual Object of either Dog or Cat if the called method is overridden in base class. It provides you with the flexibility at run time to decide which method to run depending on the actual object and overridden method in base class if any.
The complete example is as under :-
package com.test.factory;
public class Animal{
public void shout(){
System.out.println("Parent animal's shout");
}
}
package com.test.factory;
public class Dog extends Animal{
#Override
public void shout(){
System.out.println("bark..");
}
}
package com.test.factory;
public class Horse extends Animal{
#Override
public void shout(){
System.out.println("neigh");
}
}
package com.test.factory;
public class Lion extends Animal{
#Override
public void shout(){
System.out.println("roar..");
}
}
package com.test.factory;
public class AnimalFactory {
public Animal createAnimal(String str){
if(str.equals("dog")){
return new Dog();
}
else if (str.equals("horse")){
return new Horse();
}
else if(str.equals("lion")){
return new Lion();
}
else{
return new Animal();
}
}
}
package com.test.factory;
package com.test.factory;
public class Polymorphism {
public static void main(String[] args){
AnimalFactory factory = new AnimalFactory();
Animal animal = factory.createAnimal("dog");
animal.shout();
animal = factory.createAnimal("lion");
animal.shout();
animal = factory.createAnimal("horse");
animal.shout();
animal = factory.createAnimal("Animal");
animal.shout();
}
}
Output is :-
bark..
roar..
neigh
Parent animal's shout
The AnimalFactory has a createAnimal method which returns Animal. Since Dog, Lion and Horse are all animals. So we are able to create Dog, Lion and Horse objects by using Animal return type. What we achieved using Animal return type is
Animal animal = new Dog();
Animal animal = new Lion();
Animal animal = new Horse();
which is not possible without the Animal return type.
If I use return type as Dog in createAnimal method then it cannot return Lion or Horse and like wise.

Why different types of object reference is allowed in Java?

I wonder why it is allowed to have different type of object reference?
For example;
Animal cow = new Cow();
Can you please give an example where it is useful to use different type of object reference?
Edit:Cow extends Animal
This is at the heart of polymorphism and abstraction. For example, it means that I can write:
public void handleData(InputStream input) {
...
}
... and handle any kind of input stream, whether that's from a file, network, in-memory etc. Or likewise, if you've got a List<String>, you can ask for element 0 of it regardless of the implementation, etc.
The ability to treat an instance of a subclass as an instance of a superclass is called Liskov's Substitution Principle. It allows for loose coupling and code reuse.
Also read the Polymorphism part of the Java tutorial for more information.
On a simpler note, this enables polymorphism. For example you can have several objects that derive from Animal and all are handle similar.
You could have something like:
Animal[] myAnimal = {new Cow(), new Dog(), new Cat()};
foreach (Animal animal in myAnimal)
animal.Feed();
The Feed() method must then be overriden within each child class.
By the way, code is C#-like but concept is the same in Java.
This is basically a concept of standardization.
We know that each animal have some common features. Let us take an example of eating and sleeping, but each animal can have different way of eating or sleeping ... then we can define
public abstract class Animal
{
public abstract void Eat();
public abstract void Sleep();
}
//Now Define them in various classes..
public class Cow extends Animal
{
pubic void Eat()
{
//process of eating grass
}
public void Sleep()
{
//process of sleeping
}
}
public class Lion extends Animal
{
public void Eat()
{
//process of eating flesh
}
public void Sleep()
{
//process of sleep
}
}
Now you do not have to define different objects to different classes... just use Animal and call generally
public class MyClass
{
public static void main(String[] args)
{
Animal _animal = new //think the type of animal is coming dynamically
//you can simply call
_animal.Eat();
_animal.Sleep();
// irrespective of checking that what can be the animal type, it also reduces many if else
}
}
This is called polymorphism and it's one of the most powerful aspects of Java.
Polymorphism allows you to treat different objects the same.
It's a great way to create re-usable, flexible code.
Unfortunately it's a part of Java that new programmers often take awhile to understand.
The example you've provided involves inheritance (extending a class).
Another way to enjoy the benefits of polymorphism is to use interfaces.
Different classes that implement the same interface can be treated the same:
class Dog extends Animal implements Talker {
public void speak() {
System.out.println("Woof woof");
}
}
class Programmer implements Talker {
public void speak() {
System.out.println("Polymorphism rocks!");
}
}
interface Talker {
public void speak();
}
public static void testIt() {
List<Talker> talkerList = new ArrayList<Talker>();
talkerList.add(new Dog());
talkerList.add(new Programmer());
for (Talker t : talkerList) {
t.speak();
}
}
Simply putting all Cows are Animals. So JAVA understands that when Cow extends Animal, a Cow can also be called as Animal.
This is Polymorphism as others have pointed out. You can extend Animal with Dog and say that Dog is also an Animal.
In another class/method you might want to use different implementations of the same interface. Following your example, you might have something like:
public void feed( Animal animal ) {
animal.getHome().insertFood(animal.getFavFood());
}
Now you can implement the details in your animal classes and don't have to extend this method anytime you add a new animal to your programm.
So in some cases you need the common interface in order not to implement a method for each implementation, whereas on other occasions, you will need to use the explicit implementation.
This is an inheritance 101 question.
It allows objects that share common functionality to be treated alike.
It also allows specific implementations to be supplied at runtime that are subclasses of an abstract type.
I could probably ramble on for ages. Perhaps thus question is just too broad to answer here.

Is co-variance safe here?

class Food{}
class Meat extends Food{}
class Animal{
void feed(Food f){}
}
class Lion extends Animal{
void feed(Meat m){}
}
void foo(Animal a){
Food f = new Food();
a.feed(f);
}
What will happen if we send to foo(new Lion()) ?
I know that it will get error but I need the explanation please
Your Lion can eat Meat, but it can also eat any kind of food (like Spinach).
If your Lion could not eat any kind of Food, then it could not be considered an implementation of Animal.
This is critical to understand when deciding to use sub-classing and class inheritance as a means of constructing programs: you don't make your subclasses more specific than your interface or super classes.
For sub-classing to work in ways that solve problems (instead of create problems), you need to abide by this guideline: All subclasses must be functionally equivalent to the super-class (Liskov Substitution Principle) This means that three classes which provide database access to three different databases is a good candidate for being subclasses from a common class (or perhaps sharing a common interface), because the "functionality" is "offer database access".
Where your Lion example falls short is that according to your definition of Animal a real world, Lions are not an Animals because real world Lions don't eat any kind of Food. Real world Lions are more specific in their food eating ability than the general definition of an unknown animal. And it is this functional difference which makes modeling real world Lions as subclasses of this specific definition of Animal a bad fit.
You could easily fix this by having the Animal "eat food" method throw an IncompatibleFoodException, which changes the definition of an Animal from something that "eats food" to something that "eats or rejects food".
This violates the Liskov substitution principle, so it should likely be avoided (as Edwin says, it's really not an Animal if it can't eat Food).
Perhaps against first thought, this will actually not result in an error, but rather will call Animal::feed instead of Lion::feed as expected.
Just reread the title, and to answer the question specifically: No, covariance is not safe here (in terms of behaviour. In terms of syntax it is.).
Quick copy and paste of the question into an example:
class Food{}
class Meat extends Food{}
class Animal{
void feed(Food f){
System.out.println("om nom nom");
}
}
class Lion extends Animal{
void feed(Meat m)
{
System.out.println("OM NOM NOM");
}
}
public class test
{
public static void main(String[] args)
{
foo(new Lion());
}
static void foo(Animal a){
Food f = new Food();
a.feed(f);
}
}
Outputs "om nom nom"

Categories