BradleyPeh
BradleyPeh

Reputation: 35

Abstract Class confusion, object declaration and object reference?

// I've cut down the code to get to the point 

abstract class TwoDShape {

   .... constructors

   .... example variables & methods 


abstract double area();

}

Below is where it gets confusing, why is TwoDShape shapes[] = new TwoDShape[4] allowed despite the Abstract rules which should have cause a compile time error ? Why does TwoDShape test = new TwoDShape(); or other similar construction failing to compile, causing errors ? Is it because shapes[] is an object reference due to it being in an array ? But isn't it an object declaration as well (considering new is also used).

class AbsShapes {
public static void main(String args[]) {

TwoDShape shapes[] = new TwoDShape[4];

shapes[0] = new Triangle("outlined", 8.0, 12.0);
shapes[1] = new Rectangle(10);
shapes[2] = new Rectangle(10, 4);
shapes[3] = new Triangle(7.0); 

for(int i = 0; i < shapes.length; i++) {
  System.out.println("Object is " + shapes[i].getName());
  System.out.println("Area is " + shapes[i].area());
  System.out.println();
  }

 }
}

Upvotes: 0

Views: 74

Answers (2)

Konrad Botor
Konrad Botor

Reputation: 5033

This line:

TwoDShape shapes[] = new TwoDShape[4]

creates and empty array of size four capable of storing object of type TwoDShape. The objects themselves are not created - in other words immediately after creation the array holds four nulls.

Now this line:

TwoDShape test = new TwoDShape();

claas the construtor of type TwoDShape to create an object of that type. Since class TwoDShape is declared abstract, the compiler throws an error.

You may want to read those for more clarification:

Upvotes: 1

ernest_k
ernest_k

Reputation: 45309

What cannot be created is direct instances of an abstract class:

new TwoDShape(); //this won't compile.

However, this is not creating direct instances of TwoDShape:

new TwoDShape[4]; //this is creating an array of type TwoDShape

The above code creates an array of TwoDShape type. No instance of TwoDShape is created. If you call shapes[0], you will get null, meaning that there's no TwoDShape object created.

In other words, the type of shapes is not TwoDShape, but TwoDShape[]. And array types can be created using new.

Upvotes: 1

Related Questions