Jim
Jim

Reputation: 353

Abstract Class Initialization in Java

I'm currently studying for the AP Computer Science exam. I see some questions which could have a abstract class such as

public abstract class ConstructionWorker {
     public ConstructionWorker() {
         // implimentation
     }

     // other methods
}

And another class such as

public class Carpenter extends COnstructionWorker {
     public Carpenter() {
         super()
     }
}

What would the differences in initializing the object be between these two things?

ConstructionWorker bob = new Carpenter();
Carpenter jane = new Carpenter();

Upvotes: 0

Views: 471

Answers (2)

L.Spillner
L.Spillner

Reputation: 1772

The solution is, every Carpenter is an instance of ConstructionWorker but now the other way around, which means when you assign a Carpenter to an ConstructionWorker you can only use methods declared in the ConstructionWorker class. In other words you lose all methods that have been declared/overriden in the Carpenter class.

Upvotes: 0

apetranzilla
apetranzilla

Reputation: 5929

That's an example of polymorphism. In both cases, you're constructing a Carpenter instance, but in the first case, you're storing it as a ConstructionWorker, which means you can only access ConstructionWorker members through it (unless you cast it back to Carpenter).

Under the hood, they're still both Carpenter instances - you're just accessing one of them as a ConstructionWorker instead.

Upvotes: 3

Related Questions