Interface cast to final class

Read in a book saying that an interface object cannot be cast to a final class object. See the following:
final class Apple { }
interface Squeezable{ }
class Citrus implements Squeezable{ }In this case then:
Squeezable sq = new Citrus();
Apple apple = (Apple)sq; // compile errorOf course there are two fixes for the compile error.
(1) Make Apple implement Squeezable (this is easy to understand).
(2) Make Apple a non-final class (although there will be a runtime exception).
Can anybody tell me why it won't compile when Apple is a final class? What's going on behind the scene with the compiler here? Thanks!

senore100 wrote:
Thanks for all your reply. Well, actually the compiler should know that the actual object is a Citrus. No, it shouldn't. It doesn't become a Citrus obejct until runtime. The compiler only looks at the reference type on the left side of the =, not what's happening on the right side.
What if instead of new, it was Squeezeable sq = squeezableFactory.createSqueezeable(); It could return any class that implements Squeezeable.
Now, you could try to argue that it should at least do it for new, when it knows what the class will be. But there's really no point for that, and it would just complicate the language by adding special cases.

Similar Messages

  • Overidding a method defined in a Final class via an interface.

    Hi,
    Is it possible to override methods of a final class
    which has implemented methods of an interface.
    interface A{
         void method1();     
    public final class FinalityA implements A{
         public void method1(){
              // Code
    }Now,I would like to override the functionality of
    method1() defined in class FinalityA.
    I cannot subclass FinalityA as this class is final.
    // Invalid.
    class Myclass extends FinalityA{
    }Is it possible to override the functionality defined in method1()
    Please suggest

    You can do:
    public class MyClass implements A {
       private final FinalityA _wrapee;
       public MyClass(FinalityA wrapped) {
           _wrapee = wrapped;
      public void method1() {
           .. do some special processing
          _wrapee.method1();
           .. do some more stuff
            }If you want to get really clever you can do stuff with java.lang.reflect.Proxy that allows you to automatically pass on calls to interface methods (this kind of thing is increasingly used for stuff like transaction management).
    What you can't do is to fiddle with the code of the method if called from a reference to FinalityA rather than a reference to the interface. The whole point of final classes and methods is to prevent that.

  • Class vs. interface casting

    This is a long read. But since I wrote test code and think its a ligit question:
    After compiling, if I move a *.class file to a different directory, casting with a class (but not an interface) fails. Please look at my test code to understand what I am trying to say:
    public class Main {
      public static void main(String[] args) {
        try {
          MyClassLoader mcL = new MyClassLoader();
          Class classA = mcL.loadClass("whatever");
          I inst = (I) classA.newInstance(); // <-- good
          // ClassA inst = (ClassA) classA.newInstance(); <-- bad
          inst.foo();
        } catch(Exception e) { e.printStackTrace() ; }
          public static class MyClassLoader extends ClassLoader {
            protected Class<?> findClass(String s) throws ClassNotFoundException, ClassFormatError {
              try {
                InputStream in = new FileInputStream(new File("/etc/ClassA.class"));
                int i = in.available();
                byte[] buf = new byte;
    in.read(buf, 0, buf.length);
    return defineClass(buf, 0, buf.length);
    } catch(Exception e) {e.printStackTrace(); }
    return null;
    public class ClassA implements I {
    public void foo() { println("ClassA::foo-->ok"); }
    public interface I { public void foo(); }
    C:\dev\dir *java
      Main.java
      ClassA.java
      I.java
    C:\dev\javac *java
    C:\dev\move ClassA.class \etc
    C:\dev\java Main
    using interface cast = no problem
    using a class to cast = _fail_
    Exception in thread "main" java.lang.NoClassDefFoundError: ClassA
         at Main.main(Main.java:18)
    Caused by: java.lang.ClassNotFoundException: ClassA
         at java.net.URLClassLoader$1.run(Unknown Source)
         at java.security.AccessController.doPrivileged(Native Method)
         at java.net.URLClassLoader.findClass(Unknown Source)
         at java.lang.ClassLoader.loadClass(Unknown Source)
         at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
         at java.lang.ClassLoader.loadClass(Unknown Source)
         at java.lang.ClassLoader.loadClassInternal(Unknown Source)
         ... 1 more
    I will only cast with interfaces, but wondering what is going on with why casting with a class fails.
    _note_: to test that casting with classes works at all I wrote this code snippet:
    Class c = Thread.class;
    Class[] noArg = new Class[0];
    Constructor constr =  c.getConstructor(noArg);
    Thread t = (Thread) constr.newInstance(new Object[0]);
    println("-->" + t.getId());
    I hope this proves casting with classes is possible.So sometimes casting with a class is ok, sometimes not. I wonder why.
    thanks.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

    ejp wrote:
    After compiling, if I move a *.class file to a different directoryYou can't do that. The .class file has to be in whatever directory is indicated by its package statement. Two classes with the same name in different packages are different, and a .class file in the wrong directory will cause NoClassDefFoundErrors.can i ask a follow-up?
    To be painfully clear, when I hit this line:
    ClassA inst = (ClassA) classA.newInstance();The type-checking tripped me up. I had a valid "ClassA" object. Object creation had been internalized to my class loader. However, when the jvm did a type-check, it needed to load the ClassA.class file, and it had been removed. So, my casting with a class failed only because of type-checking?

  • Why not compile error on "incompatible interface cast"?

    simeple code here
    class IncompInterfaceTest {
    void doTest() {
    ClassB b = new ClassB();
    InterfaceA a = (InterfaceA)b;
    interface InterfaceA{}
    class ClassB{}
    javac issues "ClassCastException" on runtime rather than compile
    error.
    as i know incompatible type casting may be caught at runtime and
    compiler shows the error.
    but why compiler doesn't do it's job for interfaces? it's just so
    clear to be compile error to me.
    ps. in a case ClassB is final class, compiler issues a error.
    (a thread I started in google groups)
    http://groups.google.co.kr/group/comp.lang.java.programmer/browse_thread/thread/c9c12a8864672436?hl=ko#

    sun9h0st wrote:
    thanks for reply.
    I think i might know something wrong about class, object concept, so I wish you tell me more about it.
    As I though the code below means
    ClassB b = new ClassC();'b' can be an Object of ClassB as a subclass of ClassC.
    'b' IS an Object of ClassC.b is not an object.
    b is a variable that can point to an instance of ClassB or to an instance of any subclass of ClassB.
    >
    so
    b instanceof ClassB == true // as it can be
    b instanceof ClassC == true // as it is
    If b is not null, the first line will always be true.
    If b points to a ClassC or a subclass, the second one will be true.
    It means actual Object(something behind 'b' pointing, i don't know what i call it) is from ClassC to me. (somewhat like c pointer,
    'b' is a bowl that called Object and actuall instance is refered by 'b')No idea what you're saying here.
    if b IS an Object of ClassB
    shouldn't "b instanceof ClassC" is false?If we have C extends B, then...
    B b1 = new B();
    B b2 = new C();
    b1 instanceof B // true
    b1 instanceof C // false
    b2 instanceof B // true
    b2 instanceof C // true
    I Think compiler should be known that instance 'b' hold. No, it doesn't, and it's good that it doesn't, as it keeps the language simpler and more consistent.
    Also, b doesn't hold an instance. It holds a reference to an instance.

  • Generic interface in abstract super class

    hello java folks!
    i have a weird problem with a generics implementation of an interface which is implemented in an abstract class.
    if i extend from this abstract class and try to override the method i get this compiler error:
    cannot directly invoke abstract method...
    but in my abstract super class this method is not implemented as abstract!
    do i have an error in my understanding how to work with generics or is this a bug in javac?
    (note: the message is trown by the eclipse ide, but i think it has someting to do with javac...)
    thanks for every hint!
    greetings daniel
    examples:
    public interface MyInterface <T extends Object> {
       public String testMe(T t);
    public abstract class AbstractSuperClass<T extends AbstractSuperClass> implements MyInterface<T> {
       public String testMe(T o) {
          // do something with o...
          // now we have a String str
          return str;
    public final class SubClass extends AbstractSuperClass<SubClass> {
       @Override
       public String testMe(SubClass o)
          return super.testMe(o);
    }

    Hi Wachtda,
    Firstly, T extends Object is redundant as all classes implicitly extend the Object class.
    Therefore :
    public interface MyInterface <T> {
       public String testMe(T t);
    }Secondly, abstract classes may have both abstract and non-abstract instance methods. Also, two methods, one abstract and one non-abstract, must have a different signature.
    The following example will give a compile error because the methods share the same signature :
    abstract class Test {
         public void sayHello() {
              System.out.println("Hello");
         abstract public void sayHello();
    }Therefore, to make an interface method as abstract would simply block the possibility of implementing it.
    BTW, you can do this :
    abstract class Test {
         public void sayHello() {
              System.out.println("Hello");
         abstract public void sayHello(String name);
    }Finally, there's no bug in javac.

  • How do I redefine a Method of a Final Class?

    Hi,
    Is it possible to redefine a method of a final class and if so, can someone please give me a brief example of that technique?
    Thank you very much!
    Andy

    Hi,
    Please find the example.
    Program Description :      Interface I1 contains two methods : M1 and M2.
    I1 is included and incorporated in class : C1 with M2 as a final method. Both the methods are implemented in class C1.
    Class C2 is a subclass of class C1. It redefines method : I1M1 and re-implements it, but it does not do that for I1M2 as that is declared as final method.
    In the START-OF-SELECTION block, object OREF1 is created from class C1 and OREF2 from class C2 and both the methods M1 and M2 are called using both the objects.
    Example:
    report ytest .
    interface i1 .
      methods : m1 ,
                m2 .
    endinterface.
    class c1 definition.
      public section.
       interfaces : I1 final methods m2 .
    endclass.
    class c1 implementation.
      method i1~m1.
       write:/5 'I am m1 in c1'.
      endmethod.
      method i1~m2.
       write:/5 'I am m2 in c1'.
      endmethod.
    endclass.
    class c2 definition inheriting from c1.
      public section.
       methods : i1~m1 redefinition .
    endclass.
    class c2 implementation.
      method : i1~m1.
       write:/5 'I am m1 in c2'.
      endmethod.
    endclass.
    start-of-selection.
      data : oref1 type ref to c1,
             oref2 type ref to c2 .
       create object : oref1 , oref2.
       call method  : oref1->i1~m1 , u201C Output : I am m1 in c1
                      oref2->i1~m1 , u201C Output : I am m1 in c2
                      oref1->i1~m2 , u201C Output : I am m2 in c1
                      oref2->i1~m2 . u201C Output : I am m2 in c1
    Output :      I am m1 in c1 
    I am m1 in c2 
    I am m2 in c1 
    I am m2 in c1 
    Thanks,
    Anitha

  • TextLayout not Serializable AND final class - can't extend and save objects

    As the title reads, I am using a TextLayout object in a class called Foo.
    I want to be able to serialize Foo and save it to the HD. This can't be done because TextLayout does not implement Serializable.
    So I tried to create a new class that extended the TextLayout class. This wasn't possible because TextLayout is defined as:
    public final class TextLayout
    extends Object
    implements Cloneable
    Basically, I have no clue how to be able to save my Foo class to the HD since I can't serialize the TextLayout object inside the Foo class. I would really appreciate help, because it is quite important that this works.
    Thanks.

    Siniz wrote:
    I have never dabbled with with transient variables, but I just read up on it and understand what you are getting at. Is this really the only way?
    The reason why I need to use TextLayout is because I need the bounding box of the text. I see no other way to get a bounding box around text than using TextLayout.That's a question for the swing/awt forums.
    I am also not entirely sure what you mean when you say I should write my own writeObject and readObject methods? You are saying I should entirely ditch the ObjectOutputStream methods?No, you implement those methods on your class in order to customize serialization. Please see the javadocs on the Serializable interface.

  • Type param in interface referring to concrete class

    I want to declare a method in an interface that takes a type parameter that represents the concrete implementing subclass. I can live with something less than that, though I would like to avoid casting as much as possible...
    Here's my attempt at a simplified (though contrived) example:
    public interface Collectable {
        Collection<Collectable> collectMe();
    public class StampCollection implements Collectable<Stamp> {
        // Super-specialized collection for holding stamps
    public class Stamp implements Collectable {
        public Collection<Stamp> collectMe() {
            return new StampCollection(this);
    }This doesn't work because StampCollection is deemed to be incompatible with Collection<Collectable>. I'm assuming this is because the type parameter for the interface that StampCollection implements is Stamp, which is more specific than Collectable. Is that right? What are my options for fixing this (with minimal casting).

    Also, I see from some other reading that there seems to be some precendent for doing things this way (having a class implement an interface parameterized by the class itself). For example, on the Angelika Langer Java Generic FAQ linked to from the notice on this forum, she gives an example of
        class Pair<A extends Comparable<A> & Cloneable ,
                   B extends Comparable<B> & Cloneable >
          implements Comparable<Pair<A,B>>, Cloneable { ... } Which is a fairly complicated example for our purposes, but does seem to use the same strategy.
    Is this a common idiom?
    Michael

  • When to use interface and when Abstract Class?

    In a recent interview I was asked "When to use interface and when Abstract Class?" Explain with an example.
    Also in what situations a class should be made final(real time example)

    Interface is a pure contract with no implementation. Typically used to define a communication contract between two different sub-systems. Example EJB home interface. This also allows the design to change as long as the contract is met.
    Abstract class is when there exists a lot of common functionality already known and can be coded. However, a few unknowns exists (typically about data) for which abstract methods need to be defined and implemented by the sub class.
    Example: Consider a workflow engine. A great example for abstract class. The workflow process has lot of common code that is independent of the workflow type (vendor flow, contract flow, payment flow etc). However, certain decisions on the route to take will depend on value of data being submitted. So the base class will define a abstract Data getData() method and proceed assuming data will come. The implementing subclass will provide the actual logic for getting the data.
    Also see the "Template" design pattern.
    Note: To some extent the common code design drives the behavior of the abstract methods. So if the design changes then so "might" the behavior expected from the abstract methods.

  • Weblogic 10.3.2 EJB3 Local Interface in POJO/Helper classes

    Hi,
    I have a jar file containing all EJB's in application & some Helper classes. I want to access Local interfaces of EJBs in those helper classes. Is there any way I can do it? I've gone through Maxence Button & Jay SenSharma 's blogs about accessing Local interface. but it doesn't help. May be these two guys can help me more here.. My requirement is very simple. Just to access local interface in POJO/Helper classes that are in same JAR file as EJB's. I can't get reference with @EJB class level annotation as Helper classes are called independently from MBean services.. not from any EJB or Servlert.
    Please if anyone can tell me how do I get reference of local interfaces, that would be really good.
    my environment is
    Weblogic 10.3.2
    EJB3
    Regards,
    Prasad

    Hi,
    Just check ...If you want something like mentioned in the below Link with a complete Example:
    [http://jaysensharma.wordpress.com/2009/08/16/weblogic-10-3-ejb3-local-lookup-sample/|http://jaysensharma.wordpress.com/2009/08/16/weblogic-10-3-ejb3-local-lookup-sample/]
    Regards
    Jay SenSharma

  • Why class builder allows to develop abstract final class ? What is the use of such class in ABAP?

    I am new to ABAP. I tried creating abstract class and found that class builder allows development of abstract final class. What is the use of such class in ABAP?

    Hi,
    Does not compile:
    This one do:
    Inheritance:
    Regards.

  • Reading the Interfaces name which the class is implementing in a COM dll is implementing.

    Hi All,
    I'm using .NET Reflection to read a COM dll. I'm able to fetch the classes that are present in the dll. But I would like to know interface name which this class is implementing.
    For a .NET dll we can know the name of class's implementing interface name using the <classname>.BaseType.Name property.
    How can I know the interface name which this class is implementing (if any).
    Please let me know how to do this for a COM dll.
    Thanks in advance,Satish
    Thanks, Satish Bommideni "Success usually comes to those who are too busy to be looking for it."

    Hi,
    Thanks for the reply.
    I'm reading the COM assembly using the methods available in oleaut32.dll.
    Also I've imported the namespaces
    System.Runtime.InteropServices.ComTypes;
    System.Runtime.InteropServices;
    to use its respective methods and thus I'm able to read it's classes.But donot know what property to check for this class's interface.
    Kindly let me know if you need any further information.
    Thanks, Satish Bommideni "Success usually comes to those who are too busy to be looking for it."

  • Interface Mapping Object - No class definition found

    Hi
    I have created a simple Interface Mapping in the Integration Repo. When i try to TEST the interface mapping i get class not found errors.See the stacktrace below.
    LinkageError at JavaMapping.load(): Could not load class: com/sap/xi/tf/_PO_MAPPING_
      - java.lang.NoClassDefFoundError: Illegal name: com/sap/xi/tf/_PO_MAPPING_
    Looks like some standard sap packages are missing from the CLASSPATH. Anyidea where it has to be specified ?
    PO_MAPPING is the message mapping object i have created and the test is successful for this object.However when i reference it in Interface Mapping , i get the above errors.
    I suppose XI generates Java Code when i create these objects and the mappings.Any idea where the JVM seems to reference these packages and How to rectify it ?
    Thanks
    Saravana

    Hi,
    Please check whether you have applied note 755302.
    - Sreekanth

  • Java.lang.VerifyError: Cannot inherit from final class

    Hi i am trying to call a crystal report from jsp but i am getting this error
    error:-
    org.apache.jasper.JasperException: Cannot inherit from final class
         org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:460)
         org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:355)
         org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:329)
         org.apache.jasper.servlet.JspServlet.service(JspServlet.java:265)
         javax.servlet.http.HttpServlet.service(HttpServlet.java:803)
    root cause
    javax.servlet.ServletException: Cannot inherit from final class
         org.apache.jasper.runtime.PageContextImpl.doHandlePageException(PageContextImpl.java:841)
         org.apache.jasper.runtime.PageContextImpl.handlePageException(PageContextImpl.java:774)
         org.apache.jsp._1_jsp._jspService(_1_jsp.java:95)
         org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:98)
         javax.servlet.http.HttpServlet.service(HttpServlet.java:803)
         org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:331)
         org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:329)
         org.apache.jasper.servlet.JspServlet.service(JspServlet.java:265)
         javax.servlet.http.HttpServlet.service(HttpServlet.java:803)
    root cause
    java.lang.VerifyError: Cannot inherit from final class
         java.lang.ClassLoader.defineClass1(Native Method)
         java.lang.ClassLoader.defineClass(Unknown Source)
         java.security.SecureClassLoader.defineClass(Unknown Source)
         org.apache.catalina.loader.WebappClassLoader.findClassInternal(WebappClassLoader.java:1853)
         org.apache.catalina.loader.WebappClassLoader.findClass(WebappClassLoader.java:875)
         org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1330)
         org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1209)
         java.lang.ClassLoader.loadClassInternal(Unknown Source)
         com.crystaldecisions.reports.sdk.ReportClientDocument.open(Unknown Source)
         org.apache.jsp._1_jsp._jspService(_1_jsp.java:64)
         org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:98)
         javax.servlet.http.HttpServlet.service(HttpServlet.java:803)
         org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:331)
         org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:329)
         org.apache.jasper.servlet.JspServlet.service(JspServlet.java:265)
         javax.servlet.http.HttpServlet.service(HttpServlet.java:803)
    my jsp is
    <%@ page import="com.crystaldecisions.report.web.viewer.*" %>
    <%@ page import="com.crystaldecisions.sdk.occa.report.data.*"  %>
    <%@ page import="com.crystaldecisions.reports.sdk.ReportClientDocument" %>
    <%
        Object reportSource = session.getAttribute("reportSource");
        if (reportSource == null)
           String report = "report.rpt";
           ReportClientDocument reportClientDoc = new ReportClientDocument();
           reportClientDoc.open( "report.rpt", 0);
           reportSource = reportClientDoc.getReportSource();
           session.setAttribute("reportSource", reportSource);
        CrystalReportViewer viewer = new CrystalReportViewer();
        viewer.setReportSource(reportSource);
           viewer.setEnableLogonPrompt(false); 
        viewer.setOwnPage(true);
        viewer.processHttpRequest(request, response, getServletConfig().getServletContext(), null);
    %>
    and in my WEB-INF/lib i included jar files namely
    Concurrent.jar,CrystalCharting.jar,CrystalCommon.jar,CrystalContentModels.jar,CrystalExporters.jar,CrystalExportingBase.jar,CrystalFormulas.jar,CrystalQueryEngine.jar,CrystalReportEngine.jar,CrystalReportingCommon.jar,icu4j.jar,jrcerom.jar,keycodeDecoder.jar,log4j.jar,MetafileRenderer.jar,rasapp.jar,rascore.jar,rpoifs.jar,serialization.jar,URIUtil.jar,xml-apis.jar,xbean.jar,xercesImpl.jar,webreporting.jar,webreporting-jsf.jar
    please help me

    You can't inherit from a final class. 
    So - are you trying to inherit from a final class?
    Sincerely,
    Ted Ueda

  • FPGA Interface Cast question

    I'm playing with a 5644 VST and the VST Streaming template.  On the FPGA VI I added some code, then added an indicator to the FPGA VI front panel and compiled.  Running the FPGA VI in interactive execution mode, the indicator works well.  On the host end, though, I can't seem to access the new indicator with a Read/Write control. 
    Coming out of the Open FPGA VI Reference I can see the indicator on the wire, but in the Dynamic FPGA Interface Cast function it's getting stripped out of the refnum somehow.  If I connect a Read/Write control directly to the output of the Open Reference function I can access the indicator just fine.
    Any idea what I'm doing wrong?
    Thanks.
    Solved!
    Go to Solution.

    Have you re-configured your FPGA VI reference interface with the new bitfile?  The dynamic interface cast defines the output wire as having all the methods and indicators described by the type wire connected.  You can right-click on the type constant and select "Configure FPGA VI Reference...".  In the pop-up that follows, choose "Import from bitfile..." and then select the new bitfile that you've built.
    You'll need to update the fpga reference type in the "Device Session.ctl" type def as well.  This is the type that you'll be able to access throughout the project.

Maybe you are looking for

  • Issues with 32GB micro SD with Windows Phone 8 and Lumia 810

    I bought 32 GB micro SDHC card (Sandisk) that causes issues such as: (1) tap Settings - then blank screen - then go back to Home (2) when shutting down WP8, it says "goodbye" forever and it does not go away. I have to detach the battery. (3) Occasion

  • Ipad GPS question

    Does the ipad(wifi) has GPS?

  • PS CS4 on Vista x64 hangs when opening image...

    I've checked the forums and cant find anything quite like this... I've just installed (and updated) PS CS4 on a Vista x64 system - PS opens and seems to run just fine until I go to open an image (any image) - the image comes up but stays fuzzy and th

  • Monitor blacks out while using

    I have a Norwood Micro flat screen monitor. I have had recent problems with it going black while working. If I turn off the monitor and then turn it back on it works fine for awhile and then I continue this little game with the monitor throughout. Ne

  • "Buffer table not upto date" while creating Service entry via BAPI

    Hi All, I am facing the same issue while creating and accepting a service entry sheet via BAPI_ENTRYSHEET_CREATE in a report . I get a pop up message S001 (Buffer table not upto date) in ML81N. Though, it is not an error message it delays the further