Results 1 to 15 of 15
  1. #1
    Join Date
    Oct 2016
    Posts
    47
    Rep Power
    0

    Default Why would an object of a subclass have a variable of type superclass

    From the following website, Overriding and Hiding Methods (The Java™ Tutorials > Learning the Java Language > Interfaces and Inheritance), there is a superclass called Animal and a subclass extended from it called Cat.


    Java Code:
    public class Animal {
        public static void testClassMethod() {
            System.out.println("The static method in Animal");
        }
        public void testInstanceMethod() {
            System.out.println("The instance method in Animal");
        }
    }
    
    
    
    public class Cat extends Animal {
        public static void testClassMethod() {
            System.out.println("The static method in Cat");
        }
        public void testInstanceMethod() {
            System.out.println("The instance method in Cat");
        }
    
        public static void main(String[] args) {
            Cat [B]myCat [/B]= new Cat();              // line 1
            [B]Animal [/B]myAnimal = [B]myCat[/B];         // line 2
            Animal.testClassMethod();                     // line 3
            myAnimal.testInstanceMethod();           // line 4
        }
    }

    Here is the output:

    Java Code:
    The static method in Animal
    The instance method in Cat



    I'm confused about the lines inside of the main ( ) which is inside of the subclass called Cat. I have the following questions.

    1. On line 2, the variable myCat is holding an object of type Cat. Since this is the case, what is the point of having Line 2, where the object variable myCat is assigned to a variable called myAnimal, which is of type superclass? The purpose of Line 2 really confuses me.
    2. To simplify things, why couldn't you omit line 1, and just use new Cat( ); in place of myCat in line 2?
    3. Line 4 invokes the testInstanceMethod() of the subclass. Since this is the case, couldn't the same result be achieved by omitting line 2, then use myCat from line 1, in place of myAnimal on line 4? By doing this, you would in essence be doing object.method, so I would think that this would work.
    4. On Line 4 again, since myAnimal is of type Animal (which is the superclass), I would think that the testInstanceMethod( ) of the superclass would be invoked. But instead the testInstanceMethod( ) of the subclass is invoked. Why is this?

  2. #2
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    13,541
    Rep Power
    27

    Default Re: Why would an object of a subclass have a variable of type superclass

    1 and 2. I assume this is so it can later show how a call to testInstanceMethod results in the Cat version being called, irrespective of the reference type. This would have been more obvious just using:
    Java Code:
    Animal myAnimal = new Cat();
    in my opinion, and yours...
    :)

    3. Yes, which brings up your point 2. I think that there was no need at all for myCat. It just confuses the situation.

    4. And this (in my mind) is what this code is showing. It's not the type of the reference that is important when it comes to which instance method is called. It's the type of the object it points to.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  3. #3
    camel-man is offline Member
    Join Date
    Jan 2016
    Posts
    19
    Rep Power
    0

    Default Re: Why would an object of a subclass have a variable of type superclass

    So on a side note, I have a question. Say when he does
    Java Code:
    Animal mine = new Cat();
    Will mine point to an object of type Cat or type Animal? I would go on a limb and say type Cat since the new call has explicitly stated to allocate memory for a Cat object.

  4. #4
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    13,541
    Rep Power
    27

    Default Re: Why would an object of a subclass have a variable of type superclass

    In memory there will be a Cat object.
    That is what the reference (of type Animal) points at.

    The result of that is that, at runtime, a call to testInstanceMethod will use the version in Cat, as the instance is a Cat. However, if Cat had a method catSpecificMethod and you were to write:
    Java Code:
    mine.catSpecificMethod();
    then you would get a compile time error as that method does not exist on Animal, which is the reference type.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  5. #5
    camel-man is offline Member
    Join Date
    Jan 2016
    Posts
    19
    Rep Power
    0

    Default Re: Why would an object of a subclass have a variable of type superclass

    Aha makes sense, so the variable of that reference type must only adhere to that reference type methods / fields? Which in our case would be anything from Animal? What could it use from Cat?

  6. #6
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    6,226
    Rep Power
    14

    Default Re: Why would an object of a subclass have a variable of type superclass

    Quote Originally Posted by camel-man View Post
    What could it use from Cat?
    Overridden methods declared in the Animal class. It could only get "cat state" via methods
    (overridden or not) which are declared in the Animal class.

    Regards,
    Jim
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

  7. #7
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    13,541
    Rep Power
    27

    Default Re: Why would an object of a subclass have a variable of type superclass

    Think of it this way (since this is the way it works).
    It's a compilation check.
    The compiler only knows the type of the reference, so attempting to access something in the underlying object that you might know exists but doesn't actually exist on the reference type results in an error.

    So, the compiler is only concerned with the type declared for the reference.

    At runtime, the JVM uses the actual object.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  8. #8
    camel-man is offline Member
    Join Date
    Jan 2016
    Posts
    19
    Rep Power
    0

    Default Re: Why would an object of a subclass have a variable of type superclass

    Okay that makes a lot of sense. Thank you

  9. #9
    Join Date
    Oct 2016
    Posts
    47
    Rep Power
    0

    Default Re: Why would an object of a subclass have a variable of type superclass

    Quote Originally Posted by Tolls View Post
    In memory there will be a Cat object.
    That is what the reference (of type Animal) points at.
    then you would get a compile time error as that method does not exist on Animal, which is the reference type.
    What do you mean when you say "reference type points at?" With object variables, does the reference type AND the object itself get stored in memory? My understanding is that only the object itself is stored in memory. If this is the case, then where is the reference type stored?

  10. #10
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    6,226
    Rep Power
    14

    Default Re: Why would an object of a subclass have a variable of type superclass

    Reference types have to be stored, otherwise, you would not be able to get a runtime class cast exception. Where they are stored
    exactly I do not know. Probably an internal class descriptor of some kind.

    Also, note that Toll's said "compile time error."

    Regards,
    Jim
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

  11. #11
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    13,541
    Rep Power
    27

    Default Re: Why would an object of a subclass have a variable of type superclass

    The reference is in memory as (though this is implementation specific, it's something long these lines) a pointer, so a memory address for where the object lives.
    I couldn't actually say if the type of the reference is stored. I'm not sure that would actually be necessary since the compiler has already determined that the reference type is valid for whatever operation you are planning on doing. In the case of casting, the JVM only needs to know what you are casting to, so I'm not sure it would need the reference type either.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  12. #12
    Join Date
    Oct 2016
    Posts
    47
    Rep Power
    0

    Default Re: Why would an object of a subclass have a variable of type superclass

    I think need to clarify my question.

    On line 4 we have

    myAnimal.testInstanceMethod();

    If we want to invoke the method of an object, why would we use a variable (myAnimal) which is of type superclass? That's one question.

    Here is another question.

    If we want to invoke the object's method, why not just do the following. Wouldn't this make more sense? And even if this does work, why would somebody choose to assign an object to a variable of type superclass?

    Cat myCat= new Cat();
    myCat.testInstanceMethod();

  13. #13
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    6,226
    Rep Power
    14

    Default Re: Why would an object of a subclass have a variable of type superclass

    Your last example, in most cases, is the way it would be done. But the fact that you can assign a subclass
    to it's superclass (or interface type) is very useful. Imagine a class of Animal and a bunch of subclasses. Animal has
    a feedme() and a getName() method which each subclass overrides to support their particular animal. Now you
    put all the subclasses in a list of type Animal, and iterate thru it printing out the name and what food they should get. So you
    are implicitly assigning a subclass to its superclass (thru the interation process) to access information common to all subclasses.

    Regards,
    Jim
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

  14. #14
    Join Date
    Oct 2016
    Posts
    47
    Rep Power
    0

    Default Re: Why would an object of a subclass have a variable of type superclass

    Quote Originally Posted by jim829 View Post
    Your last example, in most cases, is the way it would be done. But the fact that you can assign a subclass
    to it's superclass (or interface type) is very useful. Imagine a class of Animal and a bunch of subclasses. Animal has
    a feedme() and a getName() method which each subclass overrides to support their particular animal. Now you
    put all the subclasses in a list of type Animal, and iterate thru it printing out the name and what food they should get. So you
    are implicitly assigning a subclass to its superclass (thru the interation process) to access information common to all subclasses.

    Regards,
    Jim
    Jim,

    Thank you very much for your reply. This really helps to clear things up. The only question I have now is this. How would you invoke the testInstanceMethod( ) of the Animal class?

    In your answer, please specify the reference type of the class (or object) that comes before the ".testInstanceMethod( )" part.

  15. #15
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    6,226
    Rep Power
    14

    Default Re: Why would an object of a subclass have a variable of type superclass

    Create a special method in the Cat class to call the parent method
    using the super construct.

    Java Code:
    public void invokeParentMethod() {
       super.testInstanceMethod();
    }
    However, this sort of defeats the purpose of overriding methods and I have never had to do this.

    EDIT: I think this is a better answer. From any instance method within a subclass
    you can invoke a parent class method by prefixing the keyword super. You only need to
    create a helper method if you want to call the superclass method from some other context.
    For example, from a static context you can invoke the super class method via a legal call to a helper
    instance method as long as the call is properly qualified (i.e. uses a instance reference).

    Details such as this are explained at Java Language and JVM Specifications
    But these documents are not an easy read.

    Regards,
    Jim
    Last edited by jim829; 11-14-2016 at 04:31 PM.
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

Similar Threads

  1. Replies: 9
    Last Post: 07-27-2015, 10:09 AM
  2. Replies: 1
    Last Post: 06-19-2013, 07:40 PM
  3. superclass and subclass
    By mr idiot in forum New To Java
    Replies: 19
    Last Post: 01-03-2009, 07:29 AM
  4. Replies: 1
    Last Post: 07-22-2008, 04:27 PM
  5. which class is superclass and subclass?
    By java_fun2007 in forum New To Java
    Replies: 0
    Last Post: 12-11-2007, 08:55 PM

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •