Use of the static keyword in this context?

Hi all

I have an application that has a class I want that all the other classes to access them. I'm not sure is how implement it correctly or it even happen. For example, consider the following:

Main class
public class Main {

    public static void main(String[] args) {
        new Main();
    }

    static SecondClass secondClass = new SecondClass();

    public Main() {
        
    }

}
Second class
public class SecondClass {

    public void method() {
        System.out.println("Method in Second Class");
    }
}
Third class
public class ThirdClass {

    public void doSomething() {
        //is this appropriate?
        Main.secondClass.method();
    }
}
Now I know that I could just pass an instance of the second class to all classes that need to use the second class, but I thought it would be easier to declare the second static class instance so that I could do the following to access easily given that I only ever need one instance of the class :
Main.secondClass.method();
So my question is, this approach would be appropriate or it is badly perceived to access a class in this way?
Thank you. :)

I know that my problem would be solved if all of these classes were in a class

No, your project is too important so a class... it has too many different types of objects.

Neptune, I see that your project suffers from the poor class design. It seems obvious to me that you DON'T know what must do your application, you know what it should look like, you know that you listen to the clicks of a mouse, you know you need thumbnails etc etc. But none of this will work if the data is not organized properly - and that will not happen if you do not know how each each object fits.

You develop this project to the rear. Start with data. It is. What are the data? How should be organized? What data should go to what class? etc. In addition, you must name your classes with intuitive names.

Since your project is essentially a Photo Viewer, I sggest you name your main class just that...

public class PhotoPreviewer
{
  Album[] albums;
}

... Notice the preview generator will now be able to access an array of objects from the Album. Now for the class from the Album...

public class Album
{
  String albumName;
  Photo albumPhoto;
  Photo[] photos;
}

... see how each album has now a name and a single object of Photo to represent it in the previewer? It also contains an array of Photo objects, which we will see now.

public class Photo
{
  URL url;
  BufferedImage image;
  BufferedImage thumbnail;
}

See how each picture maintains the URL, an image, and it's own miniature?

Now you can see what the data is and how the photos and Ablums of fit together to make the whole of the PhotoPreviewer project.

But with all these classes separated I'm not sure how to communicate properly.

Just add the combination of methods of accessor (GETTER and SETTER) as well as the methods of transmission as I described above.

Neptune, you see that you need start your projects based on the data it processes? Do not start a project of the graphic aspect and Auditors, managers and the buttons of the things... Start your projects with the data, and how these data fit. Once you get the data goes, THEN add graphics, pretty icons and a graphical interface.

Tags: Java

Similar Questions

  • − a valid license of the MODE of TRIAL will remove this message. See the property keywords of this PDF for more information.

    We recently purchased Adobe Acrobat Pro DC, however, that we were previously using a trial version, we get the message at the bottom of the documents ' MODE of ASSESSMENT − a valid license will remove this message. See the property keywords of this PDF for more information. "Is there a way to prevent the display of this message? The trial version has been removed before the installation of the purchased version.

    [Ask in the correct forum allows... Left the Premiere Pro for Acrobat... MOD]

    OK, the problem is that, even if you have purchased Acrobat Pro, you do not use it. You always use a free replacement product. Not only that, a free product in demo mode.

    When you go to print from the application, you must choose the Adobe PDF, not the PDF Creator printer.

  • How to use the referential cursor in this context

    Hello everyone I want to create a procedure and I am able to create it, but it does not work as I want it to be
    Please suggest the best way.
    CREATE OR REPLACE PROCEDURE UPDATE_COMMAND(V_TABLE_NAME VARCHAR2, V_COLUMN_NAME VARCHAR2)
    AS
    
    V_SQL CLOB;
    V_SQL_1 CLOB;
    TYPE V_SQL_2 IS REF CURSOR;
    V_SQL_22 V_SQL_2;
    V_SQL_23 VARCHAR2(2000);
    A clob;
    
    BEGIN
    
    V_SQL :='UPDATE '||V_TABLE_NAME ||'SET '||V_COLUMN_NAME ||' = ';
    
    V_SQL_23 := 'SELECT'|| V_COLUMN_NAME|| ' FROM ' ||V_TABLE_NAME;
    
    OPEN V_SQL_22 FOR V_SQL_23;
    
    loop
       FETCH V_SQL_22 INTO A;
     
      V_SQL_1 :=V_SQL | |V_COLUMN_NAME;
    
       dbms_output.put_line(v_sql_1);
       END LOOP;
       
       CLOSE V_SQL_22;
       
       END;
    first of all I don't know how to refer to this v_coluimn_name which I use just after the fetch command.

    When I run the procedure it gives error

    ORA-06550: line 1, column 22:
    PLS-00357: Table, view or reference sequence "QM_PRODUCT" not allowed in this context
    ORA-06550: line 1, column 7:
    PL/SQL: Statement ignored

    Prost wrote:
    I want the update command to be stored in a clob variable so that I can insert this variable in a column of a fictitious table, and then I'll get update of this table scripts manually.

    Well, what I gave just you out individual lines, so just adapt it to concatenate these lines in a CLOB variable for the loop process and then store you CLOB when finished. You should be able to handle that yourself.

    Still don't know why you want to do it right. Looks like a bad way to do something.

  • Unusual use of the static getInstance factory class definition interface

    This question is prompted by a recent new to Java forum question asking about the differences between Interfaces and abstract classes. Of course, one of the standard things mentioned is that interfaces can't actually implement a method.

    One of my former clients, the 500 group, using interfaces as class factories. The interface defines a static class of the pubis with a static method public, getInstance, who is called to generate instances of a class that implements the interface.

    This architecture was very object oriented, made good use of polymorphism and worked very well. But I have not seen this used anywhere architecture elsewhere, and it seemed a bit convoluted.

    Here's a version of 'Nick' of the model of the base interface and use
    -- interface that defines public static factory class and getInstance method
    public interface abc {
        public static class FactoryClass
        {
            public static abc getInstance ()
            {
                return (abc) FactoryGenerator(new abcImpl(), abc.class);
            }
        }
    }
    
    -- call of interface factory to create an instance
    abc myABC = abc.Factory.getInstance();
    1. each major functional area ('abc' in the above) has its own factory of interface
    2. each major functional area has its own implementation of this interface class
    3. There is a generator (FactoryGenerator) that uses the interface class ("abc.class") to determine the implementation to instantiate classes and return. The generator class can be configured at startup to control the actual class of return for a given interface.

    I should mention that the people who designed this whole architecture were not novices. They wrote very sophisticated multi-threaded code that rarely had problems, was high performance and was easy to extend to add new features (interfaces and classes of application) - pretty much plug-n-play with little, if any, side effects affecting existing modules.

    It is a process of best practices of factory design classes and methods? Please provide feedback about the use of an architecture like that.

    The way he explained to me at the time is that the interface uses standard naming conventions and acts as a template to make it easy to clone new modules: just change 'abc' to 'def' in three places and write a new class of "defImpl" which extends the interface and the new interface and the class can simply 'plug in' to the framework.

    There are in your pseudo code code in the interface to build a new abcImpl(). This deployment of a new plant means a change of this interface. If this is what is meant, it is poor. See java.util.ServiceLoader for an example of the right way to do it, with the implementation classes named in an external file.

    The generator class might use the information, if provided, to provide a new version of the class which would extend this default class.

    I hope so, but who is not exposed by your pseudocode.

    I never saw any 'Java' pattern that looks like this or any model where a contained interface a class.

    There are several examples in the JDK. Unfortunately I can't think of them right now. ;-)

    It seemed really complicated for me

    Me too.

    and it looks like the "versioning" aspect could be accomplished in a much simpler way.

    Indeed, he can see java.util.ServiceLoader.

  • Is the responsibility of the private sector in this context error

    QObject *listView = root->findChild("listView");
    listView->setProperty("dataModel", groupDataModel); //This line returns error: 'QVariant::QVariant(void*)' is private within this context 
    

    listView is a ListView declared in QML where groupDataModel is a declared GroupDataModel in C++.

    Any thoughts on what might have caused the error? I'm sorry if this question sounds stupid, Im just learn QML.
    Thank you

    Hello

    setProperty expected QVariant, but he could not find a constructor appropriate for storing QObject in QVariant.

    You can directly reference the ListView instead:

    ListView *listView = root->findChild("listView");
    listView->setDataModel(groupDataModel);
    
  • public static int panelHandle cannot be used with the extern keyword in another file



  • H4 element not allowed as child of the ul element in this context - better fix

    This page looks and works like I want to, but clearly, I broke the standards, so what is the best way to change to achieve the same thing?

    Case studies of promotional Marketing and service APTCOWEB Articles - news

    It seems it should be easy to penetrate the long ul of many courts, with headers between. But the way in which the styles are defined, I create new problems.

    Personally I would break the lists into manageable as pieces below:

    2015

    2014

    2013

    Then use the underside of css to style the h4:

    #main h4 {}

    color: #f6c238;

    background: #0d2b88;

    text-align: center;

    }

  • I used a link from the XI player who pointed out that I could get an edit function. I paid and have now no function but the periodic charge for this new feature. Please tell us how to fix this error.

    Hello. On the attached screen, there is an optional action box to change PDF to Acrobat Pro. However, when I clicked on the option - and paid for the new feature - I did not notice so that I can use this feature. When I open Adobe Reader XI, I always get the screen with the button, but no function activated, edit my automatic billing has been charged for July and August for this editing feature. I have cancelled the auto payments and want to correct the error. Do I need another product? Why have I not received notice that I was being charged every month? Thanks for responding.

    Jeanne

    Hi jeannem31310151,

    If it please download & install Acrobat DC using following the steps mentioned in this paper KB Acrobat DC subscription | Download and install.

    Refer to this KB document if you need assistance with editing PDF help Acrobat | Edit PDF files

    Kind regards

    Nicos

  • What's wrong with the dynamic region within the static region

    Hi all

    I use Jdeveloper 12 c

    I do app with a jsf page (man.jsf) contains the static region (xxx.jsff)

    the static region contains a dynamic region and I define the scope in the tent (adfc-config) (backingbean extended, scope of the request, see scope)

    the result is main.jsf is empty

    hand. JSF > > xxx.jsff (static region) > > bb.jsff (dynamic region)

    http://127.0.0.1:7101/face/hand? _afrLoop =

    What is the solution for this problem.

    Hello

    Actually the managed bean used by the static region should be extended to at least view. The managed bean should be defined in the configuration of the workflow of the static region.

    Frank

  • use of the server for executable files VI

    Hi all

    I tried to find a good explanation and example usage of VIserver to launch executables on client PC (XP) via a LAN to a PC (Win7) process controller. Basically, what I found for the controller is specified in this code snippet:

    The following was placed in the .ini file of the target at the time of construction to allow VIserver using an executable file (?):

    Server.TCP.Enabled = True
    Server.TCP.Access = "' + * '"
    Server.TCP.port = 3364
    Server.TCP.ACL = "290000000A000000010000001D00000003000000010000002A10000000030000000000010000000000"
    Server.VI.Access =""
    server.vi.callsEnabled = True
    server.vi.propertiesEnabled = True

    If a reference to an instance of application LV is open on the computer command on a specified port, and then a VI reference target

    for the .vi file (another instance?) opens on the same target for manipulation of knot VI. So what was lost for me is the executable

    I am trying to run the file. May not be wired to the terminal way to "ref Open VI". This implementation requires the .exe version and the version of VI

    I am trying to run the code? I launched with success of executable files over a LAN using plink with a script file. Problem is that I can't find a way

    get the target executables once loaded. There is most likely a C solution for this (I'll take it if anyone knows!), but since has VIserver of tools

    to control the execution, I would use it. Also, I want to understand the version of VI of the programme and the .exe in this case (s) link

    Version. Any help would be greatly appreciated.

    lb

    Ben OK,

    Your messages made me a technique to load with distance and running an exe file, built in LV8.5:

    1. to load: the controller emits a "tasklist" command to a target. The objective produces an output file of tasklist which is read by the controller. If it concludes that the target is already loaded, the controller will execute it with an invoke command node 'run a VI '.

    2. If the target is not loaded, then a script file is executed on the target via plink of the controller. This command will also start running.

    3. all the subVIs must reside on the target, as you said, even if (as in my case), the target has no LV Developer Suite installed. I placed Traoré versions of files and folders to exe in the same folder.

    4. the .ini file in the compilation has changed as shown in the first post of this thread. No special settings were used in the compilation.

    This probably isn't the exact technique you had in mind, but it doesn't seem to work... Thanks again for your help.

    lb

  • Use of the filter for the simplest needs Expression

    On the project I'm working on, I use rule Manager to evaluate hundreds of rules against the simple events based on a table alias (a line at a time, as the documents are). However, my needs are evolving to support multiple sets of rules that would be assessed against incoming data conditionally. It will also be managing versions of rulesets.

    These requirements do not appear to correspond to the way that rules Manager stores its rules, where all rows in a table of the Rule are always evaluated, and any creation of a new category of rule requires a new table, recall stored proc etc... I am mainly concerned about the proliferation of tables of the class rule I added new sets of rules. Given that I don't use any of the advanced features that offers of management rules on the Expression of basic filter functionality (for example the complex events), I'm looking for in a simple ExpFil of installation and use of the EVALUATION operator. This will allow me to store several rulesets in the same table of expressions (separated by a field of type or ruleset_id) and does not require as much structural work to add new sets of rules.

    Things seem to work very well in my first attempts, but I think that my main question is proc PROCESS_RULES of RM doesn't on the optimization of the assessment of the rules in the rule Manager - no additional optimization which is not offered by the basic functionality of ExpFil? Everything I do is a simple query to find the rules corresponding to a specific document:

    SELECT cr.*
    OF COMP_RULE_TEST cr, doct DOC_TABLE
    WHERE doct.doc_id = 123
    AND EVALUATE (cr. RULE_COND, FApprcomp.GetVarchar (doct.rowid)) = 1;

    Thank you!

    Hello

    Simple rules, there no notable performance only difference between Manager rules and filter expression. Please ensure that the indexes are created for the Expression column (they are automatically created for the rule Classes).

    Just to be complete: If you want to use several data structures and to define simple rules on the structures of the individual event, you can set a rule to structure class composite event and not really to define complex rules. For example, a rule configured for the table attributes class two alias, po and if maybe two simple rules that are associated with the simple event matching.

    Rule condition 1:
        
              itemName = 'Router' 
        
    
    Rule condition 2:
        
              destState = 'CA' 
            
    

    For a new line in the associated table of attribute "po", rules defined with the name of the corresponding event are evaluated.

    Hope this helps,
    -Aravind.

  • Why not use the static methods - example

    Hello world

    I would like to continue the below thread about "why not use static methods.
    Why not use the static methods
    with the concrete example.

    In my small application, I need to be able to send keystrokes. (java.awt.Robot class is used for this)
    I created the following class for these "operations" with static methods:
    public class KeyboardInput {
    
         private static Robot r;
         static {
              try {
                   r = new Robot();
              } catch (AWTException e) {
                   throw new RuntimeException(e + "Robot couldn't be initialized.");
              }
         }
         
         public static void wait(int millis){
              r.delay(millis);
         }
         
         public static void copy() {
              r.keyPress(KeyEvent.VK_CONTROL);
              r.keyPress(KeyEvent.VK_C);
              r.keyRelease(KeyEvent.VK_C);
              r.keyRelease(KeyEvent.VK_CONTROL);
         }
    
         public static void altTab() {
              r.keyPress(KeyEvent.VK_ALT);
              r.keyPress(KeyEvent.VK_TAB);
              r.keyRelease(KeyEvent.VK_TAB);
              r.keyRelease(KeyEvent.VK_ALT);
         }
    
                   // more methods like  paste(), tab(), shiftTab(), rightArrow()
    }
    You think it's a good solution? How could it be improved? I saw something Singleton vs somewhere of static methods. Wouldn't be better to use Singleton?

    Thanks for your comments in advance.
    lemonboston

    maheshguruswamy wrote:

    lemonboston wrote:

    maheshguruswamy wrote:
    I think a singleton might be a better approach for you. Just kill the public constructor, and provide a getInstance method to provide late initialization.

    Maheshguruswamy thanks for the tips on the steps create a singleton of this class.
    Perhaps you could say also why do you say that it would be preferable to use singleton? What is behind it? Thank you!

    In short, it seems to me that a single instance of your class will be able to coordinate actions across your entire application. If a singleton should be sufficient.

    But who doesn't answer why he expected prefer a singleton instead of a bunch of static methods. Functionally, the two are almost identical. In both cases, there is that a single 'thing' to call methods - either a single instance of the class or the class itself.

    To answer the question, the main reason to use a Singleton on a class of static methods is the same reason readers much of not static vs static decisions: polymorphism.

    If you use a Singleton (and and interface), you can do something like this:

    KeyboardInput kbi = get_some_instance_of_some_class_that_implements_KeyboardInput_somehow_maybe_from_a_factory();
    

    And then everything calling public methods of KBI has to know that there an implementor of this interface, without worrying about what concrete class is, and you can replace some implementation is appropriate in a given context. If you do not need to do, then the approach of the static method is probably enough.

    There are other reasons that may suggest a Singleton - serialization, persistence, use as a JavaBean pop to mind - but they are less frequent and less convincing in my experience.

    And finally, if this thing keeps updated a State between method calls, even if you can manage it with static member variables, it is more in line with the OO paradigm to make them non-static fields of an instance of this class.

  • "Movie Maker project file cannot be used in this context.

    I have created a slideshow of photos with music. When I use Windows Movie Maker and continue to publish my movie. I chose to publish my movie to a DVD. Then Movie Makers boot me and open DVD Maker. I try to put some audio in the background of the menu and it won't let me I get a error that says "Movie Maker project cannot be used in this context..." The heck that means and how to fix it?

    Help!

    When you import a Movie Maker project file directly from the film
    Manufacturer in DVD Maker I don't think you can continue to edit.

    Could you publish (save) the Movie Maker project in the. WMV
    Film format and then import them saved. WMV to DVD file
    Manufacturer and add other source files.

    Windows Vista - publish a movie in Windows Movie Maker
    http://Windows.Microsoft.com/en-us/Windows-Vista/publish-a-movie-in-Windows-Movie-Maker

    Movie Maker Vista - Edition
    http://www.Papajohn.org/Vista-publishing.html

  • Static ip configuration of the server. Is this possible?

    I wonder if I can put the static ip address to computers on the network without doing it manually. I use windows Server2008. Right now I have DHCP running, but I need static ip for all computers.

    Hey Nika,

    Thanks for posting your query in Microsoft Community.

    The Microsoft Answers community focuses on the context of use. Please reach out to the business community of COMPUTING in the TechNet forum below.

    http://TechNet.Microsoft.com/en-us/WindowsServer/bb310558.aspx

  • "missing the SELECT keyword" error during an insert into the temporary table using the blob value

    I'm trying to insert into an oracle temp table using select that retrieves data from a blob field but I get the error: "lack the SELECT keyword.

    How we store temporary in oracle result when we make this type of operation (extraction of data in fields and try to load them into a separate table on the fly.?)

    with cte as)

    Select user_id, utl_raw.cast_to_varchar2 (dbms_lob.substr (PREFERENCES)) as USER my_blob

    )

    create table new_table as

    SELECT user_id,EXTRACTvalue(xmltype(e.my_blob),'/preferences/locale') regional settings

    E ETC

    ----------------------------------------------------------------------------------

    BLOB data - value - which is

    <? XML version = "1.0" encoding = "ISO-8859-1" ?>

    - < Preferences >

    < time zone > America/New_York < / > zone

    < displayscheduleinusertimezone > Y < / displayscheduleinusertimezone >

    < local > Spanish < /locale >

    < DateFormat > JJ/mm/aaaa < / DateFormat >

    < timeFormat > hh: mm aaa < / timeFormat >

    < longformat > Long_01 < / longformat >

    < doubleformat > Double_01 < / doubleformat >

    < percentformat > Percentage_01 < / percentformat >

    < currencyformat > Currency_01 < / currencyformat >

    < / Preferences >

    A WITH clause that must immediately precede the SELECT keyword:

    SQL > create table t:

    2 with the o as (select double dummy)

    3 select * West longitude;

    Table created.

Maybe you are looking for