Classes and Static

1. i have Class a, this has static main
2. i have Class Conn, this connects the DB
3. i have Class Men, has Methods
4. i Create in Class Conn a Vector from Class Men.
5. main is static. i call Conn in main.
6. java doesnt allow me to call Conn from main if Conn methods are not Static.
7. ok i made Conn methods static.
8. now: if i want to call the Vector of Men Class in Conn Class. i cant. i have to make Men Class also Static.
9. well greate java. everything must get Static!!!! hmm.
whats the solution?
thx

I agree that you are probably best helped by reading an introduction to Java programming.
The "main" thing in this case is that you shouldn't try to do everything directly from your main method. In your class a (which should by convention be called A, or better yet, something a little more descriptive), you have a main method that is used to start your application. This method should look something like this:public static void main(String[] args) {
   A myApplication = new A();
   a.performDuties(); // this is a method you have to create
}That's it, no more. The method performDuties() (which is NOT static) will do all the work.

Similar Messages

  • Singleton pattern class and static class

    Hi,
    what is difference between the singleton pattern class and static class ?
    in singleton pattern, we declare a static member[which hold one value at a time] ,static method[ which return static member value] and a private constructor[not allow to direct instantiation]. My words are -- as a singleton pattern we implement static class .
    so can we say a singleton pattern is static class it means both are same or is any difference between these two ??

    malcolmmc wrote:
    On several occasions I've had to convert a static (never instanceated) class to a singleton type, for example because I realise I need an instance per thread, or I decide to make a program more modular, with more than one configuration.
    I've never done the opposite.
    So generally I favour the singleton if there any "state" involved, because it's more flexible in unanticipated directions. It also gives extra flexibility when building tests, especially if you program to an interface.Total agreement; if anything it is dead hard to override static method logic with mock code in unit tests (I had to do it by keeping the static methods in place but making them internally use a singleton instance of itself of which the instance variable could be overwritten with a mock implementation for unit testing purposes...).
    'Static classes' and/or methods are great for very simple util functions, but I wouldn't use them for anything other than that.

  • Nested Classes and Static Methods

    I was perusing the Java Tutorials on Nested Classes and I came across this...
    [http://java.sun.com/docs/books/tutorial/java/javaOO/nested.html|http://java.sun.com/docs/books/tutorial/java/javaOO/nested.html]
    I was reading the documentation and I read a slightly confusing statement. I was hoping some further discussion could clarify the matter. The documentation on "Nested Classes" says (I highlighted the two statements, in bold, I am having trouble piecing together.)
    Static Nested Classes
    As with class methods and variables, a static nested class is associated with its outer class. And like static class methods, a static nested class cannot refer directly to instance variables or methods defined in its enclosing class ? it can use them only through an object reference.
    Note: A static nested class interacts with the instance members of its outer class (and other classes) just like any other top-level class. In effect, a static nested class is behaviorally a top-level class that has been nested in another top-level class for packaging convenience.
    So this means a nested static inner class CANNOT refer to its own instanced variables, like a normal static method, but CAN refer to its outer class instanced variables?

    So this means a nested static inner class CANNOT refer to its own instanced variables, like a normal static method, but CAN refer to its outer class instanced variables?No, it means that a static nested class cannot refer to instance variables of its enclosing class. Example:public class Foo {
        int i;
        static class Bar {
            int j = i; // WRONG! Bar class is static context
    }~

  • Abstract classes and static methods

    I have an abstract report class AbstractReportClass which I am extending in multiple report classes (one for each report, say ReportA, ReportB, ...). Each report class has its own static column definitions, title, etc., which I have to access through a static method getDataMeta() in a web application. Each report has the same exact code in getDataMeta, and no report may exist without these fields. My intuition tells me that AbstractReportClass should contain the code for getDataMeta, but I know that you can't mix abstract and static keywords.
    Am I missing a simple solution to unify the getDataMeta code in the abstract base class? or do I really need to have a static function getDataMeta with the same code in each of the base classes?
    My apologies if this has been discussed many times before.
    Thanks,
    -Andrew

    I'm not trying to be "right"; rather I just asked a question about whether I can do something that seems intuitive. Perhaps you might write code in a different way than I would or perhaps I wasn't clear about every little detail about my code? Do you regularly belittle people who ask questions here?
    I have a loadFromDB() member function in AbstractReport for which all sub classes have an overloaded version. All reports I'm displaying have 4 common fields (a database id and a name and a monetary value, for example), but then each other report has additional fields it loads from the database. Inside ReportX classes' loadFromDB(), I call the superclass loadFromDB() function and augment values to get a completely loaded object. In fact, the loadedData member object resides in AbstractReport.
    I can't use a report unless it has these common features. Every report is an AbstractReport. There is common functionality built on top of common objects. Isn't this the point of inheritance? I'm essentially saying that abstract class Shape has a getArea function and then I'm defining multiple types of Shapes (e.g. Rectangle and Circle) to work with...

  • Private inner class and static private inner

    Hi,
    I understand the concept and usage of inner classes in general.
    When should we go for a private inner class and when for a static private inner class? I tried searching but it wasn't of much help.
    Basically I need to design a caching solution in which I need to timestamp the data object. After timestamping, data will be stored in a HashMap or some other collection. I'm planning to use a wrapper class (which is inner and private) which holds the data object and timestamp. I can make the program work by using either normal inner class or static inner class, however would like to know which is better in such case. Also If I can get some general guidelines as to when to use a staic inner class and when to use a normal inner class, it would help me.
    Thanks in advance.

    user1995721 wrote:
    When should we go for a private inner class and when for a static private inner class?
    I can make the program work by using either normal inner class or static inner class, however would like to know which is better
    If I can get some general guidelines as to when to use a static inner class and when to use a normal inner class, it would help me.Making the inner class static is helpful in that it limits visibility.
    If the inner class needs to access non-static fields or methods from the containing class instance
    the inner class has to be non-static.

  • Factory class and static members

    I don't understand very well why sometimes you can find a factory class (for example for the xml parsers). What's its aim?
    And why sometuimes, instead of a constructor, some classes have only static methods that returns a reference to that object?
    Anyone can tell me?
    Thanks

    Static memebers can be used in places where instances of its enclosing class is not neccesary.Only a method is required to be executed. Let me tell you with an example,
    class ConnectionPool {
    public static giveConnection(int index) {
    In the above example, our objective is to use only the method public static giveConnection(int index) {} , and not any of the other attributes of this class. You have 2 ways to use this method : One is, you can instantiate ConnectionPool p = new ConnectionPool(); . Second is , just use ConnectionPool.giveConnection(2);
    The first solution may create instance and obstruct your performance. Seond one does not do that. All invokers of this method do not instantiate and occupy space.
    Usually, factory classes have static members. Because these classes are used as a supporting processing factory. Theses members can be considered as utility methods. Hence static property will better suit for them. This answer will also tell you that the use of constructors here is not neccessary.
    Hope this has helped you.
    Rajesh

  • Abstract class and static function

    Please tell me that why a static function can't be made abstract?
    Thanks.
    Edited by: RohitRawat on Sep 9, 2009 7:45 AM

    RohitRawat wrote:
    Please tell me that why a static function can't be made abstract?
    Thanks.Because the method belongs to the class.

  • Static class and clustering

              I have a static class that I use to cache some values during a batch process. The
              batch process uses a JMS queue to parcel our identical units of work to MDBs.
              I want this to scale using a cluster with the same MDBs on multiple machines.
              Everything works fine except that I can't figure out how to tell my cache to clear
              itself out on every node between batch runs. Is there a pattern or solution to
              this problem?
              What I've tried is to create a stateless session bean method that clears my cache.
              At the begining of my batch job, (which is a stateless session bean call) I call
              this method on each server in the cluster by getting the remote interface for
              the stateless bean via the different URLs of the servers. However, the session
              bean method always executes on the one server where I make the call. It's as if
              WebLogic gives me back a local interface instead of the remote interface that
              I asked for.
              Any ideas would be appreciated.
              Colin
              

    ... static class and static method.I have never heard of a thing called "static class". Perhaps you mean a class with only static members?
    My design approach (which is bound to needs of the moment and seldom to library-development or future re-use, since both is harder than most developers realize) is to develop straight without caring too much about static or not. When a method is done, debugged and works well, it happens that other objects access this method as well.
    It may happen that I just want to use this single method and almost nothing else of the object. If that is the case, I can start looking if it's a Good Thing(tm) to make the method static, so no object creation is needed just for the one method. Sometimes it can be done, sometimes not.
    But that's just me and you'll find quite a lot of coders that'll advice you to decide what's static and what not before you start coding. And that's as good an advice as most others you can get.
    In the end it's your decision, so start fiddling around and see what fits best for you.
    -T-

  • Purpose of declaring the method or class or static and as instance

    what is the purpose of declaring a method in a class or the class itself as static.
    Does it mean we cannot create a copy of that class or method if we declare it as static.
    if so then why do they dont want that class to be created as a copy ?
    Why do they want to declare a class as static
    please provide some conceptual undersatnding regarding the static and instance class with one example

    Static methods are often used for the implementation of utility methods. Please have a look at the class CL_ABAP_CHAR_UTILITIES for example.
    You use the methods of this class in the same way as you would use a function in ABAP (like
    LINES( itab )
    ). You use it in a static way because the functionality is always the same no matter in what context you are calling the function.
    The purpose of instance methods is that their logic is in some way related to an attribute of the object instance that you use to call it.
    For example, you create an instance of object PO (a purchase order) called MY_PO. Then the method
    MY_PO->ADD_POSITION
    would add a position to a concrete PO that has a unique number etc. But if the object has a static method DELETE_POSITION then it just deletes the current position of a PO, regardless on which concrete PO you are acting at the moment.
    I hope this clarifies it for you.
    Regards,
    Mark

  • Thread safe logging class, using final and static

    Hi,
    I'm looking through a logging class (which writes entries to a text file and so on) written by someone else, and I'm trying to determine whether it's thread-safe...
    Essentially the class looks like this:
    public final class Logger {
    private static FileOutputStream fout;
    private static PrinterWriter pout;
    private static final long MaxLength = 100000;
    static {
    /* basically checks size of logfile, if bigger than 100k, then copy it as bak, and start again */
    public void write(String msg) {
    /* write entry into log file */
    public void writeWithTimeStamp(string msg) {
    /* write entry with time stamp into log file */
    Now, I could be wrong, but I don't think that the class is thread-safe is it? in order to be thread-safe, I would have to use synchronized before write() and writeWithTimeStamp(), right?
    My confusion arises from the use of the keyword "final" at the top of the class. This class isn't being inherited (or rather, there's no reason for the class not to be inheritable)... so what is it's purpose, if there is one?!
    And my other question concerns the static block. But I need to describe the current setup first: The Logger class is being use by a file server. File server basically sits there, accepts socket connections from the outside, and takes text files and output them into a local directory. When a new socket connection is created, a new thread is created. As it stands right now, each thread instantiates its own Logger object which seems weird! Bringing me to my question which was, if each thread instantiates its own Logger object, the static block is only ran ONCE, regardless of how many threads (and therefore Logger objects) are created, right??
    And wouldn't it be a better idea to simply create only ONE Logger object and pass it by reference to all newly created threads as they are needed so that all threads access the same and only Logger object? (and therefore utilize sychronization)
    Thanks!

    In JDK 1.4, there are already classes written that do all of that work. Check out the docs for the java.util.logging package. Specifically, check out FileHandler (which can rotate log files if they are greater than a specified size) and LogRecord (which is a standardized way to store logging entries). I believe the class is threadsafe, it doesn't say it isn't. Try it and see. If not, you can easily make a threadsafe wrapper for it (or any class for that matter).
    The online documentation is at:
    http://java.sun.com/j2se/1.4/docs/api/index.html
    If you are curious, the simplest way to make any class threadsafe, if you don't want to or are not able to modify the class code itself is to define another class that calls methods of the original class, but that is synchronized.
    Example:
        // NonThreadSafe.java
        public class NonThreadSafe {
            public NonThreadSafe (String s) {
                // Constructor
            public void SomeMethod (int param) {
                // Do some important stuff here...
            public int AnotherMethod (boolean param) {
                // Do some more important stuff here...
        // ThreadSafeWrapper.java
        public class ThreadSafeWrapper {
            protected NonThreadSafe nts;
            public ThreadSafeWrapper (String s) {
                nts = new NonThreadSafe(s);
            public synchronized void SomeMethod (int param) {
                nts.SomeMethod(param);
            public synchronized int AnotherMethod (boolean param) {
                return nts.AnotherMethod(param);
            public NonThreadSafe GetNonThreadSafe () {
                return nts;
        };Unfortunately, ThreadSafeWrapper isn't derived from NonThreadSafe, so you are somewhat limited in what you can do with it compared to what you could do with NonThreadSafe. AFAIK, you can't override unsynchronized methods with synchronized ones.
    Another thing you could do is just write a method that writes to your logging class, and synchronize just that method. For example:
        // ThreadSafeLogger.java
        public class ThreadSafeLogger {
            public static synchronized void LogMessage (MyLogger log, String msg) {
                log.writeString(msg);
        // In another thread, far, far away:
            ThreadSafeLogger.LogMessage(theLog, "Blah");
            ...Hope that helps.
    Jason Cipriani
    [email protected]
    [email protected]

  • How do i create a static function in a class and implement ActionListener?

    i am trying to create a pop up dialog box in a seperate class.
    and i want to make the Function static, so that i only need to access it with the class name.
    But how do i have a ActionListener ?
    everything in a static function is static rite?

    import java.awt.*;
    import java.awt.event.*;
    public class StaticFunction
        Dialog dialog;
        private Panel getUIPanel()
            Button button = new Button("show dialog");
            button.addActionListener(new ActionListener()
                public void actionPerformed(ActionEvent e)
                    if(dialog == null)
                        dialog = OutsideUtility.showDialog("hello world");
                    else if(!dialog.isVisible())
                        dialog.setVisible(true);
                    else if(dialog.isVisible())
                        dialog.dispose();
                        dialog = null;
            Panel panel = new Panel();
            panel.add(button);
            return panel;
        private WindowListener closer = new WindowAdapter()
            public void windowClosing(WindowEvent e)
                System.exit(0);
        public static void main(String[] args)
            StaticFunction sf = new StaticFunction();
            Frame f = new Frame();
            f.addWindowListener(sf.closer);
            f.add(sf.getUIPanel());
            f.setSize(200,100);
            f.setLocation(200,200);
            f.setVisible(true);
    class OutsideUtility
        public static Dialog showDialog(String msg)
            Button button = new Button("top button");
            button.setActionCommand(msg);
            button.addActionListener(new ActionListener()
                public void actionPerformed(ActionEvent e)
                    Button button = (Button)e.getSource();
                    System.out.println(button.getActionCommand() +
                                       " from anonymous inner listener");
            button.addActionListener(new ButtonListener());
            Button anotherButton = new Button("bottom button");
            anotherButton.setActionCommand("another button");
            anotherButton.addActionListener(localListener);
            Panel north = new Panel();
            north.add(button);
            Panel south = new Panel();
            south.add(anotherButton);
            Dialog dialog = new Dialog(new Frame());
            dialog.addWindowListener(closer);
            dialog.add(north, "North");
            dialog.add(new Label(msg, Label.CENTER));
            dialog.add(south, "South");
            dialog.setSize(200,200);
            dialog.setLocation(425,200);
            dialog.setVisible(true);
            return dialog;
        private static WindowListener closer = new WindowAdapter()
            public void windowClosing(WindowEvent e)
                Dialog dialog = (Dialog)e.getSource();
                dialog.dispose();
        private static ActionListener localListener = new ActionListener()
            public void actionPerformed(ActionEvent e)
                Button button = (Button)e.getSource();
                System.out.println(button.getActionCommand() +
                                   " from localListener");
        private static class ButtonListener implements ActionListener
            public void actionPerformed(ActionEvent e)
                Button button = (Button)e.getSource();
                String ac = button.getActionCommand();
                System.out.println(ac + " from ButtonListener");
    }

  • SQL, static classes and sessionBeans

    Hi,
    my JSF-project has one static class where it handle all sql-queries and I asked me if that is the "best" solution.
    I.e. a User-Sessionbean call that static class to save his data into the user-sql-table. I asked myself, if it might not better to delete this static class and let the user-sessionbean save his data itself.
    If my webserver has 100 usersessions and 50 users save their data at same time, does the "static-sql-save-version" has only one sql-connection and 49 user have to wait in a queue? And with the "every-usersession-has-his-own-sql-save-method" I have got 50 DB connection at the same time?
    I hope you could help me :)
    Alex

    you will gain some bytes by merging all the static classes in one.
    you can create a ManagerTool.java class and write inside all the static methods ...

  • Static classes and variables

    Hello,
    I put all of my constants in an *{color:#3366ff}interface{color}* called Constants.java (I only put constants in this file) and when obfuscated the Constants.class file is removed from .jar and constants are inlined into classes this is Great! However, do I gain anything by placing all of my static methods into one class? Currently, there are all over the place and also I have classes that are already static like HttpMgr.java/ErrorMgr.java/InfoMgr.java I am thinking about merging these classes together with all static methods defined within the project. Do I gain or loss anything by doing this?
    Thanks!

    you will gain some bytes by merging all the static classes in one.
    you can create a ManagerTool.java class and write inside all the static methods ...

  • JVM and static members of classes

    Hello Experts,
    I have applet project. Recently I reorganized the code and I made so many class members "static".
    The applet starts from javascript link from browser. When I start it at first time, everythink is OK,
    but when I start it second time there is a problem with these static members(Actually they are dialogs,
    panels, vectors and s.o.) They are saved in the memory in some way. When I close the parent browser(the browser
    that holds the javascript link) and then start again, everything is OK, because I starting applet for
    first time.
    How can I make the following calls like the first one ?
    Please help me !
    Best Regards,
    Valeri

    When u are opening a browser the static variables
    are persistance unless u closed the window.
    so while u are opening the second time the
    static variables are not initalizing.
    so if u remove the static .
    Or after displaying the applet u initialize the
    staic variable.

  • Difference between a static class and singleton

    What is the difference between a static object and a singleton ?
    for example:
    1 )
    public class MyObject {
    static MyObject singleton ;
    public static MyObject getInstance() {
    if (singleton ==null) singleton = new MyObject ();
    return singleton;
    private MyObject () {
    supe();
    public void myMethod() {
    2 )
    public class MyObject {
    private MyObject () {
    supe();
    public static void myMethod() {
    If I need to call the myMethod() , witch of this solution is better ?
    // case 1
    MyObject.getInstance().myMethod()
    // case 2
    MyObject.myMethod()
    .....

    This has been discussed a lot here.
    Use the forum's search feature, or, since it's not necessarily reliable, use google.
    For many intents and purposes, they're equivalent.
    However, with a singleton you can implement an interface, and get polymorphic behavior. You can't do with with a class full of static methods (which, by the way, is NOT a static class).

Maybe you are looking for

  • Can't add new image field in SRM MDM catalog

    Dear Experts I have added a new lookup[image] field in Catalog Item table. The problem is I cant find it in my MDM_SRM_UI_App>Customize Display tab>SRM-MDM Repository fields list Can't we add custom fields to repository? I also read this SAP Note 102

  • Help with spry menu

      HI guys, very good forum! I am new to web design.. I am trying to build a web but i can not figure out how can get the menu button stay in diferent colour when is clicked and page changed. I will give you examples http://www.slugandlettuce.co.uk/  

  • Setup single instance of  Oracle B2B to handle both HTTP as well as HTTPS r

    Hi, I want to send 850 transaction to different trading partner who are using HTTP and HTTPS.I want to create a single instance of ORACLE B2b to handle both HTTP and HTTPS. Please do the needful. Thanks and Regards Srinivas kola Edited by: user113425

  • How to set multi fonts in one textItem?

    I have a textItem with Chinese & English. I want to set Chinese and English in different fonts, but the script can only set one font. So, when I set the textItem in western fonts, the Chinese can't display correctly (display block). When I set it to

  • EXEC SQL

    Hi, What does an EXEC SQL stmt do in ABAP? What is the disadvantage of using it? Regards, Kalai