Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 9 of 9

Thread: Help regarding Superclass variable can reference subclass object

  1. #1
    Junior Member
    Join Date
    Jul 2011
    Posts
    28
    My Mood
    Busy
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Help regarding Superclass variable can reference subclass object

    Hello Everyone,
    I am a newbie to both java/oop as well as javaprogrammingforum.com..... i need some understanding with this topic "A superclass variable can reference a subclass object".Below is the code given in java book.
    // Dynamic Method Dispatch
    class A {
    void callme() {
    System.out.println("Inside A's callme method");
    }
    }
    class B extends A {
    // override callme()
    void callme() {
    System.out.println("Inside B's callme method");
    }
    }
    class C extends A {
    // override callme()
    void callme() {
    System.out.println("Inside C's callme method");
    }
    }
    class Dispatch {
    public static void main(String args[]) {
    A a = new A(); // object of type A
    B b = new B(); // object of type B
    C c = new C(); // object of type C
    A r; // obtain a reference of type A
    r = a; // r refers to an A object
    r.callme(); // calls A's version of callme
    r = b; // r refers to a B object
    r.callme(); // calls B's version of callme
    r = c; // r refers to a C object
    r.callme(); // calls C's version of callme
    }
    }
    The output from the program is shown here:

    Inside A's callme method
    Inside B's callme method
    Inside C's callme method



    Now my question is why create the overhead of creating a super class variable and let a subclass variable be assigned to it...and then call its respective method.
    A r; // obtain a reference of type A
    r = a; // r refers to an A object
    r.callme(); // calls A's version of callme
    r = b; // r refers to a B object
    r.callme(); // calls B's version of callme
    r = c; // r refers to a C object
    r.callme(); // calls C's version of callme
    since i have already created objects of subclass the the below modified code also works
    b.callme();
    c.callme();

    I mean i know sometimes there will be a situation where we need to assign a subclass object to superclass variable for referencing......I am really unable to get any real life idea about implementing it.

    Friends i am really stuck up with this concept and have googled several times[till 23rd or 24th pages....] to get a concrete picture about this.Please help me out by giving a simple example?
    Last edited by helloworld922; July 8th, 2011 at 11:01 AM.


  2. #2
    Super Moderator helloworld922's Avatar
    Join Date
    Jun 2009
    Posts
    2,896
    Thanks
    23
    Thanked 619 Times in 561 Posts
    Blog Entries
    18

    Default Re: Help regarding Superclass variable can reference subclass object

    The reason is abstraction. The idea is that you don't need to know every little tiny detail about the object. For example, say you're driving a car. For the most part, the pedal on the right makes you go faster, the pedal on the left slows you down, and the big round thing in front of you steers the car. How that happens isn't important for the driver (a.k.a. user) to know, but it is very important for those details to work properly in order for the car to actually move.

    These details could be for example how much gas should I use, is it fuel inject, how much air should I allow into the cylinders, and how much cooling load do I need to provide the engine as it's running.

    Similarly, you're base class would be something like "Car". It has the basic interactions needed to drive the car from the user's perspective (speed up, slow down, and steer), but the specific details shouldn't need to be spelled out there. Instead, the sub-classes, for example "Honda Civic SI 1996" or "Fararri F40" would have different ways to accomplish the goals of a car (speeding up, slowing down, and steering).

    Yes, you could theoretically drive a car knowing what kind of car you have, there's nothing wrong with that. However, sometimes it's sufficient enough to say that I just need a car to drive and it's not too important what kind of car it is as long as it's similar enough to the other Cars I know how to drive.

    For more about abstraction and inheritance, see:

    General CS concepts: Abstraction
    General CS concepts: Inheritance

  3. The Following User Says Thank You to helloworld922 For This Useful Post:

    JavaPF (July 12th, 2011)

  4. #3
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,676
    Thanks
    25
    Thanked 329 Times in 305 Posts

    Default Re: Help regarding Superclass variable can reference subclass object

    Ok, I'm not sure when this specific thing would be important, but I have an example that is sort of like it (which is far more important and realistic than what you have above), but is the same concept.

    Lets say we have an array that contains a mixture of A, B, and C objects. We obviously need to determine the identifier of the array. We don't want to use Object since it is too vague, but if we use A, each element can be either A Objects, B Objects, or C Objects, since B and C inherit from A. So, observe the code below:
    A[] arr = new A[]{new A(),new B(),new C(),new B(),new C(),new A()};

    Now, lets say we want to go through the array and call the callme() method on each object. When we pull the each item out of the array, we have to pull them as A Objects, since that is what the array is identified to. But, some of them are not A Objects, and they know they are not A Objects. So, when we run the code below:
    A[] arr = new A[]{new A(),new B(),new C(),new B(),new C(),new A()};
    		for(int i=0;i<arr.length;i++)
    		{
    			A item = arr[i];
    			item.callme();
    		}

    It outputs:

    Inside A's callme method
    Inside B's callme method
    Inside C's callme method
    Inside B's callme method
    Inside C's callme method
    Inside A's callme method

    Even though we don't necessarily know what the Object we are pulling out (A,B, or C), the object knows what it is, so we can assign a temporary A object to each value in the array, but still have it operate like the object that it is.

    NOTE: There are a few little tid-bits about this, such as even though an object is a B or a C object, by setting it to an A object, we are restricting those B and C objects to only have access to the methods and variables in the A class. But that is kind of confusing to visualize.
    NOTE TO NEW PEOPLE LOOKING FOR HELP ON FORUM:

    When asking for help, please follow these guidelines to receive better and more prompt help:
    1. Put your code in Java Tags. To do this, put [highlight=java] before your code and [/highlight] after your code.
    2. Give full details of errors and provide us with as much information about the situation as possible.
    3. Give us an example of what the output should look like when done correctly.

    Join the Airline Management Simulation Game to manage your own airline against other users in a virtual recreation of the United States Airline Industry. For more details, visit: http://airlinegame.orgfree.com/

  5. The Following User Says Thank You to aussiemcgr For This Useful Post:

    JavaPF (July 12th, 2011)

  6. #4
    Junior Member
    Join Date
    Jul 2011
    Posts
    28
    My Mood
    Busy
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Help regarding Superclass variable can reference subclass object

    Quote Originally Posted by helloworld922 View Post
    The reason is abstraction. The idea is that you don't need to know every little tiny detail about the object. For example, say you're driving a car. For the most part, the pedal on the right makes you go faster, the pedal on the left slows you down, and the big round thing in front of you steers the car. How that happens isn't important for the driver (a.k.a. user) to know, but it is very important for those details to work properly in order for the car to actually move.

    These details could be for example how much gas should I use, is it fuel inject, how much air should I allow into the cylinders, and how much cooling load to I need to provide the engine as it's running.

    Similarly, you're base class would be something like "Car". It has the basic interactions needed to drive the car from the user's perspective (speed up, slow down, and steer), but the specific details shouldn't need to be spelled out there. Instead, the sub-classes, for example "Honda Civic SI 1996" or "Fararri F40" would have different ways to accomplish the goals of a car (speeding up, slowing down, and steering).

    Yes, you could theoretically drive a car knowing what kind of car you have, there's nothing wrong with that. However, sometimes it's sufficient enough to say that I just need a car to drive and it's not too important what kind of car it is as long as it's similar enough to the other Cars I know how to drive.

    For more about abstraction and inheritance, see:

    General CS concepts: Abstraction
    General CS concepts: Inheritance

    Hey thanks friend.....!thanks for taking your time out and replying back wonderfully.....you are very close to solving my problem. Lets consider this way.... there are 3 persons who are related with my code
    1]user of the application i develop.
    2]the person who writes code for the application.[myself]
    3]Compiler/java application launcher[or whatever that says that the code i have written is error free and it is ready to use.]

    As far as the user(1) is considered i don't want to bother whether he knows or not that i have written a method called callme() or is it written once in main() or in classes that i have extended.His only concern is whether he i getting the required output.(Let it be like he is driving a car and he is happy with the car's performance..... left pedel is for braking and right pedal is for accelerating......and most important that left pedal is on left side and right pedal is on right side)

    As far as the compiler is concerned it knows i am driving a honda civic which is of subclass SEDAN which in turn is a subclass of VEHICLE class.[I mean i have already told compiler i have initialiazed class B and class C at the begining of my code in main() to access methods in those class.SO compiler knows everything]

    NOW here comes the tricky part....... I as a person who writes code knows when to call callme() of class B or callme() of class c depending on any condition that my application demands...Say if end user inputs SEDAN i'll call callme() of class B and if he inputs HATCHBACK then i'll call callme() of class C. I mean i know which one to call.Now why should i explicitly attach callme() to superclass variable r of superclass A and then call callme();

    that is if user input is SEDAN then [consider my first code of class variables]...... r=b;r.callme();
    and
    if user input is HATCHBACK then ...... r=c;r.callme();

    why overhead coding of these r=b; and r=c;

    i'll simply write
    if user input is SEDAN........ b.callme();
    if user input is HATCHBACK.... c.callme();


    What i want is when will i find such a situation where i need to explicitly assign b[class B variable/object] or c[class C variable/object] to r[class A variable/object] and then use callme().

    Its like giving a car to my user with its bonnet painted its a honda civic and its a SEDAN and its of VEHICLE class.

    The user knows its honda civic and in general he knows its a SEDAN and its of VEHICLE class.

    compiler knows that i am desiging honda civic[SEDAN] and volkswagen polo[HATCHBACK] which i have created objects of SEDAN HATCHBACK[B b = new B(); and C c = new C(); ]
    now if user inputs HATCHBACK i'll use c and if user inputs SEDAN i'll use b.

    why should i again code referring it to CLASS vehicle...that is

    A a = new A(); // object of type A class VEHICLE
    B b = new B(); // object of type B class SEDAN
    C c = new C(); // object of type C class HATCHBACK
    A r; // obtain a reference of type A

    [if user input is SEDAN]
    r=b;
    r.callme();


    [and if user input is HATCHBACK]
    r=c;
    r.callme();

    why not doing it without this overhead coding


    [if user input is SEDAN]

    b.callme();


    [and if user input is HATCHBACK]

    c.callme();


    I MEAN WHEN WILL I PRACTICALLY HAVE THAT SITUATION OF ASSIGNING SUPERCLASS VARIABLE TO REFERENCE SUBCLASS OBJECTS.

    ANYWAYS THANKS FOR REPLYING EARLIER..........VERY KIND OF YOU.

  7. #5
    Super Moderator helloworld922's Avatar
    Join Date
    Jun 2009
    Posts
    2,896
    Thanks
    23
    Thanked 619 Times in 561 Posts
    Blog Entries
    18

    Default Re: Help regarding Superclass variable can reference subclass object

    The user isn't necessarily the person who will eventually use your program externally, the user is usually the person who's using that piece of code in conjunction with their code.

    The reason why you provide the interface is because what if in a year from now, they come out with a new car?

    That means you'd need to go and find everywhere that could use a car and change it.

    if(car instanceof Fararri)
    {
         // .. drive a Fararri
    }
    else if (car instancof Jeep)
    {
        // .. drive a Jeep
    }
    else if (car instanceof NewHotness)
    {
        // .. drive the New Hotness
    }

    and on and on. This is very tedious, error prone (what if you accidentally implemented driving a car type A incorrectly?), and often times, not possible because you may not want someone else modifying your code just to satisfy their whims (not to mention, they probably don't want to go through all that work).

    It's much easier to just specify that you have a car, and the compiler/JVM will know because of how you're overriding the method which one to call directly.

    // have a car, just drive it. The JVM will know which car specifically it has and will call the right method.
    car.drive();

    This code will work for any existing and future subclasses of Car, as long as it's interface is similar.

    edit:

    Note that there's nothing wrong with referring to a specific type of Car (sometimes it may be desirable). It's just that often times when there are multiple types and they could all be valid, it's much easier and reliable to abstract away the details.
    Last edited by helloworld922; July 9th, 2011 at 01:01 AM.

  8. #6
    Junior Member
    Join Date
    Jul 2011
    Posts
    28
    My Mood
    Busy
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Help regarding Superclass variable can reference subclass object

    Friend Thanks a lot...........you just solved my thinking...i mean it it has really changed the way i think especially this line of yours.....
    The user isn't necessarily the person who will eventually use your program externally, the user is usually the person who's using that piece of code in conjunction with their code.

    THANKS for solving my problem....Now if anybody asks me about this.... i got a concrete answer which can be justified.
    THANKS A LOT....TAKE CARE

  9. #7
    Junior Member
    Join Date
    Jul 2011
    Posts
    28
    My Mood
    Busy
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Help regarding Superclass variable can reference subclass object

    Quote Originally Posted by aussiemcgr View Post
    Ok, I'm not sure when this specific thing would be important, but I have an example that is sort of like it (which is far more important and realistic than what you have above), but is the same concept.

    Lets say we have an array that contains a mixture of A, B, and C objects. We obviously need to determine the identifier of the array. We don't want to use Object since it is too vague, but if we use A, each element can be either A Objects, B Objects, or C Objects, since B and C inherit from A. So, observe the code below:
    A[] arr = new A[]{new A(),new B(),new C(),new B(),new C(),new A()};

    Now, lets say we want to go through the array and call the callme() method on each object. When we pull the each item out of the array, we have to pull them as A Objects, since that is what the array is identified to. But, some of them are not A Objects, and they know they are not A Objects. So, when we run the code below:
    A[] arr = new A[]{new A(),new B(),new C(),new B(),new C(),new A()};
    		for(int i=0;i<arr.length;i++)
    		{
    			A item = arr[i];
    			item.callme();
    		}

    It outputs:

    Inside A's callme method
    Inside B's callme method
    Inside C's callme method
    Inside B's callme method
    Inside C's callme method
    Inside A's callme method

    Even though we don't necessarily know what the Object we are pulling out (A,B, or C), the object knows what it is, so we can assign a temporary A object to each value in the array, but still have it operate like the object that it is.

    NOTE: There are a few little tid-bits about this, such as even though an object is a B or a C object, by setting it to an A object, we are restricting those B and C objects to only have access to the methods and variables in the A class. But that is kind of confusing to visualize.

    Thanks friend for your solution.Yea its too confusing to visualize this concept.But most importantly by using a superclass variable
    to reference a subclass object we are just explaining the code to other guys who might use my code to extend my superclass.
    [Imp:-Each superclass must have its own use...then only making a temporary variable of superclass and using it to reference a
    subclass object comes to effect. Its an option in java if you want to explain your code in a generalized way.....to use it or not is
    left to us......if i am right]

  10. #8
    Forum old-timer
    Join Date
    Nov 2008
    Location
    Faversham, Kent, UK
    Posts
    472
    My Mood
    Mellow
    Thanks
    4
    Thanked 58 Times in 54 Posts

    Default Re: Help regarding Superclass variable can reference subclass object

    Don't forget that by writing the bulk of your code in terms of interfaces (the 'ultimate superclasses', which just declare what methods a class should have, but leave all implementation to subclasses), you make life much easier for yourself as a developer, because you don't have to worry about the implementation code of individual subclasses until you actually want to test out the application, and you know that anyone (including you) can use your basic code however they want as long as they implement the interfaces you specified. You're basically saying "Here's my design, this application will work as intended if you provide objects that implement the specified interfaces". This allows you to work at a higher level of design abstraction when writing the code framework, and leave the fiddly implementation details until later.
    Last edited by dlorde; July 11th, 2011 at 04:21 AM.

  11. #9
    Junior Member
    Join Date
    Jul 2011
    Posts
    28
    My Mood
    Busy
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Help regarding Superclass variable can reference subclass object

    Quote Originally Posted by dlorde View Post
    Don't forget that by writing the bulk of your code in terms of interfaces (the 'ultimate superclasses', which just declare what methods a class should have, but leave all implementation to subclasses), you make life much easier for yourself as a developer, because you don't have to worry about the implementation code of individual subclasses until you actually want to test out the application, and you know that anyone (including you) can use your basic code however they want as long as they implement the interfaces you specified. You're basically saying "Here's my design, this application will work as intended if you provide objects that implement the specified interfaces". This allows you to work at a higher level of design abstraction when writing the code framework, and leave the fiddly implementation details until later.

    Yea..! got it.

Similar Threads

  1. JButton Auto-changing Reference Variable
    By bgroenks96 in forum What's Wrong With My Code?
    Replies: 6
    Last Post: June 19th, 2011, 10:57 PM
  2. [SOLVED] Invoking a superclass constructor in my subclass
    By kari4848 in forum Object Oriented Programming
    Replies: 5
    Last Post: April 29th, 2011, 01:12 PM
  3. cannot find symbol in reference variable
    By NPotter86 in forum What's Wrong With My Code?
    Replies: 2
    Last Post: November 1st, 2010, 08:21 PM
  4. Instantiating a SuperClass Map from a SubClass
    By drexasaurus in forum Collections and Generics
    Replies: 1
    Last Post: September 9th, 2010, 10:51 PM