Can we type cast class into interface?

Hello all,
Can we type cast class into interface?
If it can ,pls explain me in which suituation can we do?

You don't need to explicitly typecast a class to an interface, if the class is implementing the interface.
Example: List list = new ArrayList();    // Cast not required.And search on Google first. I'm sure this question would be answered by the lamest of tutorials.

Similar Messages

  • Casting Class to Interface..??

    Hi,
    need some help here, I have a method that returns an interface type and am trying to cast the returned interface to the class which implements it..However I'm getting a classcastexception when I attempt this and have no idea why..
    Any ideas?

    need some help here, I have a method that returns an
    interface type and am trying to cast the returned
    interface to the class which implements it..However
    I'm getting a classcastexception when I attempt this
    and have no idea why..
    Any ideas?Obvously you are mistaken about the actual implementation class that is used in this case. Casting an interface to the class that implements it is almost always a bad idea and it is always a very ugly way to do things. Why do you need to do this?
    To get the actual tyoe being used (you should already know because it is the class stated in the exception) call getClass() on the returned instance.

  • How can I split a class into 2 files?

    I converted a C++ program to Java recently and it works fine, but I ran into a problem.
    One file is very large and I need to add more functionality. Unlike with C++ where you can just put new functions in another file, I don't see a way to do it in Java.
    I made another file, and therefore another class, but the compiler complains that it can't call a static function from non-static context. (I did not declare it static so I guess it's assuming it) But I understand why. So I made the new class "extend" the old one so "this" would exist but that doesn't work -- Is it because the new class is a subclass of the original class?
    There must be a way to do this. But I don't see what is likely obvious. HELP! And thanks.

    JavaIsBetterThanCPP wrote:
    There must be a way to do this. But I don't see what is likely obvious. HELP! And thanks.Unfortunately Java has no concept of "partial classes" like C# has. Generally, however, a class that is large enough to split up into separate files is either one class that should be modularized further into separate classes, or it already is modularized and all that code is the result of many inner classes. What some people do is promote those inner classes to top-level members in their own file, and mark them as package-private. Using a package you can basically have two classes that know everything about each other and have full access to each other.
    But personally, and until I see justification otherwise, semantics in Java being unbreakingly tied to a certain file structure and naming is the most bonehead and, frankly, non-Java thing about Java.
    There's probably a pre-processor out there that will let you split a class into multiple files and will combine them into a single source file just-in-time to pass to the compiler.

  • Can I put a class into a jsp??

    I want to put this class into a jsp.. and reference it when I need it... can i just dumped it into a jsp... or do I have to do anything specific to it...
    public class areaformat {
         public synchronized static String replace(String str, char oldchar, String newstr)     {
              StringBuffer sb = new StringBuffer(str);
              int len = sb.length();
              try     {
                   for (int i=0; i<=len; i++)     {
                        if (sb.charAt(i) == oldchar)     {
                             sb = sb.replace(i, i, newstr);
                             sb.deleteCharAt(i + newstr.length());
                             i = i + newstr.length() - 1;
              }catch(StringIndexOutOfBoundsException sioobe)     {
                   if (len == 1 && str.equals("'")) {
                        sb = new StringBuffer(newstr);
              return sb.toString();
    Thx RIch

    No, you can't. You can put only the function in the beginning of your jsp file like:
    <%!
    public void myFunction(...){
    %>
    So, you can use myFunction wherever you want in the page.
    The other method is to compile your class in a file called "javac className.java" and the put the .class file generated in your WEB-INF/classes folder of your web-container.

  • I can't type some characters into firefox for android with physical keypad

    I am using an android device which is a Sharp 007sh that come with a physical 9 number keypad like those old nokia phone, running stock android 2.3 and using an input method modifier named as cedIME that can be downloaded from google play.
    and with this setup, to type character into the phone, it is necessary to press multiple time a ley to get a character. For instance, to type a 'z' into the phone, you'll have to press the '9' button four time, so it change from w to x to y and finally z. However, in Firefox, when doing so to url bar and text area, pressing the first time the button '9' would create a highlighted character 'w', then another press would change the character from 'w' to 'x', but then it no longer being highlighted and the input cursor move to the right of it. As such, pressing the button '9' for the third time would not result in the intended change from 'x' to 'y', instead it would simply add a new character 'w' after the previous character 'x', and pressing the fourth time would thus result in another 'x', which make the output become 'xx', instead of the intended 'z' character. This problem is so far unseen on any other apps.

    Hi Lilybri,
    I still have this problem with the accents in AC and I've just found that problem comes from the double-type characters (like the accents in Spanish).
    http://helpx.adobe.com/captivate/kb/double-byte-characters-cannot-input.html
    BTW, I got no answer from Adobe and i'ts been more than 2 months since I registered the bug...
    Best regards!

  • Can you code 2 classes into one source file?

    Can you have 2 classes coded in one source file? If so, do you end up with 2 .class files after the compile?

    yes you can code 2 classes in one source file. I
    believe that you have to reference one class is an
    "object" class of the class under which you save the
    file as.
    Example:
    File name is A.java
    class A{
    class B{
    When you want to refer to class B, you have to say
    A.B ( eg: A.B ab = new A.B() ). The class file(s)
    will be A.class and A$B.class.
    This is what I recall at best at the time. good luckI presume you mean when one is an inner class? Otherwise:
    public class one {
      one() { System.out.println("one");
      public static void main( String[] argv ) {
        new one();
        new two();
    class two {
      two() { System.out.println("two");
    }Will work fine, and will create one.class and two.class. But that does not mean it is a good idea to do it ;o)

  • Can I type different text into insances of the same symbol?

    Example:
    If I have a A-B-C poster in which I want each letter to be in a rectangle-shape symbol, is there a way that I could have, say, a blank text-box in the symbol, and then type a different letter into each symbol?

    When it comes to symbols you would need to create 26 symbols for each letter of the alphabet, so symbols are not the way to go.
    If all you need is a rectangle around each letter
    Set a letter, set fill to none
    Switch to pointer tool
    Appearance palette flyout  >> add new fill, set color you like for type
    Appearance palette flyout  >> add new fill, select bottom fill in appearance panel, set color you want for rectangle
    Effect >> convert shape to rectangle (turn on preview, enter settings similar to mine)
    Effect >> path >> Outline object (optional - this helps center the type in your container by getting rid of the extra space built into a font)
    Now you can option drag copies and change the letter, and the rectangle will stay same size if you chose absolute, or resize if you chose relative)

  • Can't add my class into example project

    my class is in the workspace the project
    tree with the same package(in code first
    line is "package xxxx;"). When I instatiat it, it is not red color, it always occure
    compile error: idendifier xxxx not found in the class(other class in the same pakege) xxxx.
    do I need redeploy the project? but it did not compile and build.

    Fred,
    I am not sure about the details of the
    problem you have explained below.
    But here are some guidelines that may
    help you figure out what you are doing wrong.
    1. A Workspace can contain one or more
    projects - (never any Java class files)
    2. A Project can contain one or more
    Java class files.
    3. A project has a default "Source Root"
    directory and this is used as the Root
    for the source files.
    4. Java requires public class names be the
    same as the file name
    (e.g. Class CellPhone must be saved in file
    CellPhone.java)
    5. Java requires the package name correspond
    to directory path
    (e.g. Pachage name of Acme.Video.Preview
    must be stored in <Source Root>\Acme\Video\Preview )
    6. The actual path to a file is the
    Root Source plus the package name plus the
    class name.java.
    (example: Source Root = C:\JDeveloper
    Package Name = MyCompany.Report.Util
    Class Name = GeneratePDF
    will need to be stored in:
    C:\JDeveloper\MyCompany\Report\Util\GeneratePDF.java
    As for various Identifiers not being found,
    it is simply telling you that your project's
    list of included libraries does not include
    the given identifier.
    If it is valid, then add the appropriate
    library to the project's library list.
    See Menu: Project | Project Properties.../ Add...
    I hope this helps,
    John@Oracle JDeveloper Team http://technet.oracle.com
    null

  • Can't type or past into Applescript Editor window?

    Some of us are having problems with typing/inserting text into the Applescript editor window. The problem and attempts to fix it were discussed at: http://discussions.apple.com/thread.jspa?threadID=2133365
    I am posting here to see if someone here might be able to help us.

    New account does not work. Safe boot does. Removing the .plist does not work. When the editor is restarted it does not create a new .plist.
    I tried to find the .plist in safe boot and it is not there. I went back into time machine and pulled out an older .plist and placed it in the preferences folder, and that did not fix it.

  • Suddenly I can't type my password into my ipad to unlock it. What has happened?

    Went to bed. Got up and now the keyboard comes up but won't do anything.  Could it be that one of the kids has tried to enter my password wrongly or is there another explanation?

    Hi 60mic,
    Try resetting your iPad: Hold down the Home and Power buttons at the same time and continue to hold them down until the Silver Apple appears (no data will be lost). Once the Home screen redisplays, see if your keyboard is responsive.
    Cheers,
    GB

  • ClassCastException - While type casting Home object after EJB JNDI Lookup

    Sun One Application Server throws a ClassCastException when I try to type cast Home object to it's respective interface type.
    Here is the code ---
    ==============================================
    Object obj = PortableRemoteObject.narrow( context.lookup( jndiName ), homeClass);
    System.out.println("Remote Object - obj : "+obj);
    if (obj != null) {
       System.out.println("obj.getClass().getName() : "+obj.getClass().getName());
       System.out.println("obj.getClass().getSuperclass() : "+obj.getClass().getSuperclass());
       Class[] interfaces = obj.getClass().getInterfaces();
       if (interfaces != null) {
          for (int count = 0; count < interfaces.length; count++) {
             System.out.println("interfaces[ " + count + " ].getName() : " + interfaces[ count ].getName());
    }==============================================
    The class name is dislpayed as the Stub class name.
    While displaying the interfaces, the Home Interface name is displayed.
    But later when I try to type cast it into Home Interface type, it throws a ClassCastException.
    Can somebody please check this?

    Please post the stack trace. Also, take a look at our EJB FAQ to make sure you're doing the
    recommended lookup :
    https://glassfish.dev.java.net/javaee5/ejb/EJB_FAQ.html

  • Dynamic [Runtime] type casting in Java

    Hello,
    This is my requirement.
    I have a method that takes class name as a parameter.
    Ex:
    Object myMethod(String classname){
    Object xyz = getObject(); //userdefine method which returns some object
    /*<b>I need to typecast above object with the class name passed as the method parameter</b>*/
    /*<b>How can i type cast this object</b>*/
    Object obj = (classname) xyz;
    return obj;
    In the above example, how can i dynamically typecast the object with class whose name is passed as the method parameter?

    Hello,
    This is my requirement.
    I have a method that takes class name as a parameter.
    Ex:
    Object myMethod(String classname){
    Object xyz = getObject(); //userdefine method which
    returns some object
    /*<b>I need to typecast above object with the class
    name passed as the method parameter</b>*/
    /*<b>How can i type cast this object</b>*/
    Object obj = (classname) xyz;
    return obj;
    In the above example, how can i dynamically typecast
    the object with class whose name is passed as the
    method parameter?Perhaps a little more background on the project (what you are trying to do) will help the experts here answer?
    /*with a class that takes a noarg constructor*/
    public Object getObject(String classname) throws Exception
      //might want to get a bit more specific with which exceptions it will throw
      return Class.forName(classname).newInstance();
    }Do I think this sometimes is indicative (perhaps even more often than not), of a possible design flaw? Yes..
    It gets a little trickier if you have constructors (you have to create a Class object representing the string with the .forName(..) ..and then use some reflection to determine constructors and then a bit of logic to determine which of those to use...)
    ~Dave

  • About Classes and Interfaces

    How can we define the classes and interfaces in an interview can u give me any realtime example for this

    How can we define the classes and interfaces in an
    interviewThe easiest explanation probably is to say that an interface in Java is a special class, namely a totally abstract one, that has been given a separate name.
    Classes and interfaces (because they're classes in disguise) both constitute types, meaning that variables can be declared of them. The difference is that a class can carry implementation whereas an interface cannot (because it's totally abstract).
    Java has single inheritance of implementation which means the the inheritance of classes is restricted to exactly one while you can inherit as many interfaces you like.

  • Type casting an array as element

    Hello all,
    I'm relatively new to labVIEW and I would like your help with something.
    Let us say I have an array of two I16 elements. I would like to type cast it into one single U32 element. In C, I could simple read it as a U32 or use pointers to get away with it, but I don't seem to be able to find a way to do it here.
    Cheers,
    S

    You can, in fact, use the Type Cast function to do this. Alternately, index out the two array elements, then use Join Numbers to merge them.

  • FPGA Type Casting

    Hey, all!
    I'm transferring some execution parameters from a host to an FPGA target using DMA FIFOs.  I'm looking into possibly reducing overhead by packing my data a bit more purposefully.  For example, two related I32s being packed into a single 64-bit and split up on the FPGA side.  However, when I split the data apart, the data becomes U32.  Now I have no way to accurately perform any math on the numbers, as I've lost the sign.  There's no way to type cast back into a signed integer once on the FPGA target that I can see.  Has anyone else solved this, or am I relegated to just using two I32 DMA FIFOs?
    Dan M.
    Solved!
    Go to Solution.

    You can also use the Number to Boolean Array, Build Array, and Boolean Array to Number (right click this one to set your output data type) and do the packing explictly yourself:
    These functions consume no logic resources on the FPGA because they are purely wiring operations!

Maybe you are looking for

  • Java card confusing Issues!!!!!!! java card architecture, advantage!!!!!

    QUESTION -1 As I know about architecture of any application is -                 //normal java software                          java card                                  java card                   //  1                                             

  • How do I determine what version of Firefox I have and where do I go for updates/

    Yahoo is 'suggesting' I upgrade to Firefox''' 8'''. How do I determine which version I currently have (there is not 'Internet Options' under Tools) and where to I go to find the updates withough depending on Yahoo?

  • How to calculate Average time from a date field

    Hi All, I have a date type field in my table . I want to calculate average time for a given country in a select query. Date has to be exculded. Only time has to be taken into consideration. Kindly help me. Sample data india 25-JUN-09 08:12:45 india 2

  • Importing Photoshop or Illustrator to Keynote '09 and export to Qucktime

    Hello, I have a slideshow project I am working on for a client 1280x720 for export to Quicktime H.264. I have placed a logo from photoshop for the intro with text created in Keynote. When exported to Quicktime H.264 1280x720 the playback is great but

  • Restoring play counts & original data after reformat

    I reformatted my computer and followed the steps online to restore my library, by importing my iTunes Library xml file from the desktop (and then dragging My Music into the iTunes window). Although I was able to obtain all of my original playlists, n