0

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();

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.