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?
Code java:
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()); */
}
}
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.
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 ()?
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.
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:
Code java:
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:
Code java:
public abstract class Shape
{
abstract double area();
}
I could then implement the sumArea method this way:
Code java:
public static double sumArea(Shape[] shapes)
{
double sum = 0;
for(int i = 0; i < shapes.length; ++i)
{
sum += shapes[i].area();
}
return sum;
}
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.
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:
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.
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.
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?
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.
Re: Inheritance - Object class