Junaid S.
Junaid S.

Reputation: 2642

Interfaces and classes in JAVA

Lets have following Class Diagram as an example

enter image description here

I made similar classes in java like below

public class B {

}

public interface C {

}

public class A extends B implements C {

}

public class D {
    C c = new A();
    C c1 = new B(); // Error, Type mismatch: cannot convert from B to C. WHY ?
    C c2 = (C) new B(); // Works fine. This makes me confuse ... What does this actually mean ?
}

Can anybody explain this ?

Upvotes: 1

Views: 143

Answers (4)

Doug Knesek
Doug Knesek

Reputation: 6727

Extends means "is a kind of".

A is a kind of B, so it has all the features of B.

However, B isn't a kind of A, so it doesn't necessarily have all the features of A, including implementing the interface C. That's why you get the type mismatch.

But in this case:

C c2 = (C) new B()

Casting tells the compiler "Don't check this because I know what I'm doing." So it may compile.

But if at runtime the object you actually cast can't be typed as a C, you'll get a ClassCastException. In your case, you are casting a B to a C, and a B isn't a kind of C any more than it is a kind of A. So you'll get the exception.

Upvotes: 0

Ankur Shanbhag
Ankur Shanbhag

Reputation: 7804

C c1 = new B(); // Error, Type mismatch: cannot convert from B to C. WHY ?

You can refer to derived classed only through super class references. In your case, C is a not a super class of B. Hence the error

C c2 = (C) new B(); // This makes me confuse ... What does this actually mean ?

Compiler wont allow you to perform the above casting. To cast from one type to another, both the classes must be in the same Object hierarchy.

Upvotes: 0

gefei
gefei

Reputation: 19766

Why C c2 = (C) new B(); does not compile: see Ankur Shanbhag's answer.

C c2 = (C) new B(); may compile well, but since c2 is a B object and thus cannot be converted to C, this will throw an exception at runtime.

I made an example:

public class D {
    public static void main(String[] args) {
        C c2 = (C) new B();           
        System.out.println(c2);
    }
} 

And received an exception:

Exception in thread "main" java.lang.ClassCastException: casting.B cannot be cast to C

Upvotes: 1

Robert Moskal
Robert Moskal

Reputation: 22553

C c1 = new B()

You can never instantiate class B as interface C since it doesn't implement interface C.

C c2 = (C) new B()

In the second case you are explicitly casting the instance of B to type C. The compiler allows this, but you'll get a run-time exception.

Upvotes: 1

Related Questions