Polymorphism - Ambiguous error - java

I asked a similiar question yesterday, but another issue has arisen.
class Cat {
public void isClawedBy(Cat c, Kitten k){
System.out.println("Clawed by a cat");
}
}
class Kitten extends Cat{
public void isClawedBy(Kitten k, Cat c){
System.out.println("Clawed by a Kit");
}
}
Cat g = new Cat();
Cat s = new Kitten();
Kitten t = new Kitten();
g.isClawedBy(s,t);
s.isClawedBy(t,s);
t.isClawedBy(t,t);
The issue i am am confused about is around t.isClawedBy(t,t);. I understand that s.isClawedBy(t,s); will throw an error, because s is of static type cat.
But t.isClawedBy(t,t); is throwing a "The method isClawedBy(Kitten, Cat) is ambiguous for the type Kitten" error. If i change the code to t.isClawedBy(s,t); or t.isClawedBy(t,s); it works, but unsure as to why it doesnt work for (t,t).
Thanks in advance

In Java method calls are resolved dynamically. When you call a method the JVM tries to find a method that matches the signature i.e. method name, parameter types and return types. It does this by looking in the method table of the class used, which will contain the method signatures of super types also.
When checking if a signature in the method table is suitable it will take into account the supertypes of the parameter (and return) types. In the case of t.isClawedBy(t,t) we have two methods that can match as the method defined in Kitten matches and that defined in Cat matches - note that these are different methods as they have different parameter types.
As two different methods match the method call is ambiguous.
For isClawed(s,t) and isClawed(t,s) there is no ambiguity as s is a Kitten and cannot be a Cat.

It is ambiguous because Kittens are Cats.
Thus, given:
Cat isClawedBy(Cat c, Kitten k)
Kitten isClawedBy(Kitten k, Cat c)
For a Kitten, both methods are available. A Kitten is a Cat, so a call to Cat.isClawedBy(Cat, Kitten) with two Kitten arguments fits the signature. Likewise, a call to Kitten.isClawedBy(Kitten, Cat) with two Kittens also matches the signature.
There is no way for the compiler to tell which method was intended.

It is because you didn't override that method.
For t.isClawedBy(t,t);there are two possible methods to execute.The Cat's isclawed method and the Kitten's isclawed method.
To override a method paremeters must be the same.

kitten extends cat, so kitten gets the atributs and methods of cat, so kitten class knows 2 methods
public void isClawedBy(Cat c, Kitten k)
public void isClawedBy(Kitten k, Cat c)
But it dosent know a metoth public void isClawedBy(Kitten k, Kitten k) so it dosent know what to do when u call isClawedBy(t,t);

Related

Invoking a Method of the Superclass expecting a Superclass argument on a Subclass instance by passing the an instance the of the Subclass

Can anyone please explain the output of the following code, and what's the Java principle involved here?
class Mammal {
void eat(Mammal m) {
System.out.println("Mammal eats food");
}
}
class Cattle extends Mammal{
void eat(Cattle c){
System.out.println("Cattle eats hay");
}
}
class Horse extends Cattle {
void eat(Horse h) {
System.out.println("Horse eats hay");
}
}
public class Test {
public static void main(String[] args) {
Mammal h = new Horse();
Cattle c = new Horse();
c.eat(h);
}
}
It produces the following output:
Mammal eats food
I want to know how we are coming at the above result.
Overloading vs Overriding
That's not a valid method overriding, because all the method signatures (method name + parameters) are different:
void eat(Mammal m)
void eat(Cattle c)
void eat(Horse h)
That is called method overloading (see) and class Horse will have 3 distinct methods, not one. I.e. its own overloaded version of eat() and 2 inherited versions.
The compiler will map the method call c.eat(h) to the most specific method, which is eat(Mammal m), because the variable h is of type Mammal.
In order to invoke the method with a signature eat(Horse h) you need to coerce h into the type Horse. Note, that such conversion would be considered a so-called narrowing conversion, and it will never happen automatically because there's no guarantee that such type cast will succeed, so the compiler will not do it for you.
Comment out the method void eat(Mammal m) and you will see the compilation error - compilers don't perform narrowing conversions, it can only help you with widening conversions because they are guaranteed to succeed and therefore safe.
That what would happen if you'll make type casting manually:
Coercing h into the type Horse:
c.eat((Horse) h);
Output:
Cattle eats hay // because `c` is of type `Cattle` method `eat(Cattle c)` gets invoked
Because variable c is of type Cattle it's only aware of the method eat(Cattle c) and not eat(Horse h). And behind the scenes, the compiler will widen the h to the type Cattle.
Coercing both c and h into the type Horse:
((Horse) c).eat((Horse) h);
Output:
Horse eats hay // now `eat(Horse h)` is the most specific method
Rules of Overriding
The rules of method overriding conform to the Liskov substitution principle.
Functions that use pointers or references to base classes must be able to use objects of derived classes without knowing it.
The child class should declare its behavior in such a way so that it can be used everywhere where its parent is expected:
Method signatures must match exactly. I.e. method names should be the same as well as the types of parameters. And parameters need to be declared in the same order. It is important to note that if method signatures differ (for instance like in the code snippet provided in the question, name of one of the methods was misspelled) the compiler will have no clue that these methods are connected anyhow. I.e. it no longer be considered a case of overriding, methods will be considered to be distinct, and all other requirements listed below will not be applicable. That's why it's highly advisable to add the #Override annotation to the overridden method. With it, the compiler will give a clear feedback when it fails to find a matching method in the parent classes and interfaces, if you've misspelled the name, or declared parameters in the wrong order. Your IDE will add this annotation for you if you ask it to generate a template (shortcut in IntelliJ CTRL + O).
The access modifier of an overridden method can be the same or wider, but it can not be more strict. I.e. protected method in the parent class can be overridden as public or can remain protected, we can not make it private.
Return type of an overridden method should be precisely the same in case primitive type. But if a parent method declares to return a reference type, its subtype can be returned. I.e. if parent returns Number an overridden method can provide Integer as a return type.
If parent method declares to throw any checked exceptions then the overridden method is allowed to declare the same exceptions or their subtypes, or can be implemented as safe (i.e. not throwing exceptions at all). It's not allowed to make the overridden method less safe than the method declared by the parent, i.e. to throw checked exceptions not declared by the parent method. Note, that there are no restrictions regarding runtime exceptions (unchecked), overridden methods are free to declare them even if they are not specified by the parent method.
This would be a valid example of method overriding:
static class Mammal{
void eat(Mammal m){
System.out.println("Mammal eats food");
}
}
public class Cattle extends Mammal{
#Override
void eat(Mammal c) {
System.out.println("Cattle eats hay");
}
}
public class Horse extends Cattle{
#Override
public void eat(Mammal h) throws RuntimeException {
System.out.println("Horse eats hay");
}
}
main()
public static void main(String[] args) {
Mammal h = new Horse();
Cattle c = new Horse();
c.eat(h);
}
Output:
Horse eats hay
In your example, method overloading occurs(same method name but different parameter type passed).
When you're calling c.eat(h), the compiler will know that you want to use the void eat(Mammal m) method since your h reference has the type Mammal.
If you would change the object reference to Horse or Cattle like so:
Horse h = new Horse();
The output will be:
Cattle eats hay
This happens because the compiler will use the most specific method, in this case void eat(Cattle c), based on the object reference type Horse.
You may also be interested in method overriding which uses runtime polymorphism.

Generics code fails to compile without intermediate variable

I am surprised that the first 2 lines of code in main below are allowed by the compiler. It seems to be trusting me when I say that getIt() will return a Dog even though the signature also allows a Cat to be returned.
public class GenericsAreWeird {
public static void main(String... args){
// This is fine
Dog d = getIt();
d.woof();
// This fails to compile
// getIt().woof();
// This compiles but gives a runtime ClassCastException
Cat c = getIt();
c.meow();
}
private static <T extends Animal> T getIt(){
return (T) new Dog();
}
public static class Animal {}
public static class Cat extends Animal{
public void meow(){}
}
public static class Dog extends Animal{
public void woof(){}
}
}
I generally trust Java generics to protect me from ClassCastExceptions by giving compiler errors, rather than telling me at runtime that something won't work, so allowing this seems broken.
It also seems counter-intuitive that:
Dog d = getIt();
d.woof();
is not exactly equivalent to:
getIt().woof();
the compiler needs the intermediate variable as a 'hint'.
Have generics always worked this way? Can someone point me to (or provide) a decent explanation of any other scenarios where the compiler fails to pick up a class-related error like this?
return (T) new Dog(); for the most part tells the compiler to
"shut up with your type checking, I know better than you that Dog will always be assignable to T"
to which the compiler replies
"okay, go ahead then, then you better take care of not ever calling this method expecting it to return a anything else / aCat"
Then you do call it expecting it to return a Cat and get a deserved ClassCastException. You get a runtime exception because you tell the compiler that you know it better (which you do not).
After type erasure your getIt() method will look very much like this:
private static Animal getIt(){
return new Dog();
}
But before the type erasure happens, the compiler sees, that you use a generic return type T extends Animal for the method! And thus, once it sees the line
Dog d = getIt();
it says: Ok, so T will be Dog in this particular case, so I need to insert a cast to Dog after type erasure like this:
Dog d = (Dog) getIt();
In the same way, for the call Cat c = getIt() it will resolve the type T to be Cat and add an according cast to Cat:
Cat c = (Cat) getIt();
But inside of your method the compiler warns you: Hey, are you sure, that the Dog you create will always be of type T? Remember, this is not guaranteed generally! So if you ignore this warning, you should know, what you are doing, taht's the point.
And finally, of course the call
getIt().woof()
will not compile, because in this case the compiler has no idea how to resolve the type T, so it will be just Animal, the upper limitation of T. It is not able to guess that it is a Dog only based on the call to the woof() method.
The following line:
getIt().woof();
fails because woof() is defined on Dog not Animal and getIt() returns a sub-class of Animal. Hence the compiler is unaware of woof().
You could try:
abstract class Animal { abstract void speak(); }
class Dog extends Animal { void speak() { // Dog specific implementation } }
class Cat extends Animal { void speak() { // Cat specific implementation } }
Then you could use:
getIt().speak();
You get a ClassCastException because the only information about the type returned by getIt() is that it is a sub-class of Animal. Assigning it to a variable of type Cat or Dog is unsafe. This would be true of any similar use of generics.
A common workaround is to define getIt() something like this:
<T extends Animal> T getIt(Class<T> clazz) {
// return an instance of the appropriate type based on clazz
}
You can use it thus:
Dog dog = getIt(Dog.class);

Difference between different ways in instantiating an object in Java

I have the code:
class Father{
String name="father";
void f(){System.out.print("father class");}
}
class Son extends Father{
String name = "son";
void f(){System.out.print("son class");}
void f2(){}
}
public class Test {
public static void main(String[] args) {
Father s = new Son();
System.out.println(s.name);// outputs father
s.f();// outputs "son class"
s.f2();// s does not have f2
}
}
My question is, what is the difference between doing Father s = new Father() or, Father s = new Son() or, Son s = new Son()?
As well, why does s.f2 in the example cause an error? Must Father implement f2()?
I think it is easier to explain with an animal example:
class Animal {
void printName() {
System.out.println("Animal");
}
}
class Dog extends Animal{
#Override
void printName() {
System.out.println("Dog");
}
}
class Cat extends Animal{
#Override
void printName() {
System.out.println("Cat");
}
void meow() {
System.out.println("meow");
}
}
When you extend classes, the child class can override parent's methods and can have its own methods. In my Animal example the generic Animal object can only give its name, but the Cat object can give its name and also meow. Obviously, the meow method is specific to Cat as we know that Dogs can't do meow and Animals in general.
When you do
Animal animal = new Cat();
You actually create an instance of the Cat but use it as a general Animal. Thus, your animal instance only has methods which are available in the Animal class but the execution of the methods overridden by Cat class will be delegated to the Cat class.
if you want to execute Cat's specific methods then you need to cast your Animal to the Cat
(Cat) animal.meow();
In your example to call f2() method you need to cast your father object to the son first
(Son)s.f2();
What you're dealing with is reference type (variable type) and object type (what's actually being referred to). The Java compiler needs some kind of guarantee that the object being referred to can run the method you're calling. To do this, it looks to the reference type. When executed, the method run is that of the object type.
Simply put:
Father f = new Father(); //Treated as a Father, behaves like a Father
Son s = new Son(); //Treated as a Son, behaves like a Son
Father q = new Son(); //Treated as a Father, behaves like a Son (sounds like my own father)
If you cast q to a Son by saying (Son)q, it will be treated as a Son by the compiler, unless the object isn't actually a Son, in which case you'll get a ClassCastException.
Let's take a simpler concept, since your hierarchy implies that all Sons are Fathers, but not all Fathers are Sons (which ain't quite true).
Let's take the abstract class Number and any of its children - for brevity, we can use Integer, Float and BigInteger.
Suppose we declare this:
Number num = Float.NaN;
We now have a Float instance which is referenced by a Float. We can do anything we want to that instance, but only in the context of a Number.
There's a useful method for Float called isNan which would allow us to see if our float actually is a number. In the context of Number...that method doesn't exist.
There are advantages to doing it like this - if you don't need the specificity of the child reference, you can refer to everything by its parent class (or interface). This also uncouples you from the child's API should you want to be uncoupled from it (see developing to an interface).
OK I see where is the confusion here.
In java you can override methods but not class variables
keep that rule in mind
So when you did
Father s = new Son();
the object "s" is of type father
and as we said the variables inside it wont be overwritten just the methods
So the the final result is an object that has the member variables from the Father class (the "name" variable) and the method from son class (since father had only 1 method and son overridden it).
and for why the f2 does not work
it is because the object "s" is of type Father not son (it is father object that has 1 method of it overwritten by son class other than that it will keep be father object) and Father does not have f2 method thats why you get the compile error
s.f2() is the syntax error because you told JVM that s is Father, not Son.
In the code, it can't find f2 method in Father class
class Father{
String name="father";
void f(){System.out.print("father class");}
}
But it doesn't mean the code is wrong, just the JVM doesn't like it.
if you change s.f2() to
(Son)s.f2();
It will works

What is the difference between up-casting and down-casting with respect to class variable

What is the difference between up-casting and down-casting with respect to class variable?
For example in the following program class Animal contains only one method but Dog class contains two methods, then how we cast the Dog variable to the Animal Variable.
If casting is done then how can we call the Dog's another method with Animal's variable.
class Animal
{
public void callme()
{
System.out.println("In callme of Animal");
}
}
class Dog extends Animal
{
public void callme()
{
System.out.println("In callme of Dog");
}
public void callme2()
{
System.out.println("In callme2 of Dog");
}
}
public class UseAnimlas
{
public static void main (String [] args)
{
Dog d = new Dog();
Animal a = (Animal)d;
d.callme();
a.callme();
((Dog) a).callme2();
}
}
Upcasting is casting to a supertype, while downcasting is casting to a subtype. Upcasting is always allowed, but downcasting involves a type check and can throw a ClassCastException.
In your case, a cast from a Dog to an Animal is an upcast, because a Dog is-a Animal. In general, you can upcast whenever there is an is-a relationship between two classes.
Downcasting would be something like this:
Animal animal = new Dog();
Dog castedDog = (Dog) animal;
Basically what you're doing is telling the compiler that you know what the runtime type of the object really is. The compiler will allow the conversion, but will still insert a runtime sanity check to make sure that the conversion makes sense. In this case, the cast is possible because at runtime animal is actually a Dog even though the static type of animal is Animal.
However, if you were to do this:
Animal animal = new Animal();
Dog notADog = (Dog) animal;
You'd get a ClassCastException. The reason why is because animal's runtime type is Animal, and so when you tell the runtime to perform the cast it sees that animal isn't really a Dog and so throws a ClassCastException.
To call a superclass's method you can do super.method() or by performing the upcast.
To call a subclass's method you have to do a downcast. As shown above, you normally risk a ClassCastException by doing this; however, you can use the instanceof operator to check the runtime type of the object before performing the cast, which allows you to prevent ClassCastExceptions:
Animal animal = getAnimal(); // Maybe a Dog? Maybe a Cat? Maybe an Animal?
if (animal instanceof Dog) {
// Guaranteed to succeed, barring classloader shenanigans
Dog castedDog = (Dog) animal;
}
Downcasts can be expressed more succinctly starting from Java 16, which introduced pattern matching for instanceof:
Animal animal = getAnimal(); // Maybe a Dog? Maybe a Cat? Maybe an Animal?
if (animal instanceof Dog castedDog) {
// now castedDog is available here as in the example above
}
Down-casting and up-casting was as follows:
Upcasting: When we want to cast a Sub class to Super class, we use Upcasting(or widening). It happens automatically, no need to do anything explicitly.
Downcasting : When we want to cast a Super class to Sub class, we use
Downcasting(or narrowing), and Downcasting is not directly possible in Java, explicitly we have to do.
Dog d = new Dog();
Animal a = (Animal) d; //Explicitly you have done upcasting. Actually no need, we can directly type cast like Animal a = d; compiler now treat Dog as Animal but still it is Dog even after upcasting
d.callme();
a.callme(); // It calls Dog's method even though we use Animal reference.
((Dog) a).callme2(); // Downcasting: Compiler does know Animal it is, In order to use Dog methods, we have to do typecast explicitly.
// Internally if it is not a Dog object it throws ClassCastException
Autoboxing-vs-Casting
Upcasting and downcasting are important part of Java, which allow us to build complicated programs using simple syntax, and gives us great advantages, like Polymorphism or grouping different objects. Java permits an object of a subclass type to be treated as an object of any superclass type. This is called upcasting. Upcasting is done automatically, while downcasting must be manually done by the programmer, and i'm going to give my best to explain why is that so.
Upcasting and downcasting are NOT like casting primitives from one to other, and i believe that's what causes a lot of confusion, when programmer starts to learn casting objects.
Polymorphism: All methods in java are virtual by default. That means that any method can be overridden when used in inheritance, unless that method is declared as final or static.
You can see the example below how getType(); works according to the object(Dog,Pet,Police Dog) type.
Assume you have three dogs
Dog - This is the super Class.
Pet Dog - Pet Dog extends Dog.
Police Dog - Police Dog extends Pet Dog.
public class Dog{
public String getType () {
System.out.println("NormalDog");
return "NormalDog";
}
}
/**
* Pet Dog has an extra method dogName()
*/
public class PetDog extends Dog{
public String getType () {
System.out.println("PetDog");
return "PetDog";
}
public String dogName () {
System.out.println("I don't have Name !!");
return "NO Name";
}
}
/**
* Police Dog has an extra method secretId()
*/
public class PoliceDog extends PetDog{
public String secretId() {
System.out.println("ID");
return "ID";
}
public String getType () {
System.out.println("I am a Police Dog");
return "Police Dog";
}
}
Polymorphism : All methods in java are virtual by default. That means that any method can be overridden when used in inheritance, unless that method is declared as final or static.(Explanation Belongs to Virtual Tables Concept)
Virtual Table / Dispatch Table : An object's dispatch table will contain the addresses of the object's dynamically bound methods. Method calls are performed by fetching the method's address from the object's dispatch table. The dispatch table is the same for all objects belonging to the same class, and is therefore typically shared between them.
public static void main (String[] args) {
/**
* Creating the different objects with super class Reference
*/
Dog obj1 = new Dog();
` /**
* Object of Pet Dog is created with Dog Reference since
* Upcasting is done automatically for us we don't have to worry about it
*
*/
Dog obj2 = new PetDog();
` /**
* Object of Police Dog is created with Dog Reference since
* Upcasting is done automatically for us we don't have to worry
* about it here even though we are extending PoliceDog with PetDog
* since PetDog is extending Dog Java automatically upcast for us
*/
Dog obj3 = new PoliceDog();
}
obj1.getType();
Prints Normal Dog
obj2.getType();
Prints Pet Dog
obj3.getType();
Prints Police Dog
Downcasting need to be done by the programmer manually
When you try to invoke the secretID(); method on obj3 which is PoliceDog object but referenced to Dog which is a super class in the hierarchy it throws error since obj3 don't have access to secretId() method.In order to invoke that method you need to Downcast that obj3 manually to PoliceDog
( (PoliceDog)obj3).secretID();
which prints ID
In the similar way to invoke the dogName();method in PetDog class you need to downcast obj2 to PetDog since obj2 is referenced to Dog and don't have access to dogName(); method
( (PetDog)obj2).dogName();
Why is that so, that upcasting is automatical, but downcasting must be manual? Well, you see, upcasting can never fail.
But if you have a group of different Dogs and want to downcast them all to a to their types, then there's a chance, that some of these Dogs are actually of different types i.e., PetDog, PoliceDog, and process fails, by throwing ClassCastException.
This is the reason you need to downcast your objects manually if you have referenced your objects to the super class type.
Note: Here by referencing means you are not changing the memory address of your ojects when you downcast it it still remains same you are just grouping them to particular type in this case Dog
I know this question asked quite long time ago but for the new users of this question.
Please read this article where contains complete description on upcasting, downcasting and use of instanceof operator
There's no need to upcast manually, it happens on its own:
Mammal m = (Mammal)new Cat(); equals to Mammal m = new Cat();
But downcasting must always be done manually:
Cat c1 = new Cat();
Animal a = c1; //automatic upcasting to Animal
Cat c2 = (Cat) a; //manual downcasting back to a Cat
Why is that so, that upcasting is automatical, but downcasting must be manual? Well, you see, upcasting can never fail. But if you have a group of different Animals and want to downcast them all to a Cat, then there's a chance, that some of these Animals are actually Dogs, and process fails, by throwing ClassCastException.
This is where is should introduce an useful feature called "instanceof", which tests if an object is instance of some Class.
Cat c1 = new Cat();
Animal a = c1; //upcasting to Animal
if(a instanceof Cat){ // testing if the Animal is a Cat
System.out.println("It's a Cat! Now i can safely downcast it to a Cat, without a fear of failure.");
Cat c2 = (Cat)a;
}
For more information please read this article
Better try this method for upcasting, it's easy to understand:
/* upcasting problem */
class Animal
{
public void callme()
{
System.out.println("In callme of Animal");
}
}
class Dog extends Animal
{
public void callme()
{
System.out.println("In callme of Dog");
}
public void callme2()
{
System.out.println("In callme2 of Dog");
}
}
public class Useanimlas
{
public static void main (String [] args)
{
Animal animal = new Animal ();
Dog dog = new Dog();
Animal ref;
ref = animal;
ref.callme();
ref = dog;
ref.callme();
}
}
Maybe this table helps.
Calling the callme() method of class Parent or class Child.
As a principle:
UPCASTING --> Hiding
DOWNCASTING --> Revealing
1.- Upcasting.
Doing an upcasting, you define a tag of some type, that points to an object of a subtype (Type and subtype may be called class and subclass, if you feel more comfortable...).
Animal animalCat = new Cat();
What means that such tag, animalCat, will have the functionality (the methods) of type Animal only, because we've declared it as type Animal, not as type Cat.
We are allowed to do that in a "natural/implicit/automatic" way, at compile-time or at a run-time, mainly because Cat inherits some of its functionality from Animal; for example, move(). (At least, cat is an animal, isn't it?)
2.- Downcasting.
But, what would happen if we need to get the functionality of Cat, from our type Animal tag?.
As we have created the animalCat tag pointing to a Cat object, we need a way to call the Cat object methods, from our animalCat tag in a some smart pretty way.
Such procedure is what we call Downcasting, and we can do it only at the run-time.
Time for some code:
public class Animal {
public String move() {
return "Going to somewhere";
}
}
public class Cat extends Animal{
public String makeNoise() {
return "Meow!";
}
}
public class Test {
public static void main(String[] args) {
//1.- Upcasting
// __Type_____tag________object
Animal animalCat = new Cat();
//Some animal movement
System.out.println(animalCat.move());
//prints "Going to somewhere"
//2.- Downcasting
//Now you wanna make some Animal noise.
//First of all: type Animal hasn't any makeNoise() functionality.
//But Cat can do it!. I wanna be an Animal Cat now!!
//___________________Downcast__tag_____ Cat's method
String animalNoise = ( (Cat) animalCat ).makeNoise();
System.out.println(animalNoise);
//Prints "Meow!", as cats usually done.
//3.- An Animal may be a Cat, but a Dog or a Rhinoceros too.
//All of them have their own noises and own functionalities.
//Uncomment below and read the error in the console:
// __Type_____tag________object
//Cat catAnimal = new Animal();
}
}
upcasting means casting the object to a supertype, while downcasting means casting to a subtype.
In java, upcasting is not necessary as it's done automatically. And it's usually referred as implicit casting. You can specify it to make it clear to others.
Thus, writing
Animal a = (Animal)d;
or
Animal a = d;
leads to exactly the same point and in both cases will be executed the callme() from Dog.
Downcasting is instead necessary because you defined a as object of Animal. Currently you know it's a Dog, but java has no guarantees it's. Actually at runtime it could be different and java will throw a ClassCastException, would that happen. Of course it's not the case of your very sample example. If you wouldn't cast a to Animal, java couldn't even compile the application because Animal doesn't have method callme2().
In your example you cannot reach the code of callme() of Animal from UseAnimlas (because Dog overwrite it) unless the method would be as follow:
class Dog extends Animal
{
public void callme()
{
super.callme();
System.out.println("In callme of Dog");
}
...
}
We can create object to Downcasting. In this type also. : calling the base class methods
Animal a=new Dog();
a.callme();
((Dog)a).callme2();

Polymorphism - Simple

Just confused on how to following answer is correct.
class Cat {
public void isClawedBy(Cat c){
System.out.println("Clawed by a cat");
}
}
class Kitten extends Cat{
public void isClawedBy(Kitten c){
System.out.println("Clawed by a Kit");
}
}
If the following is called
Cat g = new Cat();
Cat s = new Kitten();
Kitten t = new Kitten();
g.isClawedBy(t);
s.isClawedBy(t);
t.isClawedBy(t);
How is the answer:
Clawed by Cat
Clawed by Cat
Clawed by Kitten
I'm confused on why s.isClawedBy(t) = Clawed by Cat.
Since the dynamic type of s is a kitten, and t is a kitten.
Is it because the arguments are different, so it doesn't override it?
Another part I am confused on. //Note the arguments have been swapped.
class Cat {
public void isClawedBy(Kitten c){
System.out.println("Clawed by a cat");
}
}
class Kitten extends Cat{
public void isClawedBy(Cat c){
System.out.println("Clawed by a Kit");
}
}
If the following is called
Cat g = new Cat();
Cat s = new Kitten();
Kitten t = new Kitten();
g.isClawedBy(t);
s.isClawedBy(t);
t.isClawedBy(t);
The output is:
Clawed by Cat
Clawed by Cat
Clawed by Cat
How does it work for when t is called?
About the second query : t.isClawedBy(t) giving the output of Clawed by Cat.
Since t is a Kitten and the argument passed in the method t.isClawedBy(t) is also Kitten , the method from the superclass Cat will be called because it matches the arguments perfectly.
Class Kitten does not override isClawedBy(Cat c). It adds a new method isClawedBy(Kitten c). The runtime sees s referenced as a Cat at the time s.isClawedBy(t) is called, and it ends up calling the Cat method.
If you change Kitten to:
class Kitten extends Cat{
#Override
public void isClawedBy(Cat c){
System.out.println("Clawed by a Kit");
}
}
Then you will see the output you desire. Even more interesting, you can do:
((Kitten) s).isClawedBy(t); and you will see the proper method called.
I'm confused on why s.isClawedBy(t) = Clawed by Cat. Since the dynamic type of s is a kitten, and t is a kitten.
s has reference type Cat but holds a Kitten object. t has reference type Kitten and holds an object Kitten. When the method is run at run-time it is first checked if the reference type has such a method and then the most specific version of the method is called. Since the subclass doesn't override the method (different types in the parameter) the method in the reference type is called.
For your second part it is the exact same thing happening, there is no overload and a Kitten can indeed be passed as a Cat to the method in the reference type so again this method is the most specific one in the hierarchy and it is called.
As for the first question;
Overriding resolution is done at runtime, but overloading resolution is done at compile time.
Since the signature of your methods are not identical (different parameter types. It doesn't matter that one's the subclass of another), they're overloading.
Since resolved at compile time, the compiler does not know what the instance type is; only the declared type.
To the compiler, s.isClawedBy(t) is the method isClawedBy(Kitten) of the declared type Cat.
The compiler says "yep, Cat can accept a Kitten in its method, that's what this method is".
So, at runtime, which method that will call has ALREADY been chosen by the compiler. The lookup is NOT performed at runtime.
Thus, at runtime, despite s actually being a Kitten object, the Cat method is called.

Categories

Resources