Results 1 to 14 of 14
Like Tree1Likes
  • 1 Post By pbrockway2

Thread: Polymorphism and Access to a Subclass' Members

  1. #1
    awinston is offline Student
    Join Date
    Jul 2012
    Location
    United States
    Posts
    328
    Rep Power
    3

    Default Polymorphism and Access to a Subclass' Members

    I recently experienced a revelation about the nature of polymorphism (thanks to Furarable). However, it seems that this revelation has led to a deeper mystery.

    I have 3 classes: Automobile, Car, and TestAutomobile

    Automobile.java:
    Java Code:
    public class Automobile
    {
    
        public Automobile()
    	{
    		
    	}
    
    	public void printType()
    	{
    		System.out.println("None");
    	}
    	
    	public void printData()
    	{
    		System.out.println("None");
    	}
    
    }
    Car.java:
    Java Code:
    public class Car extends Automobile
    {
    
    	public String type;
    	public String color;
    
    	public Car()
    	{
    		type = "Car";
    		color = "Green";
    	}
    
    	public void printType()
    	{
    		System.out.println(type);
    	}
    
    	public void printData()
    	{
    		this.printColor();
    	}
    
    	public void printColor()
    	{
    		System.out.println(color);
    	}
    
    }
    I am confused about what exactly happens when an instance of Car is placed inside a variable of type Automobile. Here is part of TestAutomobile.java:

    Java Code:
    public class TestAutomobile
    {
    
    	public static void main(String[] args)
    	{
    		Automobile car1 = new Car();
    	}
    
    }
    At this point, I understand that car1 has access only to the printType() and printData() methods of the Car class (because these methods override like-named methods of the Automobile class). Therefore, it makes sense that if I execute this code, an error is thrown:

    Java Code:
    System.out.println(car1.type);
    This leads me to believe that the car1.type is currently inaccessible. However, no errors are thrown if I execute this code:

    Java Code:
    car.printType();
    Since printType() of class Car accesses car1.type, this leads me to believe that car1.type is accessible. I understand that type is accessed indirectly through a method that is accessible, so maybe that is just what happens and I'm over analyzing what is going on. A similar case arises with the accessibility of the printColor() method of class Car. If I execute this code, an error is thrown (as expected):

    Java Code:
    car1.printColor();
    This leads me to believe that the method printColor() is currently inaccessible (which makes sense in terms of polymorphism). However, this code does not throw an error upon execution:

    Java Code:
    car.printData();
    The printData() method of class Car accesses the printColor() method, so this leads me to believe that the car1.printColor() method is accessible. My question in as simple of terms as I can put it: Why do the inaccessible members of the Car class become accessible to car1 when I access them indirectly through methods that are accessible?
    Last edited by awinston; 08-01-2012 at 07:19 PM. Reason: Title Edit
    "Success is not final, failure is not fatal: it is the courage to continue that counts." - Winston Churchill

  2. #2
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,565
    Rep Power
    12

    Default Re: Polymorphism and Access to a Subclass' Members

    You might be being confused by "accessible". The compiler has its (rather strong) views about what can be done with variables and other expressions. But there is a somewhat separate question about what, at runtime, can be done with instances (objects). So, deliberately avoiding "accessible":

    Automobile car1 = new Car();
    This line declares a variable car1 of type Automobile. And it creates an instance of Car. And it assigns a reference to the newly created car as the value of the variable.

    When you say car1.something or car1.someMethod() the compiler will grumble if something or someMethod() are not declared as part of Automobile: that's what we mean by saying the variable car1 is of type Automobile.

    But when you say car1.someMethod() what actually happens at runtime will depend on the actual instance (thing, object) referred to by car1. car1 is of type Automobile, but the automobile it refers to is a car and has all the state and behaviour associated with Car. Colour printing is certainly something this object can do (because it's a Car), but it is *not* something we can ask it to do using the variable car1 because that variable is of type Automobile. (*) What we can do is ask it to print its data (which is Automobile behaviour) and - car that it is - it will print its colour.

    (* Except, of course, by casting the variable.)
    Last edited by pbrockway2; 08-01-2012 at 08:04 AM.

  3. #3
    awinston is offline Student
    Join Date
    Jul 2012
    Location
    United States
    Posts
    328
    Rep Power
    3

    Default Re: Polymorphism and Access to a Subclass' Members

    So all of the fields and methods of class Car are accessible to car1 as long as it makes sense for an Automobile to access them?

    I'm sensing an almost synonymous relationship between the accessibility of Car's methods with the accessibility of private fields. If class A has a private variable, it cannot be accessed directly by a client class. However, if there is public method in class A that returns the private variable, then the private variable can be accessed indirectly by the client class.

    Similarly, car1 cannot access its type variable directly. However, if there is an accessible method that returns this otherwise inaccessible field, then type can be accessed indirectly by car1.
    "Success is not final, failure is not fatal: it is the courage to continue that counts." - Winston Churchill

  4. #4
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    11,792
    Rep Power
    19

    Default Re: Polymorphism and Access to a Subclass' Members

    car1 is not "accessing" anything indirectly.
    The object 'car1' is pointing at is a Car, and so has full access to everything something of class Car can access.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  5. #5
    awinston is offline Student
    Join Date
    Jul 2012
    Location
    United States
    Posts
    328
    Rep Power
    3

    Default Re: Polymorphism and Access to a Subclass' Members

    Quote Originally Posted by Tolls View Post
    car1 is not "accessing" anything indirectly.
    The object 'car1' is pointing at is a Car, and so has full access to everything something of class Car can access.
    But it cannot access its type variable or its printColor() method because it is referenced by a variable of type Automobile.
    "Success is not final, failure is not fatal: it is the courage to continue that counts." - Winston Churchill

  6. #6
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    11,792
    Rep Power
    19

    Default Re: Polymorphism and Access to a Subclass' Members

    No, the object can.
    But because the reference 'car1' is declared as the parent, then the compiler throws an error.

    You need to remember there are two things at work here, the reference and the object.
    It isn't really synonymous to private/public.

    It's best viewed as a contract. Your 'car1' has a contract represented by the Automobile class (that's what 'car1' is defined as).
    That that contract is actually handled by the underlying Car class is not important in terms of what you can do with the 'car1' object, since its contract is as an Automobile.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  7. #7
    awinston is offline Student
    Join Date
    Jul 2012
    Location
    United States
    Posts
    328
    Rep Power
    3

    Default Re: Polymorphism and Access to a Subclass' Members

    Okay, then let's discuss this matter in terms of the contract. The contract prohibits the Car object from accessing the variable type and method printColor(). The contract allows the Car object to access its printType() and printData() methods. Therefore, the prohibitions of the contract can be bypassed if the "allowed" methods invoke the "prohibited" methods. In short, anything inside the "allowed" methods is okay even if it violates the prohibitions of the contract.
    "Success is not final, failure is not fatal: it is the courage to continue that counts." - Winston Churchill

  8. #8
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    11,792
    Rep Power
    19

    Default Re: Polymorphism and Access to a Subclass' Members

    No it prevents you using the 'car1' reference to access those things.
    The object underlying that reference can access them. It only needs to ensure that it does what the contract for Automobile says (it won't compile if it doesn't)...outside of that it can also do whatever else it wants.

    This is best illustrated with interfaces. A concrete class implementing an interface must provide implementations for all the methods the interface declares...that's the contract. This does not prevent that class providing other methods.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  9. #9
    awinston is offline Student
    Join Date
    Jul 2012
    Location
    United States
    Posts
    328
    Rep Power
    3

    Default Re: Polymorphism and Access to a Subclass' Members

    Quote Originally Posted by Tolls View Post
    No it prevents you using the 'car1' reference to access those things.
    The object underlying that reference can access them. It only needs to ensure that it does what the contract for Automobile says (it won't compile if it doesn't)...outside of that it can also do whatever else it wants.
    Right, I'm pretty sure we are in agreement here. The Car object by itself can access all of its members, but the contract of the Automobile reference prohibits and allows it to access only certain members.
    "Success is not final, failure is not fatal: it is the courage to continue that counts." - Winston Churchill

  10. #10
    awinston is offline Student
    Join Date
    Jul 2012
    Location
    United States
    Posts
    328
    Rep Power
    3

    Default Re: Polymorphism and Access to a Subclass' Members

    Thank you for the responses, Tolls and pbrockway2.
    "Success is not final, failure is not fatal: it is the courage to continue that counts." - Winston Churchill

  11. #11
    awinston is offline Student
    Join Date
    Jul 2012
    Location
    United States
    Posts
    328
    Rep Power
    3

    Default Re: Polymorphism and Access to a Subclass' Members

    Quote Originally Posted by pbrockway2 View Post
    You might be being confused by "accessible". The compiler has its (rather strong) views about what can be done with variables and other expressions. But there is a somewhat separate question about what, at runtime, can be done with instances (objects). So, deliberately avoiding "accessible":



    This line declares a variable car1 of type Automobile. And it creates an instance of Car. And it assigns a reference to the newly created car as the value of the variable.

    When you say car1.something or car1.someMethod() the compiler will grumble if something or someMethod() are not declared as part of Automobile: that's what we mean by saying the variable car1 is of type Automobile.

    But when you say car1.someMethod() what actually happens at runtime will depend on the actual instance (thing, object) referred to by car1. car1 is of type Automobile, but the automobile it refers to is a car and has all the state and behaviour associated with Car. Colour printing is certainly something this object can do (because it's a Car), but it is *not* something we can ask it to do using the variable car1 because that variable is of type Automobile. (*) What we can do is ask it to print its data (which is Automobile behaviour) and - car that it is - it will print its colour.

    (* Except, of course, by casting the variable.)
    After re-reading your explanation this makes a lot more sense. An Automobile doesn't understand what the command "print your color" means (it doesn't even necessarily have a color), but it does understand the command "print your data."
    "Success is not final, failure is not fatal: it is the courage to continue that counts." - Winston Churchill

  12. #12
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,565
    Rep Power
    12

    Default Re: Polymorphism and Access to a Subclass' Members

    An Automobile doesn't understand what the command "print your color" means (it doesn't even necessarily have a color), but it does understand the command "print your data."
    Yes. (Sorry I hadn't realised this thread had replies...) And it's not so much that Automobile forbids anything Car specific: it's just that it doesn't have a clue about colour.

    A couple of other thoughts strike me about subclassing:

    (0) Seriously consider not doing this. There might be alternatives that at least deserve consideration.

    Those of us of a certain age will remember "ColouredPoint extends Point" or its C++ equivalent. Nowadays we are told to "prefer composition to inheritance" and will at least consider if the following doesn't better express what we are trying to do:

    Java Code:
    class ColouredPoint {
        private Point location; // ColouredPoint HAS-A location, not IS-A point
        private Color colour;
    }
    (1) Take your declarations seriously.

    If you declare car1 as Automobile then *think* of it as an automobile. (Even change it to auto1!) If you find yourself wanting to know about its colour etc, then there's a good chance you have declared it wrongly to begin with. It might take work to correct the declaration because it affects method arguments etc, but that's better than writing the code with a cast and a prayer.

  13. #13
    awinston is offline Student
    Join Date
    Jul 2012
    Location
    United States
    Posts
    328
    Rep Power
    3

    Default Re: Polymorphism and Access to a Subclass' Members

    Quote Originally Posted by pbrockway2 View Post
    Yes. (Sorry I hadn't realised this thread had replies...) And it's not so much that Automobile forbids anything Car specific: it's just that it doesn't have a clue about colour.

    A couple of other thoughts strike me about subclassing:

    (0) Seriously consider not doing this. There might be alternatives that at least deserve consideration.

    Those of us of a certain age will remember "ColouredPoint extends Point" or its C++ equivalent. Nowadays we are told to "prefer composition to inheritance" and will at least consider if the following doesn't better express what we are trying to do:

    Java Code:
    class ColouredPoint {
        private Point location; // ColouredPoint HAS-A location, not IS-A point
        private Color colour;
    }
    (1) Take your declarations seriously.

    If you declare car1 as Automobile then *think* of it as an automobile. (Even change it to auto1!) If you find yourself wanting to know about its colour etc, then there's a good chance you have declared it wrongly to begin with. It might take work to correct the declaration because it affects method arguments etc, but that's better than writing the code with a cast and a prayer.
    Agreed. I dreamt up this slightly awkward example solely for the purpose of clarifying the nature of polymorphism.
    "Success is not final, failure is not fatal: it is the courage to continue that counts." - Winston Churchill

  14. #14
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,565
    Rep Power
    12

    Default Re: Polymorphism and Access to a Subclass' Members

    I dreamt up this slightly awkward example solely for the purpose of clarifying the nature of polymorphism
    Yes. And that's an entirely reasonable (if not the only) way of going about things.
    awinston likes this.

Similar Threads

  1. Compile-time Polymorphism or Run-time Polymorphism ?
    By dejulial in forum New To Java
    Replies: 1
    Last Post: 03-06-2012, 07:14 PM
  2. Accessing abstract class subclass's data members
    By Claymz in forum New To Java
    Replies: 23
    Last Post: 04-18-2011, 11:26 AM
  3. access class members with linked list
    By billq in forum New To Java
    Replies: 5
    Last Post: 05-09-2010, 05:04 PM
  4. Polymorphism Help
    By AWPtic in forum New To Java
    Replies: 5
    Last Post: 04-06-2009, 04:13 PM
  5. what is polymorphism
    By Nari in forum New To Java
    Replies: 5
    Last Post: 04-04-2008, 03:14 AM

Posting Permissions

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