2

Suppose the following classes in Java :

TeachingAssistant extends Graduate

Can I make an object ofGraduate and use in TeachingAssistant? Example

TeachingAssistant TA1 = new TeachingAssistant();
Graduate grad1 = new Graduate();
grad1 = TA1; //can I do this?
TA1 = grad1;// can I do this as well?

Also suppose class A extends B and implements C can I make objects of B and C in A?

1
  • Have you tried just testing it yourself? Commented Sep 13, 2015 at 22:33

2 Answers 2

3

Given

class TeachingAssistant extends Graduate{}
class Graduate{}

This sums up what you can/cannot do (and why)

TeachingAssistant t = new TeachingAssistant(); //OK
Graduate g = new Graduate(); //OK
Graduate gt = new TeachingAssistant(); //OK
TeachingAssistant tg1= new Graduate(); //Compile error: a Graduate is NOT ALWAYS a TeachingAssistant
TeachingAssistant tg2= (TeachingAssistant) new Graduate(); //Runtime error: as previous example
TeachingAssistant tg3= (TeachingAssistant)gt; //OK: gt is an object of type TeachingAssistant 
                                              //referenced by reference of type Graduate
Sign up to request clarification or add additional context in comments.

Comments

0

I believe there is a few concepts here you mentioned about.

Composition vs Inheritance

Also suppose class A extends B and implements C can I make objects of B and C in A?

I am going to make a assumption to say that C is a interface as you mentioned about implementing it. No, it is impossible to instantiate C in A. It is possible to declare object B in A as class attribute, but the use case of this is rare and you should reconsider your design solution if you are doing it.

Upcasting

grad1 = TA1; //can I do this?

Yes, you can do this, but the correct syntax should be:

grad1 = (Graduate) TA1;

Downcasting

TA1 = grad1;// can I do this as well?

You cannot do this. This will leads to compilation error.

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.