Rafael Angarita.
SCJP 6.
SCJP 78%, and looking for the next certification
Rafael Angarita wrote:I think they both compile fine.
Harry Henriques wrote:The following code snippet DOES NOT compile, but the code snippet below it DOES compile and run. This problem is part of a Drag-n-Drop problem from ExamLab by M Devaka Cooray.
The example below DOES compile without warnings or errors, and runs without exceptions. What is the difference between this code and the code above, and why does the keyword "final" make the difference?
Life is easy because we write the source code.....
Ben,
--Lost in preparation of SCJP and SCWCD--
"Start writing a new chapter, for if you live by the book you'll never make history." (Ben Sobel)
Ben Zaidi wrote:Hello,
It is because, when you declare a class final, then all of its methods are final implicitly. So as data members also i suppose.
Umm i believe my notion is wrong, because if we do something like
c[0] = new CCC();
It works. Additionally, both of the classes are not lying in the same inheritance hierarchy.
If you change the code somehow like this.
In this case, it is compiling fine even with the keyword Final.
Ben,
--Lost in preparation of SCJP and SCWCD--
"Start writing a new chapter, for if you live by the book you'll never make history." (Ben Sobel)
SCJP 6 | SCWCD 5 | Javaranch SCJP FAQ | SCWCD Links
Ankit Garg wrote:In case of a non-final class, a cast to/from interface is always allowed as there might be a class that is a sub-type of both. For example
So even if you don't declare a class D, but it might exists somewhere or someone else might create it, so the compiler allows a cast between a non-final class and interface. But in case of final-class, if that class doesn't implement an interface, then a cast between that interface and the class is not allowed
Since there can't be any class that is a sub-type of both C and I, so there can't be any object that IS-A C and I. This is why a cast between C and I is rejected at compile time as the compiler knows that the cast can't succeed at runtime.
HTH