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: Inheritance - Object class

  1. #1
    Junior Member
    Join Date
    Dec 2012
    Posts
    8
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Inheritance - Object class

    Hello,

    The following code doesn't compile because it says "method area()" not found when called with the object reference "o". If every class in Java is a subclass of the Object class, why is this throwing an error?
    package test;
      // Using abstract methods and classes.
    abstract class Figure{
    double dim1;
    double dim2;
    Figure(double a, double b) {
    dim1 = a;
    dim2 = b;
    }
    // area is now an abstract method
    abstract double area();
    }
    class Rectangle extends Figure {
    Rectangle(double a, double b) {
    super(a, b);
    }
    // override area for rectangle
    double area() {
    System.out.println("Inside Area for Rectangle.");
    return dim1 * dim2;
    }
    }
    class AbstractDemo {
    public static void main(String args[]) {
     
     
    Object o = new Rectangle(10,5);
     
    System.out.println("Area is " + o.area());
     
    /* This is compiling
     
    Figure f = new Rectangle (10,5);
    System.out.println("Area is" + f.area()); */
     
     
    }
    }
    Last edited by helloworld922; December 29th, 2012 at 02:31 AM. Reason: please use [code] tags


  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: Inheritance - Object class

    area isn't a method of the Object class.

    What does it even mean to take the area of an Object? What if that Object is a String?

    The compiler has no way of knowing what type of object the variable o is going to contain. It could be rectangles, squares, strings, jframes, etc. So it does the only sensible thing it can do and that is throw a compiler error.

    On the other hand, a Figure is defined to have an area method. That means every instance of a Figure or a subclass of Figure is guaranteed to implement area. It may not be implemented correctly, but it exists so it is perfectly valid syntax to try and call that method.

  3. #3
    Junior Member
    Join Date
    Dec 2012
    Posts
    8
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: Inheritance - Object class

    ok, thank you. I get the point now, but I am confused as to what exactly happens when we do this (Object o = new Rectangle()). What does the program understand when we say this? And, what advantage does this usage have over just writing Rectangle r = new Rectangle ()?

  4. #4
    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: Inheritance - Object class

    You're saying 2 things:


    This declares a variable. It has a type Object. That means it can hold an instance of the Object class, or any class which extends the Object class.

    o = new Rectangle()

    This creates a new instance of the Rectangle class. The variable o refers to this instance. It is allowed to do so because Rectangle extends Object. However, you are only allowed to use this Rectangle instance is if it was an Object instance. This is known as polymorphism.

    Why is this useful?

    Take the following example:

    Say you have three classes: Rectangle, Circle, and Triangle. Each class has an implementation of the area method. Now you want to be able to find the sum area of a given collection of Rectangles, Circles, and Triangles.

    You could do this:

    public static double sumArea(Rectangle[] rects, Circle[] circs, Triangle[] triags)
    {
        double sum = 0;
        for(int i = 0; i < rects.length; ++i)
        {
            sum += rects[i].area();
        }
        for(int i = 0; i < circs.length; ++i)
        {
            sum += circs[i].area();
        }
        for(int i = 0; i < triags.length; ++i)
        {
            sum += triags[i].area();
        }
        return sum;
    }

    This works, but there are 2 big flaws:

    1. What if you have a dozen or more different shapes? The amount of code even for 3 different shapes is already starting to get out of hand.

    2. What if you decide at a later date that you want to add a Pentagon class? That means you'd have to go back through your other code and manually modify them to include code which handles pentagons.

    The preferred method is to have a common base class/interface which each shape would implement. The base class needs to be able to do at least what your application requires. For example, say I had a Shape class:

    public abstract class Shape
    {
        abstract double area();
    }

    I could then implement the sumArea method this way:

    public static double sumArea(Shape[] shapes)
    {
        double sum = 0;
        for(int i = 0; i < shapes.length; ++i)
        {
            sum += shapes[i].area();
        }
        return sum;
    }

  5. #5
    Junior Member
    Join Date
    Dec 2012
    Posts
    8
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: Inheritance - Object class

    Thank you for the response. This is very helpful. I get the point about the class being generic. I think I didn't word the 2nd part of my previous question properly.

    When we use a reference variable of the Object class and then make it refer to the rectangle object, like

    Object o = new Rectangle();

    What is the need in general to create a super class reference variable and make it point to a sub-class object? I read in the book that this usage enables Java to resolve method overriding at run time. But, I am just not able to imagine a scenario where it is useful to write "Object o = new Rectangle()" and "o.area()" instead of just writing "Rectangle r = new Rectangle()" and "r.area()". I am thinking why not just create all objects like this instead of using a super class reference variable. This kind of usage will also allow Java to resolve dynamically because using "r.area()" would call the rectangle's area and then "Triangle t = new Triangle()" and "t.area()" would only call triangle's area. Why would I instead need a super class variable to implement dynamic dispatch? I am sure my understanding is very simplistic and I am missing the deeper concept behind it somewhere here. Please help.

  6. #6
    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: Inheritance - Object class

    I think you're confusing the actual instances vs. variables.

    All variables must have a type in Java. This is fixed and must be explicitly declaring it, a variable will always hold a value/instance of that type.

    If I declare a variable r with type Rectangle, it can only hold rectangles. I can't do this:

    Rectangle r = new Circle();

    So the question is what variable type should you use if you have various shapes? You need a common base class that has all the features you need/want.

    If you want an area method, this isn't in the Object class so you must define your own class which does have the area method defined. The Java compiler can't figure out at compile time what exact instance a variable will hold (if any), so it does the only thing it can do and that's give you a compiler error.

    If all you need is a specific type, then there's no reason why you can declare a variable of that type directly.

    Rectangle r = new Rectangle();
    r.area();

    This is used quite a lot and there's nothing wrong with it. Just be aware of the benefits you get from using polymorphism as I pointed out above.

  7. #7
    Junior Member
    Join Date
    Dec 2012
    Posts
    8
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: Inheritance - Object class

    Thank you for persisting with me. I've copied here the text I don't understand.

    "Dynamic method dispatch is the mechanism
    by which a call to an overridden method is resolved at run time, rather than compile time.
    Dynamic method dispatch is important because this is how Java implements run-time
    polymorphism.
    Let’s begin by restating an important principle: a superclass reference variable can refer
    to a subclass object. Java uses this fact to resolve calls to overridden methods at run time. Here
    is how. When an overridden method is called through a superclass reference, Java determines
    which version of that method to execute based upon the type of the object being referred
    to at the time the call occurs. Thus, this determination is made at run time. When different
    types of objects are referred to, different versions of an overridden method will be called.
    In other words, it is the type of the object being referred to (not the type of the reference variable)
    that determines which version of an overridden method will be executed."


    My question here, where is the need for a super class variable in order to implement run-time polymorphism, when actually declaring a variable of the subclass type itself will do that? Why does the text state this "Let’s begin by restating an important principle: a superclass reference variable can refer
    to a subclass object. Java uses this fact to resolve calls to overridden methods at run time".?

    What difference does the super class reference variable make here?

  8. #8
    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: Inheritance - Object class

    How do you refer to a class instance? It's done using a variable. A variable must have exactly one type explicitly declared for as long as the variable exists.

    So you want a variable that can refer to both circles and rectangles. How can you do that? You need to trace back the inheritance tree until you find a common class both share. If there is no common class it's impossible for any single variable to refer to either a rectangle or circle instance. Note that this isn't necessarily true for some other languages which allow dynamically typed variables. Java just isn't one of those languages.

    Your textbook is simply referring to this as a "super-class reference variable" because it's type is that common base class. There's not much really special about it, the syntax is exactly the same as you would declare any other variable. The textbook is merely making a point to show that a variable can hold the type it is explicitly declared with as well as any sub-types.

  9. #9
    Junior Member
    Join Date
    Dec 2012
    Posts
    8
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: Inheritance - Object class

    Thank you.

Similar Threads

  1. Java and Flickr - Help with Inheritance between Main Class and sub-class
    By thientanchuong in forum What's Wrong With My Code?
    Replies: 10
    Last Post: December 14th, 2012, 07:29 PM
  2. Java and Flickr - Help with Inheritance between Main Class and sub-class
    By thientanchuong in forum What's Wrong With My Code?
    Replies: 0
    Last Post: December 12th, 2012, 08:10 PM
  3. Inheritance; Problem with Test class
    By Charlie.beat in forum What's Wrong With My Code?
    Replies: 19
    Last Post: April 8th, 2012, 11:59 PM
  4. Multilevel inheritance of an abstract class
    By user2205 in forum Java Theory & Questions
    Replies: 1
    Last Post: September 27th, 2011, 06:00 PM
  5. Replies: 7
    Last Post: July 21st, 2011, 03:29 PM