Declaring top level classes instead of subclasses

I seem to have misunderstood something very basic.
It's always better, where possible, to declare the top-level class instead of the sub-class, right?
Ok, then why do I have the following problem?
I declare, from the JavaMail API the following:
Message theMessage = new MimeMessage(session);instead of declaring directly the subclass like this:
MimeMessage theMessage = new MimeMessage(session);but when I use a method which is only found in the MimeMessage class I get a compile error.
[javac] 189.           theMessage.setSubject(subject, "iso8859_1");
[javac] <-------------------------------->
[javac] *** Error: No match was found for method "setSubject(java.lang.String, java.lang.String)".
Have I really misunderstood something so basic?? Surely the compiler knows that theMessage is an instance of MimeMessage??
Any clear explanation to explain why I get this compile error would be gratefully received. I have been faithfully declaring top-level classes instead of subclasses in my code, but if the compiler doesn't let you do so, then what's the point?

Ok, my confusion was started by an article on the
Collection classes which stated that:
Map theMap = new HashMap(); was better
programming practice.
Yep.
But the Map class is an Interface, right? - Whereas
Message is a normal class with subclass MimeMessage.
I think that's where my confusion started.Well, this isn't really a class vs. interface difference. It goes to which class (or interface) is the "highest" (closest to Object) and still has all the public interface you need.
There are cases where you'll declare a variable to be of a base class type like Message.
You just need to get into the habit of separating the left side of the = from the right side. On the left, you put the bare minimum that completely meets your needs. You say, "I need a List" or "I need a Map" or "I need a SortedMap" (a subinterface of Map) or "I need a Message" or "I need a MimeMesage".
Then, on the RHS =, you decide which particular class best implements the public interface that you said you need (by declaring it on the LHS). "For my Map, I'll use a HashMap." "For my Message, I'll use a MimeMessage." "For my MimeMessage, I'll use a MimeMessage".

Similar Messages

  • What is top level class declaration in java?

    What is top level class declaration in java?

    The declaration of a class that's not nested inside any other class.

  • What makes a class a "top-level" class?

    1.
    2.    public static int getThis() {
    3.      int x = 4;
    4.      int y = 5 * x;
    5.      return y;
    6.    }
    7.  }
    8.
    9.  public class NetGro extends ToNet {
    10.    public static void main(String args[]) {
    11.      int z = getThis();
    12.      System.out.println("Z = " + z);
    13.    }
    14.  }At line 1 of this program, ToNet "can only be declared as public or the default of no modifier" (not private or protected) because it's a "top-level class." What makes ToNet a "top-level class?"

    A class or interface is 'Top-Level' if it is not nested inside another class or interface.
    Otherwise the class would not be visible... Private and Protected for classes and interface only make sense within another class or interface as inner classes or interfaces.
    Hope that helps...

  • Release memory for nested top-level classes

    Hello experts.
    I have a top-level class which consists of several static methods. Inside such a method I create several new instances of a nested top-level class inside my original class. Later I want to release one of these instances i.e. destroy instance and free memory. How can I do that?
    Thanks.

    sure, but I do not see any references to this nested top-level class. With "Releasing" I mean something like directly assigning a NULL value to the nested top-level clas in order to enable GC.
    But as I said there are no references and while monitoring the memory I see that the GC does not collect some memory. (I know that GC is not reliable, but after ten attempts of this scenario the memory allocation is equal the whole time).
    I guess the GC does not work with classes, but the classloader. But how can I control releasing memory in this scenario?
    Any further hints?

  • Top level class ?

    hi,
    i am preparing the sun certified java progammer, there's some questions involving "top level class", i don't understand what is a top level class ? can anyone give me some information about it ? is it a class at the top of a package hierarchie like class Object ????
    thanks for your help

    hi,
    i am preparing the sun certified java progammer,
    there's some questions involving "top level class", i
    don't understand what is a top level class ? can
    anyone give me some information about it ? is it a
    class at the top of a package hierarchie like class
    Object ????No. See
    http://java.sun.com/docs/books/jls/second_edition/html/packages.doc.html#26783
    Jim S.

  • How to create top level classes

    what is the meaning of top level classes. and how to create toplevel classes.

    http://help.adobe.com/en_US/AS2LCR/Flash_10.0/help.html?content=00000188.html

  • Protected top-level classes - what do you think about?

    See http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6310261

    What is subpackage? Is it like below?
    it.is.my.package.*; //the package
    it.is.my.package.subpackage.*; //the subpackage
    Exactly.
    If it is, well, I like the idea. It would improve the
    java. I�ve already had some idea like that. I
    thought: "Why don�t exist relations between packages
    in Java?".Sun claims there is no relationship, but assertions you can enable or disable for the package and all subpackages with one command.
    If you like this idea, please vote for this RFE.

  • Multiple top level package declarations

    The "Programming Adobe ActionScript 3.0" states in chapter 4 "ActionScript Language and Syntax", "Packages and Namespaces", "Creating Packages" that you can declare at the top level of a package multiple variables, functions, and namespaces in addition to a single class as long as only one is declared "public".
    However, in Flash when I declare a public class and any other variable or function either with the "internal" attribute or no attribute, I get this error:
    5006: An ActionScript file can not have more than one externally visible definition: test.function1, test.Test
    The package code is as follows:
    package test
        internal function function1():String
            return "Function1()";
        public class Test
    The same thing happens if I replace the function with an internal variable declaration. According to the manual, any declaration with the "internal" attribute should not be externally visible outside the package. Only the "public" class declaration should be externally visible.
    Can anyone clue me in as to why I get this error?

    That is not the situation described by the quoted manual section that I am trying to recreate.
    It clearly says:
    "In ActionScript 3.0, you use the package statement to declare a package, which means that you can also declare variables, functions, and namespaces at the top level of a package. You can even include executable statements at the top level of a package. If you do declare variables, functions, or namespaces at the top level of a package, the only attributes available at that level are public and internal, and only one package-level declaration per file can use the public attribute, whether that declaration is a class, variable, function, or namespace."
    The data properties and class you have decleared are outside the package within the ActionScript file, and not at the top level of a package. The "public" attribute is not available outside the package at all.
    What I wish to know is why the quoted internal declarations at the top level of the package generate the quoted error.
    However, I am beginning to believe that the documentation is in error and that what it is actually describing IS the situation you just described. When the manual says "top level of the package", it really means "top level of the ActionScript file outside the package", and when it says "the only attributes available at that level are public and internal", it really mans "the only attribute available outside the package declaration is internal. At the top level of the package, only one declaration may be made, it must have the same identifier as the ActionScript file name, and it can have either the public or internal attribute. Code within the same file but outside the package declaration can not access an internal declaration in the package declaration."
    Actually, the whole paragraph would need to be re-written to clarify the issue and to unambiguously distinguish between "top level of a package" and "top level of an ActionScript file outside the package declaration".
    As a concrete example - two ActionScript files:
    MCTest.as is saved in the same directory as MCTest.fla, and the document class of MCTest.fla is set to "MCTest".
    package
        trace("MCTest package code.");
        import flash.display.MovieClip;
        import test.Test;
        public class MCTest
        extends MovieClip
            trace("MCTest class code.");
            function MCTest()
                trace("Created Class MCTest: " + Test.StaticMessage);
    trace("MCTest outside package code");
    Test.as is saved in a sub-directory called "test".
    package test
        trace("test.Test package code");
        public class Test
            public static const StaticMessage:String = "Test: Hello World!";
            trace("test.Test class code");
    var myField:String = "myField";
    function myFunction():String
        return "myFunction";
    trace("test.Test outside package: " + myField + ", " + myFunction() + ", " + test.Test.StaticMessage);
    The resultant trace output is:
    MCTest class code.
    MCTest package code.
    MCTest outside package code
    test.Test class code
    test.Test package code
    test.Test outside package: myField, myFunction, Test: Hello World!
    Created Class MCTest: Test: Hello World!
    It is interesting to note that the package and outside package code are executed AFTER the class code.
    That seems to make more sense. You can only declare one class, variable, function, or namespace at the top level of a package with the same identifier as the file name, public or internal, and you can include executable code. At the top level of the ActionScript file outside the package declaration, you can only declare internal classes, variables, functions, and namespaces, and you can include executable code, none of which are within the package nor have access to any package internal declarations.
    The problem, therefore, would seem to be an incorrect manual. Does anyone actually know if this is accurate and the intended behavior?

  • Issue with having to declare fixed width for my top level floated LI in horizontal menu

    Hi and thanks for taking a look at my problem:
    I am having trouble getting my sub menus to display correctly in IE.
    Originally i didn't declare a fixed width for my top level li and it displayed perfectly in all browsers except IE.
    If i don't declare a fixed width for my floated floated elements, IE treates the top level li as the same width as the ul they contain (which I don't want). So I declared a width for the ul.MenuBarHorizontal li to be 80px, which is close to the minimum width that i want to use for the top level list items. However, in actual fact, the top level list items all have individually declared widths in the classes they are assigned.
    How can i re-write the html or CSS so that the browser, mainly IE, reads the correct widths for the top level ist li??
    Here is a link to the page with the problem
    Thanks in advance if anyone can help me out.

    Hi Beth,
    thanks so much for your repsonse.
    I will take your notes and advice and see if i can apply it to the actual page i was referring to. It seems you were now looking at a completely different page with a different (albeit spry) horizontal menu.
    Again, i truly appreciate your time and advice.
    Thanks!

  • [svn:fx-trunk] 9924: Empty design layers with id' s are now persisted and declared as top level properties.

    Revision: 9924
    Author:   [email protected]
    Date:     2009-09-02 09:11:03 -0700 (Wed, 02 Sep 2009)
    Log Message:
    Empty design layers with id's are now persisted and declared as top level properties.
    QE notes: None
    Doc notes:  None
    Bugs: SDK-22904
    Reviewer: Paul
    Tests run: Checkin
    Is noteworthy for integration: No
    Ticket Links:
        http://bugs.adobe.com/jira/browse/SDK-22904
    Modified Paths:
        flex/sdk/trunk/modules/compiler/src/java/flex2/compiler/mxml/InterfaceCompiler.java
        flex/sdk/trunk/modules/compiler/src/java/flex2/compiler/mxml/analyzer/SyntaxAnalyzer.java
        flex/sdk/trunk/modules/compiler/src/java/flex2/compiler/mxml/builder/DocumentBuilder.java
        flex/sdk/trunk/modules/compiler/src/java/flex2/compiler/mxml/dom/DocumentNode.java
        flex/sdk/trunk/modules/compiler/src/java/flex2/compiler/mxml/rep/MxmlDocument.java

    I seem to have fixed it by putting <div  class="clearfloat"></div> after the navigation bar?

  • Display Icon/Image instead of Role name in top level navigation

    Hi,
    I want to display a image / icon instead of role name for a particular role. Can you please tell me how to achieve this ?
    Thanks,
    VP

    Hi,
    the thread is just for the background image (for all elements).
    if you want to display icons instead of role names, you have to create your custom top level navigation using the
    navigation taglib from SAP. There are lots of examples. make a blog search for Mr "Kannengiesser" from SAP.
    In case you are using already an EHPx in your EP 7.0 the AJAX framework might have this feature.
    Regards,
    Kai

  • How do you make a menu link to child pages instead of just top-level pages?

    I want two menus on my pages - one along the top which links to the top level pages like About, Contact, Services etc. That's easy enough. I also want another menu down the left hand side which links to the sub pages under Services, but I can't find a way to do it. If you make the menu automatic it links to the top level pages. If you make it manual I can't find a way of adding the link to the sub pages I want. Any advice? I'm running the newest version of Muse on a MacBook Air.

    Hi Michael,
    I am afraid that there is no automated way to create a menu for the sub pages. You will need to create a manual menu and then use the hyperlink drop down to link the manual menu items to the pages. Select the menu item and click on the hyperlink drop down and choose the page.
    - Abhishek Maurya

  • [svn:fx-trunk] 11575: Put default style declarations into one class per application or module.

    Revision: 11575
    Author:   [email protected]
    Date:     2009-11-09 11:34:57 -0800 (Mon, 09 Nov 2009)
    Log Message:
    Put default style declarations into one class per application or module.
    Generate all the default styles in one class instead of a class for each style. The name of the style class will be based on the application or module name. An application named ?\226?\128?\156foo?\226?\128?\157 will have a style class named ?\226?\128?\156_foo_Style?\226?\128?\157. The idea is to allow applications to be compiled with different themes and get their owns styles. Currently this is not possible because a global style in both themes will have the same class name, _globalStyle. Whatever class the top-level application loads the sub-applications and modules will have to use the same class because of the flash player first-class-in-wins rule. Now each application and module will have their own style class.
    QE notes: None.
    Doc notes: None.
    Bugs: SDK-22454
    Reviewer: Paul, Pete
    Tests run: checkintests, all mustella tests.
    Is noteworthy for integration: No.
    Ticket Links:
        http://bugs.adobe.com/jira/browse/SDK-22454
    Modified Paths:
        flex/sdk/trunk/modules/compiler/src/java/flex2/compiler/css/StyleDef.vm
        flex/sdk/trunk/modules/compiler/src/java/flex2/compiler/css/StylesContainer.java
        flex/sdk/trunk/modules/compiler/src/java/flex2/tools/PreLink.java

    Revision: 11575
    Author:   [email protected]
    Date:     2009-11-09 11:34:57 -0800 (Mon, 09 Nov 2009)
    Log Message:
    Put default style declarations into one class per application or module.
    Generate all the default styles in one class instead of a class for each style. The name of the style class will be based on the application or module name. An application named ?\226?\128?\156foo?\226?\128?\157 will have a style class named ?\226?\128?\156_foo_Style?\226?\128?\157. The idea is to allow applications to be compiled with different themes and get their owns styles. Currently this is not possible because a global style in both themes will have the same class name, _globalStyle. Whatever class the top-level application loads the sub-applications and modules will have to use the same class because of the flash player first-class-in-wins rule. Now each application and module will have their own style class.
    QE notes: None.
    Doc notes: None.
    Bugs: SDK-22454
    Reviewer: Paul, Pete
    Tests run: checkintests, all mustella tests.
    Is noteworthy for integration: No.
    Ticket Links:
        http://bugs.adobe.com/jira/browse/SDK-22454
    Modified Paths:
        flex/sdk/trunk/modules/compiler/src/java/flex2/compiler/css/StyleDef.vm
        flex/sdk/trunk/modules/compiler/src/java/flex2/compiler/css/StylesContainer.java
        flex/sdk/trunk/modules/compiler/src/java/flex2/tools/PreLink.java

  • Customized Top Level Navigation iView

    Hello to all
    We are using a customized TLN iview. Its source code was modified to admit different URLs, and do the filtering depending of the default framework page which is using the TNL iview,
    I mean, the TLN would be copied inside a proyect folder on the Portal Content, where would be a DFPage that contains a copy of TNL iview, and this copy would have a different roleFilter attribute.
    Then, the TLN was modified again in order to merge roles that had the same name.
    Those changes doesn't seem really important, they have just declared some vars, and each of them added one code line. The first one extended the first part of an IF condition, and the second one extended it with another condition, using OR.
    The problem is that after the modifications, our TLN doesn't highlight correctly the first node when accessing or refreshing the Portal, instead of it shows a default start page that doesn't belong to any of our roles
    The TLN iview has a procedure named PrintNavNodes, which is called on the event OnClick (I assume), and when we accessrefresh the page too.
    The iview works well when clicking its buttons, it's just the first time it is used when the wrong page is shown, that's the problem we need to correct.
    This procedure (PrintNavNodes) lodges the code changes. The only var modified is String prefix, so maybe anyone could tell me a default value to it, o a way to catch that mistake in order to show another page when the default page is to appear.
    Also, I would appreciate if anyone knows about an API, andor a How to... manual, or any kind of documentation about this subject.
    We have no possibility of reject the changes, so we need to find an alternative solution. Here is the code...
    Thanks in advance, and regards
        private void PrintNavNodes(IPortalComponentRequest request, IPortalComponentResponse response)
         ILogger loggerArquitectura = request.getLogger(portal_logger);
             String strDataToPrint=;
         NavigationEventsHelperService navHelperService = (NavigationEventsHelperService)PortalRuntime.getRuntimeResources().getService(com.sap.portal.navigation.helperservice.navigation_events_helper);
         NavigationNodes initialNodes = navHelperService.getRealInitialNodes(request);       
    !-- Change Heiko Broker for SiteNavigation          
              IPortalComponentContext componentContext = request.getComponentContext();
              IPortalComponentProfile profile = componentContext.getProfile();
              String roleFilter = profile.getProperty(RoleFilter);
            if(initialNodes != null)
         INavigationNode firstChild = null;
         INavigationNode firstContent = null;          
         String prefix=ROLESportal_content;
    !-- Change Marta Alberto
         PROBLEM In the new TLN, when using the merge roles feature, the
         url of the merge roles is different (start with the word merge.....).
         This is a wrong implementation because it filters all the nodes that do
         not start with ROLES.
         SOLUTION Compare with the other prefix too.
         String newPrefixThatFixesTheProblem=MERGESportal_content;          
         String newPrefixThatFixesTheProblem=merge(;
                if(initialNodes.size()  0)      
                for(Iterator it = initialNodes.iterator(); it.hasNext();)
                    INavigationNode initialNode = (INavigationNode)it.next();
                        strDataToPrint=initialNode.getName(),;
    !-- Change Heiko Broker for SiteNavigation          
         if (initialNode.getName().startsWith(prefix+roleFilter)
    !-- Change Marta Alberto
         PROBLEM In the new TLN, when using the merge roles feature, the
         url of the merge roles is different (start with the word merge.....).
         This is a wrong implementation because it filters all the nodes that do
         not start with ROLES.
         SOLUTION Compare with the other prefix too.
          initialNode.getName().startsWith(newPrefixThatFixesTheProblem + prefix + roleFilter))                    
                         firstContent = PrintNode(initialNode, request, response, 0);
                         if(firstChild == initialNode)
                             if(firstChild.getLaunchURL() != null && !firstChild.getLaunchURL().equals())
                                 firstContent = firstChild;
                             else
                             if(firstContent == null)
                                 try
                   firstContent = firstChild.getFirstChild();
                                 catch(NamingException e)
                   ILogger logger = request.getLogger(navigation_logger);
                   if(logger != null && logger.isActive())
                        logger.severe(this, e, Exception in Top Level Navigation);
                             HttpSession httpSession = request.getServletRequest().getSession();
                             httpSession.setAttribute(NavFirstContentNode, firstContent);
                }  end FOR
            response.write(););

    Hi,
    Check authentication related properties of iView. Make sure all of them are set to lowest level or none
    Regards,
    Ganga

  • Customizing Top level navigation

    Hi,
    I have requirement where in i have to customize the top level navigation. Insted of hyper links display i have to show them like buttons, not exactly buttons but the hyperlinks shown for the navigation should be removed.
    Is it possible to show with out links and once click on the respective workset should be able to navigate that workset.
    Is it possible to place image for each workset navigation in top level navigation.
    Regards,
    Ravi.

    Hi Darrell,
    I checked that code and it is using the navHelperServer.getQuickLink method where it gets the Quick Link Value of the pages i guess.
    I could not find the method details and the declaration of this method in the help. Is it the custom method written of that class.
    I am using the below standard code of the LightTopLevelNavigation.
    I guess i need to put the custom code between the navNodeAnchor Tags of Selected and non selected Nodes.
    <TABLE border="0" cellspacing="0" cellpadding="0" class="mainTable" align="center">
      <TR>
    <!--     <TD nowrap class="notch"> </TD> -->
        <TD>
          <TABLE border="0" cellspacing="0" cellpadding="0" class="table1">
            <TR>
              <nav:iterateInitialNavNodes>
                <nav:ifNavNodeInSelectedPath>
                  <TD nowrap class="chosenTDLevel1">
                    <% if(previewMode) { %>
                      <A class="chosenOnLevel1"><nav:navNodeTitle/></A>
                    <% } else if(levels==1) { %>
                      <nav:navNodeAnchor navigationMethod="byURL" anchorAttributes="class='chosenOnLevel1'">
                      </nav:navNodeAnchor>
                    <% } else if(levels==2) { %>
                      <nav:navNodeAnchor navigationMethod="byURL" anchorAttributes="class='chosenOnLevel1'" urlParameters="InitialNodeFirstLevel=true"/>
                    <% } %>
                  </TD>
                  <% if(levels==2) { %>
                    <nav:storeNavNode/>
                  <% } %>
                </nav:ifNavNodeInSelectedPath>
                <nav:ifNotNavNodeInSelectedPath>
                  <TD nowrap class="unChosenTDLevel1">
                    <% if(previewMode) { %>
                      <A class="chosenOnLevel1"><nav:navNodeTitle/></A>
                    <% } else if(levels==1) { %>
                      <nav:navNodeAnchor navigationMethod="byURL" anchorAttributes="class='unChosenOnLevel1'"/>
                    <% } else if(levels==2) { %>
                      <nav:navNodeAnchor navigationMethod="byURL" anchorAttributes="class='unChosenOnLevel1'" urlParameters="InitialNodeFirstLevel=true"/>
                    <% } %>
                  </TD>
                </nav:ifNotNavNodeInSelectedPath>
                   <nav:ifHasMoreIterations>
                     <TD nowrap class="spacingTDPipeLevel2" valign="center"> | </TD>
                   </nav:ifHasMoreIterations>
              </nav:iterateInitialNavNodes>
              <TD nowrap class="spacingTDLevel1"> </TD>
            </TR>
          </TABLE>
    Thanks
    Sumanth

Maybe you are looking for

  • Can't sync Samsung SCH-u740 with Mac

    Anyone know when/if Apple will add a plugin or provide docs on how to create a plugin for the SCH-u740? I have scoured the web to no avail. Just got this great phone, but if I can't sync to it ... loses a lot of utility. Please help ...

  • I need to reverse the command and let the computer use Windows to search the program I want to use t

    I am not sure if you can help me.  I need to command my computer to look for a program that is most suited to open files automatically.  I accidentally check the mannual mode and appointed Adobe Reader x to be the designated program.  Now nothing wil

  • 终于搞定Weblogic8.1sp3下奇怪的Oracle错误了!也算是新Bug喽!

    本来计划新服务器割接要在本月底完成,可是在部署完成以后在操作数据库的时候却出了岔子.怎么也不能用了,连接很正常,就是不能 select,update,insert等操作.最经常报的三个错误是: OALL8 is in an inconsistent state. Bigger type length than Maximum Protocol Violation 三个错误随机出现,最常见的是前两个. 因为现有的程序正在一台 Linux 服务器上正常运行,我只是把整套系统原模原样的重新部署到了一台

  • BPEL abstract process

    Hi A BPEL orchestration server is responsible for executing BPEL process flows and managing the deployed process instances. Orchestration is associated with private processes while Choreography stands for abstract processes, aka public protocol. Can

  • LibGL error: failed to load driver: swrast

    I'm trying to launch Dungeon Defenders but this happens: $ ./DungeonDefenders --LIBGL_DEBUG=verbose Dungeon Defenders: Installed in '/home/casa/Giochi/DungeonDefenders'. libGL error: failed to load driver: swrast libGL error: Try again with LIBGL_DEB