class horse{/*some data and functions*/}
class bird{/*some data and functions*/}
class pegasus : public horse, public bird
{}
If classes are present as above, then in main why do I create like below mentioned
1) horse *temp = new pegasus;
instead I will create like
2) pegasus *temp = new pegasus;
In second method I can access functions of horse and bird, all functions including non virtuals where are in first method I can't access non virtual functions of pegasus object.
You use the first approach when you need to treat your pegasus object like a horse, pretending that you do not know that it is also a bird. As long as you can do it, you should, because it lets you change the implementing class without changing anything else. This is called programming to interface.
You use the second approach when you need to use both the horse and the bird aspects of your pegasus object. This places tighter constraints on the objects that you can assign to tmp, because it must provide implementations of both classes.
Related
This question is taken from an AP Computer Science practice test.
public class Bird
{
public void act()
{
System.out.print("fly");
makeNoise();
}
public void makeNoise()
{
System.out.print("chirp");
}
}
public class Dove extends Bird
{
public void act()
{
super.act();
System.out.print("waddle");
}
public void makeNoise()
{
super.makeNoise();
System.out.print("coo");
}
}
Suppose the following declaration appears in a class other than Bird or Dove:
Bird pigeon = new Dove();
What is printed as a result of the call pigeon.act()?
I thought the answer would be "fly chirp", but the textbook says that the answer is "fly chirp coo waddle". I thought that 'pigeon' could only access methods available in Bird? I was under the impression that, if the user wanted to access methods in Dove, 'pigeon' would have to be cast to Dove.
Would Bird pigeon = new Bird(); give the same output? How about Dove pigeon = new Dove();?
Long story short, when you access act method of pigeon, its override from Dove is called.
I thought that 'pigeon' could only access methods available in Bird?
That is certainly true, at least, for situations when no casting is applied. However, method act is available on the class Bird, the statically known type of pigeon, so the call compiles fine.
However, accessing methods is only about being able to call them. What methods do when you call them is decided at runtime based on the dynamic type of pigeon. This is where method overriding comes into play, because Dove overrides Bird's methods, but in addition it also calls Bird's methods. That is why the code hits all four printouts.
Would Bird pigeon = new Bird(); give the same output?
No, the output would be different, because in this case both dynamic and static types of pigeon would be the same, i.e. Bird, so only Bird's implementations would be invoked.
the class Dove does override the methods act and makeNoise of class Bird. Overriding means changing the behavior of a method visible to the sub-class, (in your case Dove). Methods are visible to a sub-class if they have a public or protected access modifier or if they have a package private access modifier and the sub-class belongs to the same package as the super-class does.
pigeon is an instance of Dove.
calling pigeon.act() results in calling Dove.act.
Dove.act calls super.act which is Bird.act.
Bird.act prints fly and calls makeNoise on pigeon resulting in calling Dove.makeNoise.
Dove.makeNoise calls super.makeNoise which is Bird.makeNoise.
Bird.makeNoise print chirp.
Dove.makeNoise prints coo after calling super.makeNoice
What you experience here is polymorphism in action. And instead of answering your various questions directly; I will simply explain the case you are observing.
You call act() on an instance of Dove; that causes a call to super; printing "fly".
That super method then calls makeNoise() ... on "itself". But as said: "itself" is a Dove object; thus you get the Dove noise! "coo"!
Then the Dove implementation ends; and prints "waddle".
The essence is: the exact version of a method that is invoked is determined at runtime and it only depends on the exact type of the object the method is invoked on.
The above gives you all the information you need to answer your other questions yourself. In that sense: don't request answers; ask for explanations; and use those to solve the puzzle yourself!
From your question "I thought that 'pigeon' could only access methods available in Bird? I was under the impression that, if the user wanted to access methods in Dove, 'pigeon' would have to be cast to Dove." This is actually true.
Lets try to find the mssing link in the understanding.
When we have code like Bird pigeon = new Dove(); where Dove extends Bird we have actual object of Dove and reference type is of Bird. As the object is of Dove so it has the methods, both inherited from super class as well as the ones which are added.
Another important point is all the overriden methods have only one instance. Its Overriden meaning the behavior of the same method has been modified, its not an additional separate method. There is only one copy of inherited method not both. Its the overloaded methods which are separate, just the names are same but signature is different. This is the reason you get the behaviour of Dove when you invoke any overriden method.
This one is simple super , using it a sub class can access the accessible (visible) entities (instance properties and methods) of its super class. If a sub class uses super keyword to invoke a method then its the method of the parent class which gets invoked. But again this can be considered that the author of the sub class did it intentionally. Once the class is written and Objects of such class is created then on the object using . (dot operator) users can only invoke whats there in the object. If any method has used super keyword its part of the behavior of the object. Users of the Sub class object can not invoke behavior of the parent class method if its overridden in sub class.
Lastly yes if you wish to invoke any additional method of Dove (Sub class ) using a reference of Bird (Super class) then you need to cast it to Dove.
I have been reading about dynamic polymorphism in java recently(I am beginner). As per my understanding if a reference of a parent class type is assigned as a reference to its child like below
tutorialspoint it involves dynamic polymorphism. In the example discussed in the link, I understand an Object of employee class is used to access a (overridden) method of salary class.
In that example neither is employee abstract nor is an interface. (which means it is possible to create an object for the parent).
Now, as per this link stackoverflow, I see that an interface is used to discuss dynamic polymorphism.
Question: How is it possible to use interface as an example for dynamic polymorphism?
Moreover, in the example discussed in tutorialspoint, it is said that compiler look for the method in parent class but JVM invokes the child class method during run time.
Interfaces neither have method definition nor can be instantiated, so how can
List<Animal> animalPen = new LinkedList<>(); be used for dynamic polymorphism.
Actually, the explanation isn't really much different.
List animalPen = new LinkedList<>();
boolean empty = animalPen.isEmpty();
In this example, the compiler validates whether animalPen has a method isEmpty by looking to its reference type List. List declares the method isEmpty and so, even if it does not define it, the system is then guaranteed that animalPen has a defined method by that signature.
This is because a non-abstract class must define all methods from all interfaces it implements. This ensures that all instances of an interface is one which has, somewhere in its hierarchy, defined the interface's methods.
You use interfaces to do polymorphism when you have different behaviours in your objects. Let's say you have a class Duck and you have a FlyBehavior variable declared. In this case the first thing you think of doing is a class named FlyBehavior to make an object of that type. Now let's say you have different type of ducks, like the Mallard duck, Redhead duck and now you have a Rubber duck, all of them extend the Duck class. Your rubber duck will not fly, so FlyBehavior will be different for the rubber duck. So, you make FlyBehavior an interface and create two new classes: ItFlies and NoFly, both implement the FlyBehavior interface. The constructor in Duck will have a a FlyBehavior parameter that you'll need to fill when you create a new object of type Duck, as you say, an interface can't be instantiated, but since ItFlies and NoFly, both implement the FlyBehavior interface, you can fill the FlyBehavior parameter with these two classes (or any class that implements FlyBehavior). This object oriented technique is also useful to make your program more independent and flexible in case of making modifications.
I have some background in C++ and know some Java too (apparently far from enough).
When I see overriding behavior in Java or C++, it does not seem to differ much. Given below example in JAVA:
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");
}
}
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
a.move();// runs the method in Animal class
b.move();//Runs the method in Dog class
}
}
In Java, you use a base class reference, in C++ you use a base class pointer, and depend on the type of instance it points to (a base class object instance or a subclass instance), you can achieve polymorphism.
The above is based on you call the instance method using a base class reference or pointer, right?
Now I see this example in Java.
What is the order of the Constructors in this Java Code?
Basically it says if a base class function is overriden, then in the process of creating a subclass object, even the base class initialization portion will be affected. See below explanation I copied from above link:
new Son()
=>
Son._init
=> first every constructor calls super()
Father._init
Object._init
who() => is overridden, so prints "son" !!!!!
tell(name) => name is private, so cannot be overridden => "father"
who() => "son"
tell(name) => "son"
Why should this happen? I mean does this conform to how polymorphism should be use? When making base class portion of initialization, why use overrided function from subclass?
In Java doc http://docs.oracle.com/javase/specs/jls/se7/html/jls-12.html#jls-12.5, I only find this:
"Unlike C++, the Java programming language does not specify altered rules for method dispatch during the creation of a new class instance. If methods are invoked that are overridden in subclasses in the object being initialized, then these overriding methods are used, even before the new object is completely initialized. "
But I don't know the reason behind it, and it feels strange.
Any thoughts?
This is one of the extremely rare cases where C++ is trying to protect you from shooting yourself in the foot more than Java does. (Or at least it has the noble intention to do so.)
You are very likely to shoot yourself in the foot in any language if you try invoking an overridable (virtual) method M of your base class B from within the constructor of B. That's because M is likely to be overridden in derived class D, but at the moment that B is being constructed, D has not been constructed yet. So, D.M is being invoked before the constructor of D has been invoked. That can spell disaster.
So, Java simply allows this to happen, use at your own risk. (If you have sufficient warnings enabled, your compiler will tell you that you are living life dangerously.)
C++ does not prohibit this either, but it slightly changes its behaviour so as to contain the damage, so to speak: when you invoke a virtual method from within a constructor, it does not really invoke it as a virtual method, (with a VMT lookup,) but it invokes it directly, as a non-virtual method.
(Either that, or from within the constructor of B it simply uses class B's VMT instead of D's VMT. Which, come to think of it now, makes sense. But I am not sure about that, it has been a long time since I last troubleshot this behaviour of C++.)
This might be a simple question for many but has confused me. I am picking an example from Kathy Sierra that shows the utility of Abstract Classes but I am unable to understand the overall importance of abstract classes.
Example
We have an abstract class Car with abstract methods - power() & topSpeed(). These methods are implemented in sub classes BMW, Volkswagen and Audi.
My question is - why do we need to have the abstract class Car in the first place to customize methods for each car type? Why not have these two methods in any one of these car subtypes, say BMW and then other two - Volkswagen and Audi - can simply override these methods?
By making a method abstract, it means that people have to implement it. You require people to do so and it is impossible for people to forget to do so, as it will fail to compile if they do.
The #override annotation exists for a very similar reason, by marking a method as #override you get an error if (for example) you typed the method name wrong and aren't actually overriding something.
In many ways the abstract class is half way between an interface and a normal class - it defines what you need to do to use it in the same way an interface does, but it also handles some of the implementation for you.
Classes can only extend one other class. They can implement any number of interfaces.
For example you might have MotorVehicle inherited by Car, Motorbike and Train - but then you might have a Steerable interface implemented by Car, Motorbike and Pedalbike.
To answer the question in the comments:
If there is an Interface "I" having method m() which is implemented by class "A" and another class "B" wants to access the method m(), what is the need of interface here. Can we simply not implement that method in class A?
You can - but if on the other hand class B wants to access the method m() in both a class A and class C (where A and C don't inherit from each other or a common class containing m()) then the way to do that is to specify a common interface I and class B uses the interface type, I, not the types A and C at all.
Also remember that interfaces can be used between packages and libraries. For example Listener and Strategy patterns make heavy use of interfaces. When the Java developers wrote JButton (for example) the ActionLstener is specified as an Interface to provide maximum flexibility to people using JButtons in the future.
Why not have these two methods in any one of these car subtypes, say BMW and then other two - Volkswagen and Audi - can simply override these methods?
Wouldn't that require Volkswagen and Audi to inherit from BMW? That wouldn't be correct, since those aren't BMWs.
The abstract base class and its abstract methods form a kind of contract which inheriting objects must implement. There's no such thing as a concrete Car that isn't a more specific type. But all concrete types share commonalities. The abstract Car enforces those commonalities, allowing specific types to be treated as generic instances of Car when needed.
For example, if you have code which needs a Car on which it will invoke the Drive() method, that code doesn't care what kind of Car it gets. It will Drive() any Car. So it accepts an abstract type so that anything which implements that type can be used:
UseACar(Car car)
{
car.Drive();
}
// elsewhere
BMW myCar = new BMW();
UseACar(myCar);
Without this enforcement of the contract, a statically-typed and compiled language would have no way of guaranteeing that .Drive() exists on the object. You'd need to create a UseAX() method for every possible kind of car, each accepting a different type. Using polymorphism like this allows you to create a single, more generic method which works on any instance of the abstract type.
So that you can write code that deals with Cars without knowing what kind of car it is:
public void PrintTopSpeed(Car car)
{
System.out.println("This car's top speed is " + car.topSpeed());
}
If the Car class didn't define topSpeed(), this code wouldn't compile. You'd have to have a different version of this print function for each of your BMW, Volkswagen, Audi, etc. derived classes. This is perhaps the most basic concept in object-oriented programming, so you really need to master it. Base classes allow objects to share common behavior, and allow code to be written to use that behavior without any knowledge of what specific type of object it's dealing with.
Polymorphism is the answer. If you don't have methods power() and topSpeed() in the abstract class you can't do things like this :
List<Car> cars;
cars.add(new Porshe());
cars.add(new Ford());
for(Car car : cars){
System.out.println(car.topSpeed());
}
You would have to handle lot of thing your self if you have only custom methods in your subclasses.
This is called abstraction. Methods in abstract class are considered as protocol so that car makers should not violate.
abstraction is great when the original programmer/architect want's to allow customized behavior to some base class and ensure that the consuming programmer implements the required methods.
What is the use of creating base class object using child class reference in Java
If I understand correctly, you mean:
class Parent {
...
}
class Child extends Parent {
...
}
Parent p = new Child ();
There are many reasons:
Flexibility: you can use Parent as a parameter type, and pass any subclass (i.e. Child and other) as this parameter.
Polymorphism: You can override Parent method in several Child classes and use them in turn where Parent object required (like in Strategy pattern)
If you're working on some public API you can make Parent class public and visible to everyone but all Childs can be invisible to outer users. It can make your API more narrow. Good example is Collections API. There are 32 implementations (i.e. Childs) which are used implicitely, but only a few public interfaces. You can obtain synchronized, unmodifiable and other collections through Collection (i.e. Parent) interface not knowing implementation details.
Animal myAnimal1 = new Dog();
Animal myAnimal2 = new Cat();
Animal myAnimal3 = new Horse();
Suppose Animal has a method called getAnimalSound() and Dog, Cat, Horse all override that method according to them. Now, this code is very extensible, your API can have just one method getAnimalSound() to indicate sound of any kind of an animal, in tern each animal class has already implemented their own version of getAnimalSound()
System.out.println(getAnimalSound(myAnimal1)); //runtime finds animal1 is dog, prints Bark
System.out.println(getAnimalSound(myAnimal2));//runtime finds animal2 is cat, prints Meow
System.out.println(getAnimalSound(myAnimal3));//runtime finds animal3 is horse, prints Niih
As you can see one Method getAnimalSound() is the standard API, but we achieved so much of extensibility.
If you mean things like
List<String> list = new ArrayList<String>()
then you are not actually creating an instance of the superclass. You are only telling the user to handle it as if it was one. The point is that you often don't need to know the exact implementation that was chosen and wish to retain the ability to change the implementation. Hence you only tell a user of an API that something is a List and if your algorithm requires it, you can change the implementation to use a LinkedList instead, without changing the API.