Why do we need private static method or member class

Dear java gurus,
I have a question about the use of private and static key words together in a method or inner class.
If we want to hide the method, private is enough. a private static method is sure not intended to be called outside the class. So the only usage I could see is that this private static method is to be called by another static method. For inner class, I see the definition of Entry inner class in java.util.Hashtable, it is static private. I don't know why not just define it as private. Could the static key word do anything better.
Could anybody help me to clear this.
Thanks,

What don't you get? Private does one thing, andstatic does >something completely different.
If you want to listen to music, installing an airconditioner doesn't help>
Hi, if the private keyword is the airconditioner, do
you think you could get music from the static keyword
(it acts as the CD player) in the following codes:You're making no sense and you're trying to stretch the analogy too far.
Private does one thing. If you want that thing, use private.
Static does something completely different and unrelated. If you want that thing, use static.
If you want both things, use private static.
What do you not understand? How can you claim that you understand that they are different, and then ask, "Why do we need static if we have private"? That question makes no sense if you actually do understand that they're different.

Similar Messages

  • I really need abstract static methods in abstract class

    Hello all.. I have a problem,
    I seem to really need abstract static methods.. but they are not supported.. but I think the JVM should implement them.. i just need them!
    Or can someone else explain me how to do this without abstract static methods:
    abstract class A {
    abstract static Y getY();
    static X getX() {
        // this methods uses getY, for example:
        y=getY();
       return new X(y); // or whatever
    class B extends A {
    static Y getY() { return YofB; }
    class C extends A {
    static Y getY() { return YofC; }
    // code that actually uses the classes above:
    // these are static calls
    B.getX();
    A.getX();I know this wont compile. How should i do it to implement the same?

    Damn i posted this in the wrong thread.. anyways.
    Yes offcourse i understand abstract and static
    But i have a problem where the only solution is to use them both.
    I think it is theoretically possible ot implement a JVM with support for abstract static methods.
    In fact it is a design decision to not support abstract static methods.. thats why i am asking this question.. how could you implemented this otherwise?
    There is an ugly soluition i think: using Aspect Oriented Programming with for example AspectJ.. but that solution is really ugly. So anyone has an OO solution?

  • Private static method

    How do I get access to a private static method of a class?
    I can't just call it by object.privatemethod() , right?

    unless your call is made within the body of the
    class, you cannot call it, otherwise just call it via
    a static ref of the class
    ObjectName.privateMethod()
    (not)
    ObjectInstance.privateMethod()...where "ObjectName" is the name of the class.
    Or you can just call it with privateMethod(), but that tends so suggest "this.privateMethod()" so I'd go with qualifying it with the class name, to be clear.

  • What is the use of private static method/variable?

    Hi All,
    I have read lots of books and tried lots of things but still not very clear on the
    topic above.
    When exactly do we HAVE to use private static methods?
    private implies its only for class, cannot be accessed outside.
    But then static means, it can be accessed giving classname.method.
    They seem to be contradicting each other.
    Any examples explaining the exact behaviour will be well appreciated.
    Thanks,
    Chandra Mohan

    Static doesn't really "mean" that the method/field is intended for use outside the class - that is exactly what the access modifier is for.
    Static implies that it is for use in relation to the class itself, as opposed to an instance of the class.
    One good example of a private static method would be a utility method that is (only) invoked by other (possibly public) static methods; it is not required outside the class (indeed, it might be dangerous to expose the method) but it must be called from another static method so it, in turn, must be static.
    Hope this helps.

  • Why interfaces can not declare static methods?

    Why interfaces can not declare static methods?

    Why are you shouting?
    Is your internet broken?
    [http://www.google.co.uk/search?q=interface+static+methods+java] 2,440,000 hits.

  • Why do we need the @EJB annotation at the class level?

    Why do we need the @EJB annotation at the class level?
    Eg: Why do we need the first piece of code, when the second code seems much simpler .
    *1.*
    @Stateful
    @EJB(name="ejb/TradeLocalNm",
    beanInterface=TradeLocal.class)
    public class TradeClientBean implements TradeClientRemote {
    *2.*
    @Stateful
    public class TradeClientBean implements TradeClientRemote {
    @EJB private TradeLocal trd;
    }

    I think it is possible to do it in an aggregated level however you need to define your distribution rules in order to get the desired result, you need also to consider that if distribution rules changes and the value after promotional planning returns the same value, it is possible that detailed level are not realigned to the new distribution rule (e.g. regarding another ratio).
    Maybe this is one of several causes.
    Regards,
    Carlos

  • Static methods in startup class

    I have declared few static methods in startup class. What will happen
              once startup class is executed in cluster environment, will the access
              to those static methods be clustered and replicated across the
              clusters. How exactly the startup class behaves in clustered
              environment.
              I will appreciate an urgent response.
              Thanks,
              SidShar .
              

    SidShar,
              > I have declared few static methods in startup class. What will
              > happen once startup class is executed in cluster environment,
              > will the access to those static methods be clustered and
              > replicated across the clusters.
              No.
              > How exactly the startup class behaves in clustered environment.
              It is run on each server that it is configured to run on. The method calls
              to the startup class will all be local unless you do some special work to
              force it to be otherwise.
              If you want to have something done once and only once in the cluster, or
              coordinate stuff like that, then either use a shared resource (such as the
              database) to coordinate it all, or use Coherence, which lets you share and
              coordinate access to data among all the servers in the app tier.
              Peace,
              Cameron Purdy
              Tangosol, Inc.
              http://www.tangosol.com/coherence.jsp
              Tangosol Coherence: Clustered Replicated Cache for Weblogic
              "sidshar" <[email protected]> wrote in message
              news:[email protected]..
              >
              

  • I am not able access static methods from startup class

    I have a simple java class which queries the Database and holds some data. I am trying to access a static method of this class from the StartupClass and I am not able to do so. But I am able to access a static variable of the same class.
    Can someone help me here.

    Well, welcome to the world of "hacked" phones. If your purchase was from the US, you obviously purchased an iPhone that is locked to a US carrier. The iPhone must have been jailbroken and unlocked via software to accommodate your foreign SIM card. Now that you have updated the phone, it is locked back to the US carrier. Only the carrier can authorize Apple to unlock the iPhone and none of the US carriers will unlock the iPhones. Best suggestion is to sell the phone and obtain a factory unlocked version directly from the Apple store.
    To answer your other question, there is not a supported method to downgrade iOS.

  • How to find the arguments of a static method from the class file

    Hi,all !
    How to find the arguments of a static method from the class file? for example, when we meet a bytecode "invokestatic", how can I know the arguments of this static method?

    Hi,all !
    How to find the arguments of a static method from the
    class file? for example, when we meet a bytecode
    "invokestatic", how can I know the arguments of this
    static method?You mean
    1. The values?
    2. Argument names?
    3. Argument signatures.
    I would suppose for the last that the easiest way would be to parse the signature string.
    The first is not possible - not from the class file.
    The second is only in the debug information stored in the optional part of the class file. And figuring out the format for that is going to be a problem.

  • What is the purpose of Static methods inside a class?

    Hi,
    What is the purpose of Static methods inside a class?
    I want the answers apart from "A static method does not require instance of class(to access) and it can directly be accessed by the class name itself"
    My question is what is the exact purpose of a static method ?
    Unlike attributes, a separate copy of instance attributes will be created for each instance of a class where as only one copy of static attributes will be created for all instances.
    Will a separate copy of instance method be created for each instance of a class and only one copy of static methods be create?
    Points will be rewarded for all helpful answers.

    Hi Sharma,
    Static methods is used to access statics attributes of a class. We use static attributes when we want to share the same attribute with all instances of a class, in this case if you chage this attribute through the instance A this change will change will be reflected in instance B, C........etc.
    I think that your question is correct -> a separate copy of instance method will be created for each instance of a class and only one copy of static methods be create ?
    "A static method does not require instance of class(to access) and it can directly be accessed by the class name itself"
    Static Method: call method class=>method.
    Instance Method: call method instance->method.
    Take a look at this wiki pages.
    [https://wiki.sdn.sap.com/wiki/x/o5k]
    [https://wiki.sdn.sap.com/wiki/x/ZtM]
    Best regards.
    Marcelo Ramos

  • What am I doing wrong with the isNew() method?  and why do I need the other methods?

    I have coded an include jsp like this.
              <%@page language="Java"%>
              <%@page import="javax.servlet.http.HttpSession"%>
              <%!
              String iContextPath;
              String iCommonPath;
              String iImagesPath;
              %>
              <%
              iContextPath = request.getContextPath();
              iCommonPath = iContextPath + "/common";
              iImagesPath = iCommonPath + "/images";
              System.err.println(" here ");
              HttpSession thisSession = request.getSession( false );
              if( thisSession.isNew() ){
              System.err.println("isnew");
              response.sendRedirect( iContextPath + "/common/login.jsp" );
              %>
              Now I also have a redirect.jsp in the root of an application that contains
              this.
              <html>
              <body>
              <%
              System.err.println("Redirecting at this time from the root");
              response.sendRedirect( request.getContextPath() + "/secureArea/");
              %>
              </body>
              </html>
              And I have a logout.java servlet that looks like this.
              package com.pch.epics;
              import java.io.IOException;
              import javax.servlet.ServletException;
              import javax.servlet.http.HttpServlet;
              import javax.servlet.http.HttpServletRequest;
              import javax.servlet.http.HttpServletResponse;
              import weblogic.servlet.security.ServletAuthentication;
              public class Logout extends HttpServlet{
              private static final String CONTENT_TYPE = "text/html";
              //Initialize global variables
              public void init() throws ServletException{
              //Process the HTTP Get request
              public void doGet( HttpServletRequest request, HttpServletResponse
              response ) throws ServletException, IOException{
              String username = "";
              if( request.getUserPrincipal() == null ){
              username = "Unknown";
              } else {
              username = request.getUserPrincipal().getName();
              System.err.println( "ePics logging out '" + username + "'" );
              request.getSession( false ).invalidate();
              ServletAuthentication.logout( request );
              ServletAuthentication.invalidateAll( request );
              ServletAuthentication.killCookie( request );
              response.sendRedirect( request.getContextPath() );
              //Process the HTTP Post request
              public void doPost( HttpServletRequest request, HttpServletResponse
              response ) throws ServletException, IOException{
              doGet( request, response );
              //Clean up resources
              public void destroy(){
              First of all, why won't the isNew() report a new session in the server log?
              EVERY request coming in says it's an old request (ie it's not new). The
              J2EE Applications and BEA WebLogic Server book from BEA says this should
              work.
              My second question is why do I need to do those three lines from
              ServletAuthentication to logout a user? Ok, maybe I'm from the MS world,
              but that seems excessive, especially since I've already done a
              session.invalidate() right before it, but the bea docs say I'm required to
              do all four!
              

    When you invalidate a session. You invalidate the session of the web
              application that your jsp/servlet is part of. It is possible to have more
              than one web application on WLS and have them share a authentication info.
              While these applications share authentication they do not share their
              sessions so because of that calling session invalidate does not kill all the
              sessions. ServletAuthentication is needed to kill all the sessions and do a
              complete logout from WLS.
              "Flip" <[remove][email protected]> wrote in message
              news:[email protected]...
              > I have coded an include jsp like this.
              >
              > <%@page language="Java"%>
              > <%@page import="javax.servlet.http.HttpSession"%>
              > <%!
              > String iContextPath;
              > String iCommonPath;
              > String iImagesPath;
              > %>
              > <%
              > iContextPath = request.getContextPath();
              > iCommonPath = iContextPath + "/common";
              > iImagesPath = iCommonPath + "/images";
              >
              > System.err.println(" here ");
              > HttpSession thisSession = request.getSession( false );
              > if( thisSession.isNew() ){
              > System.err.println("isnew");
              > response.sendRedirect( iContextPath + "/common/login.jsp" );
              > }
              >
              > %>
              >
              > Now I also have a redirect.jsp in the root of an application that contains
              > this.
              > <html>
              > <body>
              > <%
              > System.err.println("Redirecting at this time from the root");
              > response.sendRedirect( request.getContextPath() + "/secureArea/");
              > %>
              > </body>
              > </html>
              >
              > And I have a logout.java servlet that looks like this.
              > package com.pch.epics;
              >
              > import java.io.IOException;
              > import javax.servlet.ServletException;
              > import javax.servlet.http.HttpServlet;
              > import javax.servlet.http.HttpServletRequest;
              > import javax.servlet.http.HttpServletResponse;
              > import weblogic.servlet.security.ServletAuthentication;
              >
              > public class Logout extends HttpServlet{
              > private static final String CONTENT_TYPE = "text/html";
              > //Initialize global variables
              > public void init() throws ServletException{
              > }
              >
              > //Process the HTTP Get request
              > public void doGet( HttpServletRequest request, HttpServletResponse
              > response ) throws ServletException, IOException{
              > String username = "";
              > if( request.getUserPrincipal() == null ){
              > username = "Unknown";
              > } else {
              > username = request.getUserPrincipal().getName();
              > }
              > System.err.println( "ePics logging out '" + username + "'" );
              > request.getSession( false ).invalidate();
              > ServletAuthentication.logout( request );
              > ServletAuthentication.invalidateAll( request );
              > ServletAuthentication.killCookie( request );
              > response.sendRedirect( request.getContextPath() );
              > }
              >
              > //Process the HTTP Post request
              > public void doPost( HttpServletRequest request, HttpServletResponse
              > response ) throws ServletException, IOException{
              > doGet( request, response );
              > }
              >
              > //Clean up resources
              > public void destroy(){
              > }
              > }
              >
              > First of all, why won't the isNew() report a new session in the server
              log?
              > EVERY request coming in says it's an old request (ie it's not new). The
              > J2EE Applications and BEA WebLogic Server book from BEA says this should
              > work.
              >
              > My second question is why do I need to do those three lines from
              > ServletAuthentication to logout a user? Ok, maybe I'm from the MS world,
              > but that seems excessive, especially since I've already done a
              > session.invalidate() right before it, but the bea docs say I'm required to
              > do all four!
              >
              >
              >
              

  • Why do i need to declate methods two times for this program work

    Hi,
    why should i have to declare 2 times the methods
    public void mouseClicked(MouseEvent e) {    }
    public void mousePressed(MouseEvent e) {    }
    public void mouseReleased(MouseEvent e) {    }
    public void mouseEntered(MouseEvent e) { }
    public void mouseExited(MouseEvent e) {  }
    to make this program work? why when i declate 1 time this program doesn't work good?
    import java.awt.*;*
    import javax.swing.;
    import java.awt.datatransfer.*;
    import java.io.FileReader;
    import java.io.IOException;
    import java.awt.event.MouseListener;
    import java.awt.event.MouseEvent;
    public class Main extends JPanel implements MouseListener {
    public Main() {
    super(new GridLayout(2,2));
    final JTextArea jt= new JTextArea("dear test :) ",5,20);
    FileReader reader = null;
    System.err.println("Error closing reader");
    exception.printStackTrace();
    JButton bu = new JButton("copiar");
    final Clipboard clipboard = getToolkit().getSystemClipboard();
    //new add
    add(nn);
    add(tt);
    bu.addMouseListener(new MouseListener() {
    public void mouseEntered(MouseEvent e) {
    StringSelection data = new StringSelection(jt.getText());
    clipboard.setContents(data, data);
    public void mouseClicked(MouseEvent e) {
    public void mousePressed(MouseEvent e) {
    public void mouseReleased(MouseEvent e) {
    public void mouseExited(MouseEvent e) {
    private static void createAndShowGUI() {
    //Create and set up the window.
    JFrame frame = new JFrame("TextDemo");
    public static void main(String[] args) {
    //Schedule a job for the event dispatch thread:
    //creating and showing this application's GUI.
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
    public void run() {
    createAndShowGUI();
    public void mouseClicked(MouseEvent e) {    }
    public void mousePressed(MouseEvent e) {    }
    public void mouseReleased(MouseEvent e) {    }
    public void mouseEntered(MouseEvent e) { }
    public void mouseExited(MouseEvent e) {  }
    }

    import java.awt.;
    import javax.swing.;
    import java.awt.datatransfer.*;
    import java.io.FileReader;
    import java.io.IOException;
    import java.awt.event.MouseListener;
    import java.awt.event.MouseEvent;
    public class Main extends JPanel implements MouseListener {
    public Main() {
    super(new GridLayout(2,2));
    final JTextArea jt= new JTextArea("dear test :) ",5,20);
    FileReader reader = null;
    System.err.println("Error closing reader");
    exception.printStackTrace();
    JButton bu = new JButton("copiar");
    final Clipboard clipboard = getToolkit().getSystemClipboard();
    //new add
    add(nn);
    add(tt);
    bu.addMouseListener(new MouseListener() {
    public void mouseEntered(MouseEvent e) {
    StringSelection data = new StringSelection(jt.getText());
    clipboard.setContents(data, data);
    public void mouseClicked(MouseEvent e) { }
    public void mousePressed(MouseEvent e) { }
    public void mouseReleased(MouseEvent e) {}
    public void mouseExited(MouseEvent e) { }
    private static void createAndShowGUI() {
    //Create and set up the window.
    JFrame frame = new JFrame("TextDemo");
    public static void main(String[] args) {
    //Schedule a job for the event dispatch thread:
    //creating and showing this application's GUI.
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
    public void run() {
    createAndShowGUI();
    public void mouseClicked(MouseEvent e) { }
    public void mousePressed(MouseEvent e) { }
    public void mouseReleased(MouseEvent e) { }
    public void mouseEntered(MouseEvent e) { }
    public void mouseExited(MouseEvent e) { }
    } the problem is this line bu.addMouseListener(new MouseListener() {
    if i change this to bu.addMouseListener(this() {
    it gives error saying expected ')'
    and then doesn't compile.
    i just don't know why , although the program runs when i declare the methods two times,
    but i think it's better java code , if i learn it why is this error and correct it

  • Private static method accessed from main, please explain

    hi,
    i dont understand what happened with this code:
    static means you dont have to have an object to call the method - fine.
    but private means that the method is only available within the class,
    so how can one call the method initLookAndFeel() from main?
    public class Converter{
       //constructors etc...
       private static void initlookAndFee(){/* do stuff */}
    }//end of class converter
    public static void main( String args[]){
       initLookAndFeel(); ///????????????????????????????????????
       Converter converter = new Converter();
    }//end of main

    ...dang those stupid SMALL parenthesis!
    yes, main IS within the class converter... doh!
    thanx. M.

  • How to call a static method in a class if I have just the object?

    Hello. I have an abstract class A where I have a static method blah(). I have 2 classes that extend class A called B and C. In both classes I override method blah(). I have an array with objects of type B and C.
    For every instance object of the array, I'm trying to call the static method in the corresponding class. For objects of type B I want to call blah() method in B class and for objects of type C I want to call blah() method in C class. I know it's possible to call a static method with the name of the object, too, but for some reason (?) it calls blah() method in class A if I try this.
    So my question is: how do I code this? I guess I need to cast to the class name and then call the method with the class name, but I couldn't do it. I tried to use getClass() method to get the class name and it works, but I didn't know what to do from here...
    So any help would be appreciated. Thank you.

    As somebody already said, to get the behavior you
    want, make the methods non-static.You all asked me why I need that method to be
    static... I'm not surprised to hear this question
    because I asked all my friends before posting here,
    and all of them asked me this... It's because some
    complicated reasons, I doubt it.
    the application I'm writing is
    quite big...Irrelevant.
    Umm... So what you're saying is there is no way to do
    this with that method being static? The behavior you describe cannot be obtained with only static methods in Java. You'd have to explicitly determine the class and then explicitly call the correct class' method.

  • Apply static method requirements on class (Static interface methods)?

    I have a set of classes where is class is identified with a unique ID number. So each class has a public static int getId() method. Each class also has either a constructor that takes a byte array or a static factory method that takes a byte array.
    I would like to maintain a hashmap of these classes keyed to the ID's however I am not sure how to have some interface of abstract parent class that requires each of these classes to implement these static methods.
    What I was hoping to do was something like this>>>
         public interface MyClasses{
              static MyClasses createInstance(byte[] data);
         HashMap<Integer, MyClasses> map;
         public void init() {
              map = new HashMap<Integer, MyClasses>();
              map.put(Class1.getId(), Class1.class);
              map.put(Class2.getId(), Class2.class);
         public void createInstance (int id, byte[] data) {
              map.get(id).createInstance(data);
         }Is there some way I could do this?

    What about something like this?
    public interface Initializable
         public void initialize(byte[] data);
    public class Factory
         private final Map<Integer, Initializable> map = new HashMap<Integer, Initializable>();
            public void registerClass(int id, Class klass)
                    if (! Initializable.class.isAssignableFrom(klass))
                             // you may also want to ensure the class declares a parameterless constructor
                             throw new IllegalArgumentException("duff class");
                    if (this.map.keySet().contains(id))
                             throw new IllegalArgumentException("duff id");
              this.map.put(id, klass);
         public Initializable createInstance(int id, byte[] data)
                    // need some exception handling of course
              Initializable i = map.get(id).newInstance();
                    i.initialize(data);
                    return i;
    }

Maybe you are looking for

  • New printer and monitor combination

    My Epson 5800 and 4200 printers both died at the same time, and shortly afterward my MAG/Innovision 17" monitor also. I replaced both printers with the Epson Artisan 725 AIO and the monitor with a Dell 2320L LED LCD. Printers from Staples with a doub

  • Link to specific text from another web page

    Hello all Is is possible to link from one page to a specific piece of text in another web page in the same site? I have tried named anchor, hyperlink, etc but it just goes to the page rather than the text. I don't know if I am attempting the impossib

  • Custom xml report errored with :emsg:was terminated by signal 4

    Friends, one of the custom report errored out with the below error: Current NLS_LANG and NLS_NUMERIC_CHARACTERS Environment Variables are : American_America.UTF8 stat_low = 84 stat_high = 0 emsg:was terminated by signal 4 Program was terminated by si

  • Macbook Pro charger static noise

    So I have been looking at the different discussions about why some macbook pro chargers are making a static noise while connected to the mac, but none of these really fit my situation. For some reason when I plug in the charger in an outlet that is h

  • Problem in SMPP Driver configuration.

    Hello , I have developed the bpel process for sending SMS using 11g R1 and want to configure SMPP driver in soa_server1, For that please let me know what steps I have to follow, I dont have regestration over SMSC, where should I get free accountid, s