Why do we make methods besides main private?

just wondering why are some methods made private?

885018 wrote:
just wondering why are some methods made private?Because there's no need to call them from outside the class, and in fact, it could be harmful to do so.
Think of a car. There are a few controls that you the driver have access to (public methods): Gas, brake, steering wheel, gearshift, etc. But there are many other mechanisms in your car that have jobs to do, that you don't need to touch and shouldn't touch, but that are invoked as a result of you interacting with the "public methods". For instance, you don't need to directly trigger the spark plugs to ignite the fuel-air mixture, so there are no switches in the driver's compartment for you to do so. That is a "private method" that is invoked as a result of what you do with the "public methods."

Similar Messages

  • Why a base class cannot be a Private or Protected ?????

    why a base class cannot be a Private or Protected ?????

    why a base class cannot be a Private orProtected
    ?????Who would be able to access it? (Assuming "base"
    means top-level class.)Private, none. Protected, all classes in same package
    and subclasses (as with the methods).
    Actually, its somewhat illogical that a class be
    declared package-private, but not protected, since
    protected is less restrictive.having a protected class would make no sense. subclasses are not permitted to lessen the protection of members of their superclass, so you'd end up with a class that nothing could use, except subclasses that in turn nothing else could use

  • Why is the static method in the superclass more specific?

    Why is the static method in the superclass more specific than the static method in the subclass? After all, int is a subtype of long, but Base is not a subtype of Sub.
    class Base {
        static void m(int i){ System.out.println("Base"); }
    class Sub extends Base {
        static void m(long l){ System.out.println("Sub"); }
    class Test {
        public static void main(String[] args) {
            int i = 10;
            Sub sub = new Sub();
            sub.m(i);
    }The first example compiles without error.
    Output: Base
    class Base {
        void m(int i){ System.out.println("Base"); }
    class Sub extends Base {
        void m(long l){ System.out.println("Sub"); }
    class Test {
        public static void main(String[] args) {
            int i = 10;
            Sub sub = new Sub();
            sub.m(i);
    }In the second example, both instance methods are applicable and accessible (JLS 15.12.2.1), but neither is more specific (JLS 12.2.2), so we get a compiler error as expected.
    : reference to m is ambiguous,
    both method m(int) in Base and method m(long) in Sub match
    sub.m(i);
    ^
    1 error
    Why don�t we get a compiler error for the static methods?

    Thank you for your ideas.
    ====
    OUNOS:
    I don't get Sylvia's response. This is about static methods, what are instances are needed for??Yes, the question is about static methods. I included the example with non-static methods for a comparison. According to JLS 15.12.2, both examples should cause a compiler error.
    And why you create a Sub object to call the method, and dont just call "Sub.m(..)"Yes, it would make more sense to call Sub.m(i). Let�s change it. Now, I ask the same question. Why is there no compiler error?
    ====
    DANPERKINS:
    The error in your logic stems from calling static methods on instances, as ounos pointed out. Solution: don't. You won't see any more ambiguities.A static member of a class may also be accessed via a reference to an object of that class. It is not an error. (The value of the reference can even be null.)
    Originally I was looking only at the case with non-static methods. Therefore, I used sub.m(i). Once I understood that case, I added the static modifiers. When posting my question, I wish I had also changed sub.m to Sub.m. Either way, according to JLS 15.12.2, a compiler error should occur due to ambiguous method invocation.
    ====
    SILVIAE:
    The question was not about finding an alternative approach that doesn't throw up an ambiguity. The question related to why, in the particular situations described, the ambiguity arises in only one of them.
    Yes.
    Proposing an alternative approach doesn't address the question.
    Yes.
    ====
    If anyone is really interested, here is some background to the question. Some people studying for a Sun Java certificate were investigating some subtleties of method invocations:
    http://saloon.javaranch.com/cgi-bin/ubb/ultimatebb.cgi?ubb=get_topic&f=24&t=019182
    I remember seeing the non-static case discussed in this forum once before in a more practical context. jschell probably knows the link.

  • Methods outside main()

    Hello,
    Can have methods outside main() ?
    I am trying to call abc and says non-static method abc() cannot be referenced from a static context
    abc();
    When I make it static it is compiling but I dont want it to be a static method...
    public static void main( String[] as )
              abc();
         public void abc( )
    //Prints Hello
    }

    No I dont have too much of a C/C++ background but I am
    curious about static variable and methods..
    I can understand that we need to use static methods
    when you want the value to be same across all objects
    and at the same time can be changed....
    for example:
    Object 1
    public static String loc = "location:4444";
    Object2 calls
    loc = "location:5555"
    so if object 2 changes port or location... Object 1's
    loc also changes...
    So this means that when we are going to change the loc
    later on somewhere we can make it static... Otherwise
    if our location will never change and always be
    location:4444 then we are better off making that
    variable final and not static.
    Am I right?I'm not really following what you're asking, but static and final are not mutually exclusive. One of the most common uses of static member variables is as class-wide constants--either public or private--in which case they are also final.

  • How can i invoke a void method in main?

    Hi guys I am killing myself over why we use void method if we can't call on it from main.
    For example i am trying to create a program to calculate military time. In my main i am trying to call setHour which is void. setHour is supose to check if the input of hour is over 24 and if it is i have to reset hour to 00. But it gives an error that i can't call on that method because it is void.
    So how do i invoke it from main?
    and
    Why do we use void if we can't call on it?
    Thanks

    ok here it is mate. It is not finished but pay attention on the setMethods that is what im trying to invoke from main. Here's my methods and then main will be under it.
    public class MilitaryTime
          private int hour;
          private int minute;
          private int second;
           public MilitaryTime()
             hour=0;
             minute=0;
             second=0;
           public MilitaryTime(int hour, int minute, int second)
             this.hour=hour;
             this.minute=minute;
             this.second=second;
           public MilitaryTime(MilitaryTime t)
           public void setHour(int h)
             if(h>=24)
                h=00;
             else
                hour=h;
           public void setMinute(int m)
             if(m>=60)
                m=00;
             else
                minute=m;
           public void setSecond(int s)
             if(s>=60)
                s=00;
             else
                second=s;
           public int getHour()
             return hour;
           public int getMinute()
             return minute;
           public int getSecond()
             return second;
           public void tick()
             second=second+1;
           public String toUniversalString()
             StringBuffer     buffer;
             buffer = new StringBuffer();
          // add the hour (with leading zero if its neccesary)
             if(this.hour < 10)
                buffer.append("0");
             buffer.append(this.hour).append(":");
          // add the minute (with leading zero if its neccesary)
             if(this.minute < 10)
                buffer.append("0");
             buffer.append(this.minute).append(":");
          // add the second (with leading zero if its neccesary)
             if(this.second < 10)
                buffer.append("0");
             buffer.append(this.second).append("");
             return buffer.toUniversalString();
           public String toString()
             StringBuffer     buffer;
             buffer = new StringBuffer();
          // add the hour (with leading zero if its neccesary)
             if(this.hour < 10)
                buffer.append("0");
             buffer.append(this.hour).append(":");
          // add the minute (with leading zero if its neccesary)
             if(this.minute < 10)
                buffer.append("0");
             buffer.append(this.minute).append(":");
          // add the second (with leading zero if its neccesary)
             if(this.second < 10)
                buffer.append("0");
             buffer.append(this.second).append("");
             return buffer.toString();
       }Here is main where i try and call setHour to check for accuracy.
    import javax.swing.*;
    public class TestMilitaryTime
         public static void main(String[]args)
                        String sHour=JOptionPane.showInputDialog(null,
                "Input Hour:", "Military Time",JOptionPane.QUESTION_MESSAGE);
                        int hour=Integer.parseInt(sHour);
                        String sMinutes=JOptionPane.showInputDialog(null,
                "Input minutes:", "Military Time",JOptionPane.QUESTION_MESSAGE);
                        int minutes=Integer.parseInt(sMinutes);
                        String sSeconds=JOptionPane.showInputDialog(null,
                "Input seconds:", "Military Time",JOptionPane.QUESTION_MESSAGE);
                        int seconds=Integer.parseInt(sSeconds);
                        MilitaryTime time= new MilitaryTime(hour,minutes,seconds);
                        System.out.println(time.setHour());
                        System.out.println("The military time is you enterd is "+time.toString());
         Everything else works fine except the setHour thing.
    Thanks

  • Why do we need static for main() .........?

    Why do we need static for main method
    class Sample
    public static void main(String args[])
    System.out.println("HI EVERYONE");
    }

    The Java virtual machine is another term for the Java interpreter, which is the code that ultimately runs Java programs by interpreting the intermediate byte-code format of the Java programming language. The Java interpreter actually comes in two popular forms: the interpreter itself (called java) that runs programs via the command line or a file manager, and the interpreter that is built into many popular Web browsers such as Netscape, HotJava, and the appletviewer that comes with the Java Developer's Kit. Both of these forms are simply implementations of the Java virtual machine, and we'll refer to the Java virtual machine when our discussion applies to both. When we use the term java interpreter, we're talking specifically about the command line, standalone version of the virtual machine; when we use the term Java-enabled browser (or, more simply, browser), we're talking specifically about the virtual machine built into these Web browsers.
    excerpts Orelly "Java Threads" Chapter 1. (If you don't believe me). Did i do any fundamental wrong by saying interpreter ? Is that a Sin ?
    That is why i told concentrate on what answer I gave regarding the question. I am not going to argue any more. If you don't like my comments then I am Sorry :(

  • Why java allow start() method only once for a thread

    Hi ,
    Why java allows start method only once for thread . suppose
    Thread t = new Thread();
    t.start();
    say at later stage if again we call t.start() IllegalStateException is thrown , even though isAlive method returns false.
    Hence the question , why start() method is allowed only once.If you need start a thread , we need to create a new instance.

    Really. Why do you think that? Do you have any evidence? It is one of the first things I would think of, personally.Considering that the Thread API doesn't allow you to specify a stack address (only stack size), I think it demonstrates they wanted to remove that capability from their Thread API all together. That missing "capability" makes me believe they want me to believe it's not something I need to worry about when using their API... I think the exact semantics of the Thread class and its methods were driven by how to make it most understandable and usable for their customers. I'm certain this issue was one of many that was given considerable thought during the design and implementation of the JVM and the underlying runtime classes.
    Do I have any evidence? No. But if you can point me at some first-hand information on this, I'd love to read it. Most of what I've found is second or third hand accounts. (and I mean that sincerely, not as a smart-ass remark or rebuke of your comments).
    On the one hand you seem to think the Java API designers are idiots, on the other hand you think that they should be. I can't make it out.I thought my position was that the Java developers were talented enough to implement platform in whatever way their API called for; hence, the designers made a choice about how they wanted their API to be used by their customers. They decided which capabilities they wanted to include or exclude, and created an API that was consistent with their vision for this technology. While I'm certain technical limitations had an effect on the API design, I certainly don't think the API was dictated by the them.
    I think the current design of the Java Thread API was a reflection of their vision to make Threading easier and more accessible to Joe Programmer, not limitations in the implementation. I never said it was wrong or that I could do better... I just said I think they could have done something different if they decided it would have made for a better customer experience. But hey, maybe I'm wrong.

  • Disadvantage LSMW Method besides Recording

    Hi Expert,
    In LSMW, there are several method such as Direct input, Batch recording, Bapi, and IDoc. Commonly, we use Batch recording. I would like to use another method for uploading the data, but then my supervisor ask me if there is disadvantage / side effect on using other method besides recording.
    Especially, if I want to use Bapi method, I need to activate Idoc inbound Processing. Is there any negative effect if I activate it?
    Thanks before

    If LSMW would only have recording as import method, then I would call the usage of the whole tool a disadvantage.
    I use LSMW for many years, and maybe because we are big company with complex processes I rarely find an option where recording can be a solution.
    Recording is static, most of the data I have to deal with requires flexibility, hence I have to make use of the other 3 import options.So it is an advantage to have Batch Input, IDOC and BAPI method.
    What is save, what is unsave? if you connect a test system with a productive system, then some say that this is unsave.
    Sure there can be side effects, especially if a an unexperienced user has to do the customizing.
    I personally have never seen a negative side effect with activating IDOC inbound processing in LSMW.

  • How can I make my iWeb site private?

    How can I make my iWeb site private with a password?

    The inbuilt facility to do this disappeared with the demise of MobileMe. It is possible: some ISPs offer this facility (GoDaddy is one) so you should start by checking whether yours does.
    If not, you can do it yourself provided your ISP allows you to add an .htaccess file to your foldere - not all do. Also it's not entirely straighforward if you are unfamiliar with the techniques involved.
    This page describes the method:
    http://www.thesitewizard.com/apache/password-protect-directory.shtml
    Please note the caveats at the bottom of the page: this isn't a highly secure method and you should not rely on it to protect sensitive information.

  • Why did Apple make the new iPod unable to use Griffin iTalk or iTrip?

    I was so disappointed when I upgraded to the new 5th gen. iPod and was unable to use the accessories I purchased for my previous iPod. Am I missing something? What am I supposed to do? Is there an attachment that will make them usable? Why would Apple make a new iPod that wouldn't include the same connector?

    See below your so-called answer to my question.
    I also noticed you have marked it solved. If, as a moderator, you can say that your response was considerate of the people using the system then I guess it was solved. If I was to mark it I would say the reply was very condescending and thus worthy of a 1 out of 10 as far as a reply goes. In the future please do not answer my posts as I would like to be treated with a little respect as I'm sure you would like. Please get some other Mod who can perhaps relate to a person's concern. Your answer may be correct but your way of putting it across sounds like some of the 13 year old school children I use to teach.
    You have a good day.

  • Why when I make a dvd from an album are my photos not in order?

    Why when I make a dvd from an album are my photos not in order?

    hansm99079164 a écrit:
    Why when I make a dvd from an album are my photos not in order?
    Simply because your Explorer/Finder only takes into account the file names and dates of your files.
    For instance, in Windows, you have to tell the explorer to sort by 'date taken' otherwise the default sort orders are file dates or file names.
    If you have given a 'custom' sort order to your albums, the only way for the Explorer to sort in the same way is to set the custom sort order in the album, export to a new folder with the 'rename' option - same starting text string plus order.

  • Why does the Java method ServletContext.getResourceAsStream return null with a know good path to an xsl file?

    iPLANET ISSUE
    Why does the Java method ServletContext.getResourceAsStream return null with a know good path to an xsl file?
    CODE
    ServletContext context = mpiCfg.getServletConfig().getServletContext();
    // Debugging
    out.print(context.getServerInfo());     // Get server info
    out.print(&#8220;getRealPath = &#8221; + context.getRealPath("WEB-INF/xsl/RedirectToAcs.xsl"));
    String strXslName = "RedirectToAcs.xsl";
    InputStream is = context.getResourceAsStream("WEB-INF/xsl/"+ strXslName);
    TRACE FROM THE LOG
    [26/Jul/2002:08:23:15] info ( 2868): [0][][ClearCommerceCcpaMpi][]getServerInfo() = iPlanet-WebServer-Enterprise/6.0, getRealPath() = C:\iPlanet\Servers\web-apps\ccpa\WEB-INF\xsl\RedirectToAcs.xsl
    [26/Jul/2002:08:23:15] info ( 2868): [0][][ClearCommerceCcpaMpi][]strXslName = RedirectToAcs.xsl, is = null
    [26/Jul/2002:08:23:15] info ( 2868): [1][][ClearCommerceCcpaMpi][16]ResourceAsStream is null
    [26/Jul/2002:08:23:15] info ( 2868): [1][][ClearCommerceCcpaMpi][30]Problem reading XSL file.
    DIRECTORY DUMP
    C:\iPlanet\Servers\web-apps\ccpa\WEB-INF\xsl>dir
    Volume in drive C has no label.
    Volume Serial Number is 9457-EBF4
    Directory of C:\iPlanet\Servers\web-apps\ccpa\WEB-INF\xsl
    07/22/2002 05:54p <DIR> .
    07/22/2002 05:54p <DIR> ..
    07/22/2002 05:54p 3,086 RedirectToAcs.xsl
    07/22/2002 05:54p 3,088 Response.xsl
    2 File(s) 6,174 bytes
    2 Dir(s) 1,797,405,696 bytes free

    I think there's supposed to be a forward slash before WEB-INF.
    InputStream is = context.getResourceAsStream("/WEB-INF/xsl/"+ strXslName);

  • Why does JDBC make me commit a query?

    I was working with two DB2 database connections, A and B, and performed the following logic:
    Turned off AutoCommit for A and B
    Updated A
    Updated B
    Committted A
    Rolled back B
    Selected from A
    Selected from B
    Updated A
    Committed A
    Closed Connection A
    Closed Connection B
    Everything worked well until I tried to close Connection B. It threw a SQL Exception with the description "invalid transaction state". I read online that this means you are trying to close a connection with uncommitted data. It didn't make sense because the only thing I had done since rolling back was SELECT. When I tried it with a rollback or commit immediately before closing the connection, it worked. Any ideas why it would make me commit a SELECT? Is this just an unintended bug or could they have implemented it like this on purpose?

    I also first was wondering why a select should be committed.
    But also a select can cause locks that influence other connections. How, depends on the isolation level you set. For example SERIALIZABLE would block inserts by another connection that would change your retrieval in case you repeat it.
    To make the DBMS know that after your retrieval your processing of these data is done - no changes following - you must end the transaction by commit (or rollback - would be the same here since you've done no changes).

  • Why does backbean's method be invoked when page navigation to other page

    Hi, All
    Why does backbean's method getBeans() be invoked
    when current page(list.jsp) navigation to other page(edit.jsp)?
    //client list.jsp
    <h:dataTable id="items" value="#{userDelegate.beans}"
    var="user" rowClasses="oddRow, evenRow" headerClass="tableHeader" >
    //server backbean
    public class CustomDelegate extends BaseDelegate{
    public ListDataModel getBeans(){}
    when list.jsp first initialize(first load), jsf invoke getBeans(), is right;
    but when from list.jsp navigation to edit.jsp, jsf invoke getBeans() too!
    what's the matter with it?

    How are you invoking the navigation? With a simple h:outputLink which links to another page or with an h:commandLink/h:commandButton which naturally first invokes the backingbean?
    If you're using h:outputLink, then this behaviour may not occur. You may review/redesign your JSF and bean logic.
    If you're using UICommand link/button, then this is usual behaviour. (re)read the JSF lifecycle for an explanation. If you ONLY want to get the navigation case, then you can 1) replace the methodbinding from action or actionListener by just the navigation case string, or 2) add immediate="true" to the UICommand element.
    This article might be of interest: http://balusc.xs4all.nl/srv/dev-jep-djl.html

  • Why my account payment method decline

    Why my account payment method decline

    Altafjan wrote:
    Why my account payment method decline
    iTunes Store: Accepted forms of payment
    http://support.apple.com/kb/HT5552
    If necessary...
    Contact iTunes Customer Service and request assistance
    Use this Link  >  Apple  Support  iTunes Store  Contact

Maybe you are looking for

  • Please Help CS5 crashes on new Mac Air

    Photoshop CS5 is crashing everytime i open a file within a span of 1 min making photoshop useless to work on. I am using the new Mac Air. I have no clue what to do. The following is the crash log checked previous thread its similar to them but what i

  • HT1695 Trouble connecting to VErizon network home system?

    When trying to connect to my home verizon network, it recognizes the name of the network, but doesn't offer me the opportunity to put in a password when I select it.  What's up??  DW

  • How do I stop the "install Flash..." pop-up? It is annoying!

    I use Windows 7 and Firefox 23, and both a updated often. I uninstalled ALL Adobe products to get rid of their spying tools - long-tern cookies that could not be blocked. Shortly after I used Adobe's tools to eliminate local storage, I would go back

  • Dreamweaver photo album

    When I put up a new photo album in Dreamweaver and put it live on my site, only the thumbnails show up. What am I doing wrong

  • Windows to Mac and Back workflow

    Hello: Thanks in advance.. Here is the workflow: Vegas Sony on Windows .avi clips captured into Sony Vegas on Windows clips copied onto external firewire drive firewire drive goes to editor editor works on MacBook Pro - Final Cut Pro 6 How does the f