Z
Z
zevilcube2019-08-30 02:00:48
Java
zevilcube, 2019-08-30 02:00:48

Is it possible in Java to make an object of one class an object of another?

There is a class:

Class C1 {
 public C1 () {
  // Код конструктора
 }
}

There is another class that inherits the first one:
Class C2 extends C1{
}

And there is a method located in another part of the code:
public void myMethod (C1 c1object) {
// Код метода
}

In theory, any object of class C2 will also be an object of class C1 (yes?), But if we try to call it, we will get an error. Is it possible to get an object of class C1 from an object of class C2 ?
myMethod(new C2());

Answer the question

In order to leave comments, you need to log in

3 answer(s)
M
Maxim Moseychuk, 2019-08-30
@fshp

There is no error, everything works.
https://repl.it/@maksimmosieichuk/PromotedMulticol...
No. You can get a reference to an object of type C1 from a reference to C2. But at the same time, the object will still behave like C2, which it is. This is called polymorphism.

N
Nikita, 2019-08-30
@jkotkot

can. there will be no error. if you have a bug, then it's something else, not inheritance.

S
Senior Devosaur, 2019-08-30
@Cranberry

The right question already contains the answer. What exception does the compiler throw?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question