Fill subclasses extending the same original class

How can I add two extends classes in java?

    class B extends Object{

    }

    class C extends Object{

    }

    B b = new B();

    C c = (C)b;//Cannot cast from B to C
+3
source share
7 answers

You can not. Consider a small rename:

class Ford extends Car{

}
class Chevrolet extends Car{

}

Ford ford = new Ford();

Chevrolet chevrolet = (Chevrolet) ford;

Both are, however, a car, so you can tell

Car car = ford;

but no more than that.

+11
source

Closest you can use interfaces

 class B extends Object implements Thing {}
 class C extends Object implements Thing {} 

 B b = new B()
 Thing c = (Thing)b

As others have shown, you cannot do what you are trying with only classes.

+3
source

B C, B C, , Object. :

class Animal {
    public void eat();
}

class Dog extends Animal {
    public void bark();
}

public Cat extends Animal {
    public void meow();
}

, :

Cat sprinkles = new Cat();

// this doesn't make sense
Dog aDog = (Dog) sprinkles;
aDog.bark(); // can't do this because sprinkles can't bark()

// but this does
Animal myCat = (Animal) sprinkles;
myCat.eat(); // but it can eat()
+3

, b C. .

+2

. , , , . B C ( ). - ? ?

+1

B class C "is-a", .

, B C, , Object, Object. , B is-a Object C is-a Object:

B b = new B();
Object ob = (Object)b;

C c = new C();
Object oc = (Object)c;

, , :

class B extends Object {
    public void doSomething();
}

class C extends Object {
    public void doAnotherThing();
}

, ?

C realC = new C();
realC.doSomething();   // This is OK.

B c = (B)realC;
c.doSomething();       // ???

, C, doSomething, ? , , B C , , .

, , , .

+1

but ... providing this hierarchy class X {} class Z extends X{} class Y extends X{} X z = new Z(); X y = new Y(); Z y2 =(Z)y; Why alloweb compiler casting between Z and Y? It does not work at runtime, obviously cos Z is not Y.

+1
source

Source: https://habr.com/ru/post/1766635/


All Articles