Why do we need to override the methods of parent class? - java

I mean if we want to rewrite all the content of the method in the child class and change its function, why couldn't we just write a new method with a different name? What's the difference? I know this is a simple question. But I am new to programming and very confused. THX.

It's about giving different behaviour to common functionality for that type of thing, for example let's assume all Vehicles beep, but a Car Honk's and a Moped Meep Meeps!
class Vehicle {
public void beep() {
System.out.println("Beep!");
}
}
class Car extends Vehicle {
#Override
public void beep() {
System.out.println("Honk!");
}
}
class Moped extends Vehicle {
#Override
public void beep() {
System.out.println("Meep Meep!");
}
}

That's called Polymorphism. Have a look at the link.
A simple example is the Java Collections framework. You have an interface List when you are using it. You don't want to know how add or size is working. It should just work.
But when you are on the implementation side there are differences for ArrayList or a LinkedList in the way how they manage the items, that where stored in there.
When you look at already implemented methods in super classes, you might need one method to have a different behavior. Now pretend you have some method calls in your current code. If you don't want them to change, so you just override that method and the client does not have to change his code in order to use your functionality.

Overriding is a feature that is available while using Inheritance.
It is used when a class that extends from another class wants to use most of the feature of the parent class and wants to implement specific functionality in certain cases.
class Animal{
public void move(){
System.out.println("Animals can move");
}
}
class Dog extends Animal{
public void move(){
System.out.println("Dogs can walk and run");
}
}
class Cat extends Animal{
}
public class TestDog{
public static void main(String args[]){
Animal a = new Animal(); // Animal reference and object
Animal b = new Dog(); // Animal reference but Dog object
Animal c = new Cat(); // Animal reference but Cat object
a.move();// runs the method in Animal class
b.move();//Runs the method in Dog class
c.move();//Runs the method super method
}
}
So by using a parent class you dont need to define move() in each of class that extends animal you can override it wherever necessary.

Related

Java: Create particular child class object in Java

So let's suppose that I have a class Animal in Java, and 3 child classes. The structure looks like this
class Animal{
...
public breed(){
//create a new child class object here
}
}
class Bird extends Animal{
...
}
class Bear extends Animal{
...
}
class Frog extends Animal{
...
}
I want to create another object in breed class, but I want to create an object of the same child class, from which the method breed() was executed. For instance, if frog.breed() was executed I want to create a new Frog object there (assumming frog is a Frog object), if bear.breed() was executed I want to create a new bear object etc.
Is there any way to handle it in animal class, or I have to override method in every child class?
It's possible if you pass a reference to a function. I suspect method references and passing functions as arguments may be a bit beyond your level right now, but it's not that complicated.
class Animal {
private final Supplier<Animal> ctor;
Animal(Supplier<Animal> ctor) {
this.ctor = ctor;
}
public Animal breed() {
return ctor.get();
}
}
class Bird extends Animal {
public Bird() {
super(Bird::new);
}
}
The advantage of overriding is that Java allows to you make the return type more specific. So if you have a Bird bird; you could do Bird chick = bird.breed();.
class Bird extends Animal {
public Bird breed() { //super return type is Animal, this return type is more specific
return new Bird();
}
}
Without overriding, you can't make the return type more specific, so you would have to assign it to a variable of type Animal chick = bird.breed(), unless you were to cast it.
Also achievable with reflection, but you should avoid it if possible.
Yes, you can do it, using reflection. But this approach isn't recommended, cause it's error-prone and you should consider rather using standard Java inheritance constructions.
Example with recursion:
class Animal{
public Animal breed() throws InstantiationException, NoSuchMethodException, InvocationTargetException, IllegalAccessException {
return this.getClass().getDeclaredConstructor().newInstance();
}
}

Abstract class or casting?

I'm trying to figure out whether implementing individual methods of a subclass in an abstract superclass, or casting is the better way to go about the following scenario.
Suppose I have an abstract class Animal which has two subclasses, Dog and Cat and a Main class where I save objects of Dog and Cat in an Animal array. The following is how I would go about using methods of the subclasses in a more generalized array.
class Main{
public static void main(String[] args){
Animal[] animalArray = new Animal[2];
animalArray[0] = new Cat();
animalArray[1] = new Dog();
for (Animal a : animalArray){
if (a.getClass().equals(Dog.class){
((Dog)a).bark();
} else {
((Cat)a).meow();
}
}
}
}
However a friend suggested that casting isn't best practice, and that I should define each method in the abstract superclass in the following way:
public abstract class Animal{
public abstract String meow(){
return null;
}
public abstract String bark();
return null;
}
}
After setting the return values of these methods to null I would need to use #Override and implement them in the respective subclasses.
Which way is better? I'm afraid the abstract class will be too large and will have methods assigned to subclasses that don't make sense (even if all they do is return null). I think by using casting I can make more precise uses of the methods.
meow() and bark() shouldn't be defined in the Animal class. These methods are specific to Cat and Dog classes.
You should define an abstract method as shown below, in the Animal class and override it in the sub classes.
public abstract class Animal {
public abstract String action() {};
}
public class Dog extends Animal {
#Override
public String action() {
//your implementation (bark)
}
}
public class Cat extends Animal {
#Override
public String action() {
//your implementation (meow)
}
}
Hope it answers your query.

How to wrap different type of object in one single wrapper object

i have a condition where i need to use a fixed Method signature which may accept different type of object. one solution i think is to use a super class and let all as a subclasses. however is there any good elegant design pattern kind of solution where we solve this
also once method gets an object of certain type can we know the type of instance without instanceof check ?
please suggest.
Your question is a little bit vaque, and can be interpreted in two different ways:
Implementing different behavior in one class
Let's assume you have two different classes: Cat and Dog. Then you have a class Animals and want to do something like this:
Cat cat = new Cat();
Dog dog = new Dog();
Animals animals = new Animals();
animals.feed(cat);
animals.feed(dog);
Here feed() executes different code, depending on the parameter type:
public class Animals {
public void feed(Cat cat) {
// ... feed the cat
}
public void feed(Dog dog) {
// ... feed the dog
}
}
This is called method overloading.
Implementing different behavior in different classes
On the other hand, you could define an interface Pet which provides a method, let's say eat():
public interface Pet {
void eat();
}
Then Cat and Dog should implement Pet to get different behavior:
public class Cat implements Pet {
public void eat() {
//...
}
}
public class Dog implements Pet {
public void eat() {
//...
}
}
Then your class Animals would look like this:
public class Animals {
public void feed(Pet pet) {
pet.eat();
}
}
Implementing an interface is a better pattern than inhering a super class. in that way your classes retain their one-inheritance capacity.
regarding the other question about instanceOf, there is rarely a genuine need to determine the actual class of the object. you can always resort to polymorphism. put all methods that you need to invoke on the object in the interface itself. in that way you will never need to know the actual type.

Instantiating interfaces in Java

I have this interface:
public interface Animal {
void Eat(String name);
}
And this code here implements the interface:
public class Dog implements Animal {
public void Eat(String food_name) {
System.out.printf(food_name);
}
public static void main(String args[]) {
Animal baby2 = new Dog(); // <- this line
baby2.Eat("Meat");
}
}
My question is, why does the code work? An interface cannot be instantiated. Yet in this case, interface was instantiated (marked with the comment).
What is happening here?
No it is not - you are instantiating a Dog, but since a Dog is an Animal, you can declare the variable to be an Animal. If you try to instantiate the interface Animal it would be:
Animal baby2 = new Animal();
Try that, and watch the compiler scream in horror :)
Dog is not an interface: Dog is a class that implements the Animal interface.
There's nothing untoward going on here.
Note that you can instantiate an anonymous implementation of an interface, like so:
Animal animal = new Animal() {
public void Eat(String food_name) {
System.out.printf("Someone ate " + food_name);
}
};
Let's consider below code:
interface Cookable {
public void cook();
}
class Food {
Cookable c = new Cookable() {
public void cook() {
System.out.println("anonymous cookable implementer");
}
};
}
The preceding code creates an instance of an anonymous inner class, but here, the new just-in-time class is an implementer of the Cookable interface. And note that this is the only time you will ever see the syntax:
new Cookable()
where Cookable is an interface rather than a nonabstract class type. Think about it:
You can't instantiate an interface, yet that's what the code looks like it's doing. But, of course, it's not instantiating a Cookable object-- it's creating an instance of a new anonymous implementer of Cookable.
You can read this line:
Cookable c = new Cookable(){}
as "Declare a reference variable of type Cookable that, obviously, will refer to an object from a class
that implements the Cookable interface. But, oh yes, we don't yet have
a class that implements Cookable, so we're going to make one right
here, right now. We don't need a name for the class, but it will be a
class that implements Cookable, and this curly brace starts the
definition of the new implementing class."
Important to remember for anonymous interface implementers-- they can implement only one interface. There simply isn't any mechanism to say that your anonymous inner class is going to implement multiple interfaces. In fact, an anonymous inner class can't even extend a class and implement an interface at the same time. The innve class has to choose either to be a subclass of a named class and not directly implement any interface at all or to implement a single interface.
So don't be fooled by any attempts to instantiate an interface except in the case of an anonymous inner class. The following is not legal:
Runnable r = new Runnable(); // can't instantiate interface
whereas the following is legal, because it's instantiating an implementer of the Runnable interface(an anonymous implementation class):
Runnable r = new Runnable() {
public void run(){ }
};
You can read my article here.
What you're observing here is the Dependency inversion aspect of SOLID.
Your code is depending on the abstraction of the Animal contract by instantiating a concrete implementation of it. You're merely stating, "I'm instantating some object, but regardless of what that object actually is, it will be bound to the contract of the Animal interface."
Take, for instance, these sorts of declarations:
List<String> wordList = new LinkedList<>();
Map<Integer, String> mapping = new HashMap<>();
In both of those cases, the primary aspect of the list and map is that they follow the generic contract for a List and Map.
Animal baby2 = new Dog(); //HERE!!!!!!!!!!!!!!!!!!!!!!
Surely you are not instantiating the Animal. You are only referring the Dog instance to it.
In java we can take the super class reference.
This is a case of polymorphism, It looks like you are creating 'Animal' object but it is not. You are creating 'Dog' object which is calculated on run time.'Animal' acts as contract. Interface can not be instantiated directly but can be used as type by upcasting its subclass. You can also use anonymous class to instantiate an object as 'Animal' type.
Animal baby2 = new Dog(); //upcasting polymorphically
Animal baby3=new Animal(){
public void Eat(String food){System.out.println("fdkfdfk"); }
}
//You can instantiate directly as anonymous class by implementing all the method of interface
The interface Animal is not be intantiated but be implemented by Dog.And a Dog is intantiated
When you say:
Animal baby2 = new Dog();
the reference type is Animal(the interface) which points to a concrete implementations (Dog). The object type Dog is concrete and can be instantiated. In this case, as long as Dog hasanimal point to Dog. a concrete implementation of all the methods in the interface, you can make a reference type of
If you did something like,
Animal baby2 = new Animal(); // here you are actually instantiating
this would be invalid because now you are trying to create a concrete object from an abstract implementation.
The Interface Animal acts as the data type to the class Dog. You're actually instantiating the Dog class not the interface or it's data type.
To have a wider picture :
Animal [] Zoo = new Animal[10] ; // is also correct
but why ?
The whole idea is that in the table above you can put 10 animals of different types. The only conditions for this is that all the animals entering the Zoo must implement the interface Animal .
public interface Animal {
void Eat();
}
class Wolf implements Animal { void Eat (){
System.out.println("Wolf eats meat ") ;}}
Class Zebra implements Animal{ void Eat (){
System.out.println("Zebra eats the grass ") ;}}
class test {
public static void main (String args []) {
Animal [] Zoo = new Animal[2] ;
Zoo[0] = new Wolf() ;
Zoo[1] = new Zebra() ;
//so you can feed your animals in Zoo like this
for (int i=0 ; i<Zoo.lenght;i++) {Zoo[i].Eat();}
}
}
You can't instantiate an interface. The functionality can be considered similar to that of an abstract class. You can have a reference to the interface but you don't create an object of interface. If you do something like this....
Animal a = new Animal();
The compiler will show an error- "Cannnot instantiate the type Animal".
Actually you can instantiate the interface. Here is the code you can try
public static void main(String args[]) {
System.out.println(new Animal() {
public String toString() {
return "test";
}
});
}
This program runs successfully and prints test
Try it.
Here it is just referencing to the interface but instantiation is done by the class only.
for e.g
Animanl a = new Dog
Animal a - variable is referenced
new Dog - now Memory is allocated
Java 8 let you use, the functional interface,
#FunctionalInterface // this is not mandatory
interface A{
void m1(); // only one abstract method allowed for functional interface
}
class Main{
public static void main(String a[]){
// old usage
A a1 = new A(){
#Override
public void m1(){
System.out.println("Call Me normally");
}
};
a1.m1();
// new in java 8, functional interface
A a2 = ()-> System.out.println("Call Me as functional interface");
a2.m1();
}
}
What have you done is type casting. You have created an instance of class dog and has type caste it to interface animal.It is an example of runtime polymorphosim. But yes an interface can be implemented and I have reached here while searching for this.
i.e.
public class demo16{
interface cardio{
void run();
}
static void foo(){
cardio c = new cardio(){ //HENCE instance of "interface cardio" is being created inside a method foo
public void run(){
System.out.println("How you doing ! ");
}; //HENCE observe the ";" beside }
}; //HENCE observe the ";" beside }
c.run();
}
public static void main(String [] args){
foo();
}
}

Is this still polymorphism?

While coding, I got an interesting doubt about polymorphism and I couldn't understand a solution for this.
public class Animal {
public void getLegs() {
SOP("4 legs");
}
}
public class Kangaroo extends Animal {
public void getLegs() {
SOP("2 legs");
}
public static void main(String[] args) {
Animal a = new Kangaroo(); // without changing this how can I get Animal getLegs
SOP(a.getLegs()); // Important Line
}
}
Now If I want to call the getLegs method of Animal, how do I? Is it possible? Is it still polymorphism?
Yes, it is the most basic form of demonstrating polymorphisim.
Basically you are dealing with an Animal named a. When you call a.getLegs() your code doesn't bind to the implementation of getLegs() in Animal, rather it binds to the lowest sub-class implementation, getLegs() in Kangraoo().
If the Animal has an implementation, it is said to be hidden by the subclass implementation. If Animal has no implementation, then it is not possible to construct stand-alone classes of Animal as they lack implementations for all of the required methods, and under such a circumstance, Animal is said to be an abstract class (one that cannot be constructed directly, but only can be constructed by it's sub classes).
If you really want to call your method for Animal, and you can employ a static method, you can use hiding instead of overriding.
It works as follows: for static methods only, the called method is the one related to the declared type, not the object instance. In other words, it follows the class because the method is a class method, not an instance method.
An example, adapted from this page:
public class Animal {
public static void testClassMethod() {
System.out.println("The class" + " method in Animal.");
}
public void testInstanceMethod() {
System.out.println("The instance " + " method in Animal.");
}
}
public class Kangaroo extends Animal {
public static void testClassMethod() {
System.out.println("The class method" + " in Kangaroo.");
}
public void testInstanceMethod() {
System.out.println("The instance method" + " in Kangaroo.");
}
public static void main(String[] args) {
Kangaroo myRoo = new Kangaroo();
Animal myAnimal = myRoo;
myRoo.testInstanceMethod();
myAnimal.testInstanceMethod();
Kangaroo.testClassMethod();
Animal.testClassMethod();
}
}
The result will be (pay attention to the 3rd and 4th lines, as opposed to the 1st and 2nd):
The instance method in Kangaroo.
The instance method in Kangaroo.
The class method in Kangaroo.
The class method in Animal.
In Java it's not possible to access Animal's implementation. It will always return Kangaroo's version.
(Note in C# it is possible by tagging the overriding method with "new", but it's a fairly specialised use case).
Accessing what appears to be an Animal but getting the behaviour specified by Kangaroo is exactly what polymorphism is - the ability for a child object to be substituted wherever its parent is expected.
In general you wouldn't want to have the calling code know about the inheritance hierarchy because this would tightly couple your code together. If you genuinely need to access Animal's implementation of this method it suggests your design is probably wrong.
The spirit of Polymorphism is to execute different code decided at runtime. To make it more clear, I'll modify your code a bit.
public class Animal {
public void getLegs(){
SOP('4 legs');
}
}
public class Kangaroo extends Animal{
public void getLegs(){
SOP('2 legs');
}
public static void main(String[] args){
Animal a = new Kangaroo(); //without changing this how can I get Animal getLegs
Kangaroo kng= new Kangaroo ();
Animal an = new Animal();
SOP(a.getLegs()); // Kangaroo's version is called
SOP(kng.getLegs()); //Again, Kangaroo's version is called
SOP(an.getLegs()); //Animal version is called
}
}
and Yes, as all say you can't call Animal from your line Animal a = new Kangaroo();..as none will want to do it. Rather he will directly write. Animal a = new Animal();..
So finally it is the object not referance which decides which method will be called
Now If I want to call the getLegs method of Animal, how do I? Is it possible?
If you want to access the overridden method - which contradicts polymorphism - you can use reflection. Get the getLegs method from Animal's class, and then invoke it on your Kangaroo object. However, this is a hack, and not something you'd do in a regular program.
SOP( Animal.class.getMethod("getLegs").invoke(a) );

Categories

Resources