[Last Call] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

super and sub classes?

Posted on 2012-09-01
6
Medium Priority
?
441 Views
Last Modified: 2012-09-06
can someone explain these lines to me please?
Why did it cast the myCat with Superclass?
Why hide() was called from the Superclass?
but override() called from the subclass?


       Cat myCat = new Cat();
        Animal myAnimal = (Animal)myCat;
        myAnimal.hide();
        myAnimal.override();


http://www.java-tips.org/java-se-tips/java.lang/what-is-a-java-superclass.html

 public class Animal {

    public static void hide() {
        System.out.println("The hide method in Animal.");
    }

    public void override() {
        System.out.println("The override method in Animal.");
    }
}

public class Cat extends Animal {

    public static void hide() {
        System.out.println("The hide method in Cat.");
    }

    public void override() {
        System.out.println("The override method in Cat.");
    }

    public static void main(String[] args) {
        Cat myCat = new Cat();
        Animal myAnimal = (Animal)myCat;
        myAnimal.hide();
        myAnimal.override();
    }
}
0
Comment
Question by:dkim18
6 Comments
 
LVL 21

Expert Comment

by:Amitkumar P
ID: 38358173
Overriding depends on having an instance of a class. The point of polymorphism is that you can subclass a class and the objects implementing those subclasses will have different behaviors for the same methods defined in the superclass (and overridden in the subclasses). A static method is not associated with any instance of a class so the concept is not applicable.


Refer : http://geekexplains.blogspot.in/2008/06/can-you-override-static-methods-in-java.html
0
 

Author Comment

by:dkim18
ID: 38358182
I am really interested on these lines:

 Cat myCat = new Cat();
 Animal myAnimal = (Animal)myCat;

Why and what situation will you do this?
Cat is the subclass and it is inherited from Animal already.
What was the casting for?
0
 
LVL 17

Expert Comment

by:krakatoa
ID: 38358860
import java.lang.reflect.Field;


class Animal {


 int teeth = 17;
 static  Animal myAnimal;
 static Cat myCat;

	public static void main(String[] args){myCat = new Cat();
 
		myAnimal = (Animal)myCat;
		System.out.println("Individual called myCat has "+myCat.teeth+" teeth and "+myCat.eyes+" eyes");
		System.out.print("Individual myAnimal has "+myAnimal.teeth+" teeth, and ");
try{
try{
Field eyez = Class.forName("Animal").getField("eyes");
}catch(NoSuchFieldException nsfe){System.out.println(" no eyes");}			
}catch(ClassNotFoundException cnfe){cnfe.printStackTrace();}

		System.out.println();
	}


  static class Cat extends Animal{

   static int eyes = 2;
    int teeth = 34;

         Cat(){if(this instanceof Cat){System.out.println("I am a Cat ");}if(this instanceof Animal){System.out.println("I am an Animal ");}
	System.out.println("As an Animal I have "+super.teeth+" Teeth.");System.out.println("As a Cat I have "+this.teeth+" teeth");
	System.out.println("As a Java sub-class I have "+teeth+" teeth");
	System.out.println("As a Java superclass I have "+((Animal)this).teeth+" teeth");

			
		
         }

   }

}

Open in new window

0
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 
LVL 36

Accepted Solution

by:
mccarl earned 668 total points
ID: 38359697
Why did it cast the myCat with Superclass?
This was just to demonstrate the point at hand, which is "What methods are actually invoked when you have a subclass (Cat) object instance held in a superclass (Animal) defined variable?". So the cast is to make it clear to the compiler that you actually mean to do this.

Why hide() was called from the Superclass?
Because .hide() is a static method, ie. a class method and .hide() is being called via a variable of class Animal, then Animal.hide() is what actually gets invoked.

but override() called from the subclass?
Because .override() is an instance method (ie. not static) and .override() is being called on an object instance of class Cat (even though it is held in a variable of class Animal, it is still an object of class Cat, because it was created as a "new Cat()"), then the Cat.override() method is invoked in the context of the myCat/myAnimal object.
0
 
LVL 17

Assisted Solution

by:krakatoa
krakatoa earned 668 total points
ID: 38360856
Actually, this is more illustrative than my previous  -

import java.lang.reflect.Field;


class Animal {


 int teeth = 17;
 public int eyes = 145;//Try commenting this out, recompiling, and running.
 static  Animal myAnimal;
 static Cat myCat;

	public static void main(String[] args){myCat = new Cat();
 
		myAnimal = (Animal)myCat;
		
		System.out.println("Individual called myCat has "+myCat.teeth+" teeth and "+myCat.eyes+" eyes");
		System.out.print("Individual myAnimal has "+myAnimal.teeth+" teeth, and ");


      Field eyez;
      Integer eyeCount;
      Class animalClass = myAnimal.getClass();
      try {try{try{
        eyez = animalClass.getField("eyes");
        eyeCount = (Integer) eyez.get(myAnimal);
        System.out.println(eyeCount.toString()+" eyes.");
      } catch (NoSuchFieldException e) {System.out.println("no eyes");}
      }  catch (SecurityException e) {System.out.println(e);}
      } catch (IllegalAccessException e) {System.out.println(e);}



	}



  static class Cat extends Animal{

   static int eyes = 2;
    int teeth = 34;

         Cat(){if(this instanceof Cat){System.out.println("I am a Cat ");}if(this instanceof Animal){System.out.println("I am an Animal ");}
	System.out.println("As an Animal I have "+super.teeth+" teeth.");System.out.println("As a Cat I have "+this.teeth+" teeth");
	System.out.println("As a Java sub-class I have "+teeth+" teeth");
	System.out.println("As a Java superclass I have "+((Animal)this).teeth+" teeth");

			
		
         }

   }

}

Open in new window


int eyes must be public.
0
 
LVL 12

Assisted Solution

by:Sharon Seth
Sharon Seth earned 664 total points
ID: 38367714
myCat has been cast to Animal for demonstrating polymorphic behaviour , I'll explain where we come across this in real time ie; why we would  want a cat to be referenced by an Animal.
Say , you have a method in another class that does something on any animal - cat or dog or horse , or any animal . Say , it has to call override() on one of the animals .
For this , I will write a method like this :

void doSomething(Animal a)
{
   a.override();
}
 
Now , because of polymorphism , the run time will invoke the override method of the animal passed to it . It could be cat or a dog or a horse - the runtime takes care of calling the appropriate override method . In the absence of this polymorphic behaviour , doSomething() has to be overloaded for each animal type and you will have to write as many doSomething() methods as the number of animals , like this:
1. doSomething(Cat c){c.override()}
2. doSomething(Dog d){d.override()}
3.doSomething(Horse h){h.override()}
and so on

By writing your method to accept a super class reference , the method is generalised and can be passed in many kinds of animals .
0

Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction This article is the second of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers the basic installation and configuration of the test automation tools used by…
Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
This tutorial covers a step-by-step guide to install VisualVM launcher in eclipse.
This theoretical tutorial explains exceptions, reasons for exceptions, different categories of exception and exception hierarchy.
Suggested Courses
Course of the Month18 days, 2 hours left to enroll

830 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question