Accessing variables in a parent class?

Hello everyone,
I'm rather new to java, and I've been looking at the documentation a bit but am still trying to figure out just what I am looking for. I've posted an example of such before where I have two seperate files, the parent class file and the child class file. What I want to do is somehow return the instance of parent that child was created with from the below code.
public class parent {
     protected int var;
     public static void main(String[] args) {          
          child chld = new child();
}Is it possible to get the same instance of parent that created the child? If so, can it be used to access or modify the variables held by parent? Or is it only possible to do this by creating methods to set or get the value of the variable?
Can someone point me to the proper term as well, so as I might check the manual as well?

Another thing I just noticed; your question does not seem to match your post's subject title. Taking that into context, it is possible to read your post very differently. Do you mean that you want to reference parent from inside of its own method, not necessarily after it has returned?
You can access an object's variables and its methods from within a method it owns. To clarify what I mean...
public class Something
    int someData = 0;
    public void someAction()
        // Something has a variable "someData" which can be accessed directly from inside of Something's own method someAction()
        someData = 5;
        System.out.println(someData);
}If you mean you want a reference to the object itself from within one of its methods, Google for the "this" keyword.
None of these have anything to do with the child object though, so I'm still a bit stumped as to what exactly you mean. Perhaps a combination of all answers received so far?
Again, you probably need to further clarify exactly what you're looking for.

Similar Messages

  • Accessing subclass data when parent class is part of private data of another class.

    I am working up an OOP test program and have a problem with data access.
    I have the following classes defined:
    General Test
    General Report
    Specialized Test
    Specialized Report
    The Specialized Test and Specialized Report are subclasses of General Test and General Report, respectively.
    The General Test class contains a General Report class instance as part of it's private data.
    Specialized Test writes a Specialized Report to its parent class data on initialization. The Specialized Report contains additional data items in its private data.
    I have a method for Specialized Test where I first access the Report object stored in the General Test private data, then try to access the private data of the Specialized Report, that should be returned.I get a class mismatch, as the General Test accessor does not know it is returning a Specialized Report.
    Should I simply typecast the returned report to the more specific class before trying to access the subclass data as shown below, even though it will already be the more specific class?
    Thanks,
    Josh

    I don't see your image - maybe it just hasn't finished uploading yet - but if I'm understanding correctly, using To More Specific Class (not Type Cast) is a fine solution here. It's reasonable to use To More Specific Class to get the wire type to match the type of data that you know it will carry when the compiler cannot make that determination for you automatically.

  • Problems accessing child swf from parent class

    First off: Hi. I'm new - to the forum and to Flash.
    I'm currently writing a flash app that requests a XML feed
    from a Java controller and loads child swfs into various parts of
    the stage based on the settings/URL details received from the XML
    feed.
    Its nearly there and I've got my head round a couple of weird
    things, but theres one thing left that I've found impossible to
    solve. Once the loader class has loaded the swf, it can't access
    its methods or set its variables and the child can't access the
    parent either (or access the parent's variables full stop). From
    what I've read this should be possible. Heres some of my code plus
    pseudo code:
    Note the Panel class is not linked to a symbol and uses
    composition to act like a movie clip, rather than inheritance.
    quote:
    class Panel{
    function Panel(owner:MovieClip, insName:String,
    depth:Number){
    initiates properties etc....
    panelMovie = owner.createEmptyMovieClip(insName,depth);
    listener.onLoadComplete = mx.utils.Delegate.create(this,
    scheduleModule);
    loader.addListener(listener);
    loader.loadClip(moduleX.url, panelMovie);
    function scheduleModule(){
    trace(panelMovie.key);
    trace(panelMove.keyTest());
    panelMovie.key = "dave";
    trace(panelMovie.key);
    Child swf:
    quote:
    var key:String = "test";
    As you can see I create an empty movieclip which I store a
    reference to in this class under the field "panelMovie". I then use
    this (instead of target_mc like you might do with an event handler)
    to try to access the child swf. The output is:
    trace(panelMovie.key); = "test" (Works fine)
    trace(panelMove.keyTest()); = (Nothing returned)
    panelMovie.key = "dave";
    trace(panelMovie.key); = "test" (Previous line = no effect)
    Is this something related to using a class? Really would be
    preferentially to keep all code outside of the fla.
    I've also tried a lot of different combinations of _root,
    _parent and _levelx. None of which I truly understand.
    Any help would be much appreciated! Plus any good tutorial
    links on timeline and referring to objects in it!
    (Couldn't find the code tag/button...)

    >>trace(panelMove.keyTest()); = (Nothing returned)
    You have panelMove here instead of panelMovie
    Dave -
    Head Developer
    http://www.blurredistinction.com
    Adobe Community Expert
    http://www.adobe.com/communities/experts/

  • How to access variables declared in java class file from jsp

    i have a java package which reads values from property file. i have imported the package.classname in jsp file and also i have created an object for the class file like
    classname object=new classname();
    now iam able to access only the methods defined in the class but not the variables. i have defined connection properties in class file.
    in jsp i need to use
    statement=con.createstatement(); but it shows variable not declared.
    con is declared in java class file.
    how to access the variables?
    thanks

    here is the code
    * testbean.java
    * Created on October 31, 2006, 12:14 PM
    package property;
    import java.beans.*;
    import java.io.Serializable;
    public class testbean extends Object implements Serializable {
    public String sampleProperty="test2";
        public String getSampleProperty() {
            return sampleProperty;
    }jsp file
    <%@ page contentType="text/html;charset=windows-1252"%>
    <%@ page import="java.sql.*,java.util.*"%>
    <html>
    <head>
    <title>Schedule Details</title>
    </head>
    <jsp:useBean id="ConProp" class="property.testbean"/>
    <body>
    Messge is : <jsp:getProperty name="msg" property="sampleProperty"/>
    <%
      out.println(ConProp.sampleProperty);
    %>
    </body>
    </html>out.println(ConProp.sampleProperty) prints null value.
    is this the right procedure to access bean variables
    thanks

  • How to access the parent class variable or object in java

    Hi Gurus,
    I encounter an issue when try to refer to parent class variable or object instance in java.
    The issue is when the child class reside in different location from the parent class as shown below.
    - ClassA and ClassB are reside in xxx.oracle.apps.inv.mo.server;
    - Derived is reside in xxx.oracle.apps.inv.mo.server.test;
    Let say ClassA and ClassB are the base / seeded class and can not be modified. How can i refer to the variable or object instance of ClassA and ClassB inside Derived class.
    package xxx.oracle.apps.inv.mo.server;
    public class ClassA {
        public int i=10;
    package xxx.oracle.apps.inv.mo.server;
    public class ClassB extends ClassA{
        int i=20;   
    package xxx.oracle.apps.inv.mo.server.test;
    import xxx.oracle.apps.inv.mo.server.ClassA;
    import xxx.oracle.apps.inv.mo.server.ClassB;
    public class Derived extends ClassB {
        int i=30;
        public Derived() {
           System.out.println(this.i);                  // this will print 30
           System.out.println(((ClassB)this).i);  // error, but this will print 20 if Derived class located in the same location as ClassB
           System.out.println(((ClassA)this).i);  // error, but this will print 20 if Derived class located in the same location as ClassA
        public static void main(String[] args) { 
            Derived d = new Derived(); 
    Many thanks in advance,
    Fendy

    Hi ,
    You cannot  access the controller attribute instead create an instance of the controller class and access the attribute in the set method
    OR create a static method X in the controller class and store the value in that method. and you can access the attribute by 
    Call method class=>X
    OR if the attribute is static you can access by classname=>attribute.
    Regards,
    Gangadhar.S
    Edited by: gangadhar rao on Mar 10, 2011 6:56 AM

  • Access parent class?

    I'm just wondering if there's some way to access the class that instantiates a class from the instantiated class. Say if I had a class that has a Vector and creates a bunch of other classes that are added to the Vector. Is it possible for the instances of the class to access the Vector? I realize that this is poor OO, but I was just wondering if Java has some way of making this work, or if this just has "rethink idea" all over it... Thanks for your time.

    You can pass a reference variable pointing at the parent to the child object and store it there. Via this pointer you can reach the parent. It's common practice. This for example will print "parent". The parent just let go of the child but the child holds a reference to its parent,
    class Child {
       Parent parent;
       public Child (Parent p) {
          parent = p;
          parent.print();
    class Parent {
       public Parent () {
           new Child(this);
       public void print() {
          System.out.println("Parent");
    Parent p = new Parent();

  • Accessing variables from Child window from the parent window

    Hi All,
    I am in the process of integration of payment gateway, here I am opening payment gateway page as a new window, and after payment is done then I need access one variable which is hidden variable ...any ideas

    Have a hidden field/js variable in the parent page. Add a Javascript function in parent page which would take a value as parameter and set in the parent page hidden field/js variable. In the child window, you can invoke the method from script block as window.opener.setValue(document.getElementById('CHILD_WINDOW_HIDDEN_FIELD_ID').value)
    For Javascript related questions, please visit Javascript forums.

  • Accessing a variable defined in one class from another class..

    Greetings,
    I've only been programming in as3 for a couple months, and so far I've written several compositional classes that take MovieClips as inputs to handle behaviors and interactions in a simple game I'm creating. One problem I keep coming upon is that I'd love to access the custom variables I define within one class from another class. In the game I'm creating, Main.as is my document class, from which I invoke a class called 'Level1.as' which invokes all the other classes I've written.
    Below I've pasted my class 'DieLikeThePhishes'. For example, I would love to know the syntax for accessing the boolean variable 'phish1BeenHit' (line 31) from another class. I've tried the dot syntax you would use to access a MovieClip inside another MovieClip and it doesn't seem  to be working for me. Any ideas would be appreciated.  Thanks,
    - Jeremy
    package  jab.enemy
    import flash.display.MovieClip;
    import flash.events.Event;
    import jab.enemy.MissleDisappear;
    public class DieLikeThePhishes
    private var _clip2:MovieClip; // player
    private var _clip3:MovieClip; //phish1
    private var _clip4:MovieClip; //phish2
    private var _clip5:MovieClip; //phish3
    private var _clip6:MovieClip; //phish4
    private var _clip10:MovieClip; // background
    private var _clip11:MovieClip // missle1
    private var _clip12:MovieClip // missle2
    private var _clip13:MovieClip // missle3
    private var _clip14:MovieClip // missle4
    private var _clip15:MovieClip // missle5
    private var _clip16:MovieClip // missle6
    private var _clip17:MovieClip // missle7
    private var _clip18:MovieClip // missle8
    private var _clip19:MovieClip // missle9
    private var _clip20:MovieClip // missle10
    private var _clip21:MovieClip // missle11
    private var _clip22:MovieClip // missle12
    var ay1 = 0;var ay2 = 0;var ay3 = 0;var ay4 = 0;
    var vy1 = 0;var vy2 = 0;var vy3 = 0;var vy4 = 0;
    var phish1BeenHit:Boolean = false;var phish2BeenHit:Boolean = false;
    var phish3BeenHit:Boolean = false;var phish4BeenHit:Boolean = false;
    public function DieLikeThePhishes(clip2:MovieClip,clip3:MovieClip,clip4:MovieClip,clip5:MovieClip,clip6:M ovieClip,clip10:MovieClip,clip11:MovieClip,clip12:MovieClip,clip13:MovieClip,clip14:MovieC lip,clip15:MovieClip,clip16:MovieClip,clip17:MovieClip,clip18:MovieClip,clip19:MovieClip,c lip20:MovieClip,clip21:MovieClip,clip22:MovieClip)
    _clip2 = clip2;_clip3 = clip3;_clip4 = clip4;_clip5 = clip5;_clip6 = clip6;
    _clip10 = clip10;_clip11 = clip11;_clip12 = clip12;_clip13 = clip13;_clip14 = clip14;
    _clip15 = clip15;_clip16 = clip16;_clip17 = clip17;_clip18 = clip18;_clip19 = clip19;
    _clip20 = clip20;_clip21 = clip21;_clip22= clip22;
    _clip3.stage.addEventListener(Event.ENTER_FRAME, onEnterFrame)
    function onEnterFrame(event:Event):void
    vy1+= ay1;_clip3.y += vy1; vy2+= ay2;_clip4.y += vy2;
    vy3+= ay3;_clip5.y += vy3; vy4+= ay4;_clip6.y += vy4;
    if (phish1BeenHit ==false)
    if(_clip3.y >620)
    {_clip3.y = 620;}
    if (phish2BeenHit ==false)
    if(_clip4.y >620)
    {_clip4.y = 620;}
    if (phish3BeenHit ==false)
    if(_clip5.y >620)
    {_clip5.y = 620;}
    if (phish4BeenHit ==false)
    if(_clip6.y >620)
    {_clip6.y = 620;}
    if (_clip11.hitTestObject(_clip3) ||_clip12.hitTestObject(_clip3)||_clip13.hitTestObject(_clip3)||_clip14.hitTestObject(_cl ip3)||_clip15.hitTestObject(_clip3)||_clip16.hitTestObject(_clip3)||_clip17.hitTestObject( _clip3)||_clip18.hitTestObject(_clip3)||_clip19.hitTestObject(_clip3)||_clip20.hitTestObje ct(_clip3)||_clip21.hitTestObject(_clip3)||_clip22.hitTestObject(_clip3))
    _clip3.scaleY = -Math.abs(_clip3.scaleY);
    _clip3.alpha = 0.4;
    ay1 = 3
    vy1= -2;
    phish1BeenHit = true;
    if (_clip11.hitTestObject(_clip4) ||_clip12.hitTestObject(_clip4)||_clip13.hitTestObject(_clip4)||_clip14.hitTestObject(_cl ip4)||_clip15.hitTestObject(_clip4)||_clip16.hitTestObject(_clip4)||_clip17.hitTestObject( _clip4)||_clip18.hitTestObject(_clip4)||_clip19.hitTestObject(_clip4)||_clip20.hitTestObje ct(_clip4)||_clip21.hitTestObject(_clip4)||_clip22.hitTestObject(_clip4))
    _clip4.scaleY = -Math.abs(_clip4.scaleY);
    _clip4.alpha = 0.4;
    ay2 = 3
    vy2= -2;
    phish2BeenHit = true;
    if (_clip11.hitTestObject(_clip5) ||_clip12.hitTestObject(_clip5)||_clip13.hitTestObject(_clip5)||_clip14.hitTestObject(_cl ip5)||_clip15.hitTestObject(_clip5)||_clip16.hitTestObject(_clip5)||_clip17.hitTestObject( _clip5)||_clip18.hitTestObject(_clip5)||_clip19.hitTestObject(_clip5)||_clip20.hitTestObje ct(_clip5)||_clip21.hitTestObject(_clip5)||_clip22.hitTestObject(_clip5))
    _clip5.scaleY = -Math.abs(_clip5.scaleY);
    _clip5.alpha = 0.4;
    ay3 = 3
    vy3= -2;
    phish3BeenHit = true;
    if (_clip11.hitTestObject(_clip6) ||_clip12.hitTestObject(_clip6)||_clip13.hitTestObject(_clip6)||_clip14.hitTestObject(_cl ip6)||_clip15.hitTestObject(_clip6)||_clip16.hitTestObject(_clip6)||_clip17.hitTestObject( _clip6)||_clip18.hitTestObject(_clip6)||_clip19.hitTestObject(_clip6)||_clip20.hitTestObje ct(_clip6)||_clip21.hitTestObject(_clip6)||_clip22.hitTestObject(_clip6))
    _clip6.scaleY = -Math.abs(_clip6.scaleY);
    _clip6.alpha = 0.4;
    ay4 = 3
    vy4= -2;
    phish4BeenHit = true;
    if (_clip3.y > 10000)
    _clip3.x = 1000 +3000*Math.random()-_clip10.x;
    _clip3.y = 300;
    _clip3.alpha = 1;
    _clip3.scaleY = Math.abs(_clip3.scaleY);
    ay1 = vy1 = 0;
    phish1BeenHit = false;
    if (_clip4.y > 10000)
    _clip4.x = 1000 +3000*Math.random()-_clip10.x;
    _clip4.y = 300;
    _clip4.alpha = 1;
    _clip4.scaleY = Math.abs(_clip4.scaleY);
    ay2 = vy2 = 0;
    phish2BeenHit = false;
    if (_clip5.y > 10000)
    _clip5.x = 1000 +3000*Math.random()-_clip10.x;
    _clip5.y = 300;
    _clip5.alpha = 1;
    _clip5.scaleY = Math.abs(_clip5.scaleY);
    ay3 = vy3 = 0;
    phish3BeenHit = false;
    if (_clip6.y > 10000)
    _clip6.x = 1000 +3000*Math.random()-_clip10.x;
    _clip6.y = 300;
    _clip6.alpha = 1;
    _clip6.scaleY = Math.abs(_clip6.scaleY);
    ay4 = vy4 = 0;
    phish4BeenHit = false;
    var missleDisappear1 = new MissleDisappear(_clip11,_clip3,_clip4,_clip5,_clip6,_clip10);
    var missleDisappear2 = new MissleDisappear(_clip12,_clip3,_clip4,_clip5,_clip6,_clip10);
    var missleDisappear3 = new MissleDisappear(_clip13,_clip3,_clip4,_clip5,_clip6,_clip10);
    var missleDisappear4 = new MissleDisappear(_clip14,_clip3,_clip4,_clip5,_clip6,_clip10);
    var missleDisappear5 = new MissleDisappear(_clip15,_clip3,_clip4,_clip5,_clip6,_clip10);
    var missleDisappear6 = new MissleDisappear(_clip16,_clip3,_clip4,_clip5,_clip6,_clip10);
    var missleDisappear7 = new MissleDisappear(_clip17,_clip3,_clip4,_clip5,_clip6,_clip10);
    var missleDisappear8 = new MissleDisappear(_clip18,_clip3,_clip4,_clip5,_clip6,_clip10);
    var missleDisappear9 = new MissleDisappear(_clip19,_clip3,_clip4,_clip5,_clip6,_clip10);
    var missleDisappear10 = new MissleDisappear(_clip20,_clip3,_clip4,_clip5,_clip6,_clip10);
    var missleDisappear11 = new MissleDisappear(_clip21,_clip3,_clip4,_clip5,_clip6,_clip10);
    var missleDisappear12 = new MissleDisappear(_clip22,_clip3,_clip4,_clip5,_clip6,_clip10);

    I would approach it in much the same way as you would in java, by making getters and setters for all of your class variables.
    Getters being for returning the values, Setters being for setting them.
    So you would make a get function for the variable you want to access ala:
    function get1PhishBeenHit():boolean {
         return this.phish1BeenHit;
    Then to access the value of that variable from outwith the class:
    var result:boolean = ClassInstanceName.get1PhishBeenHit();

  • Accessing a Sub class variable in a Super Class

    Hi ,
    Is there any easiest way to access a Subclass Variable in a Super Class.
    Class Super1{
    Class sub extends Super1
    private String substring1;
    In my application the 'substring1' values is not null .But all fields in Super1 class are null .
    How can i access the value of the Subclass Variable in Super class .
    Thanks

    This would be a way to make the superclass dependent on subclass behavior. Of course this only makes sense if getSubString() is likely to have multiple different implementations in different subclasses.
    public abstract class Super {
      public String getString() {
       return "SuperString" + getSubString();
      protected abstract String getSubString();
    public class Sub extends Super {
      private String substring;
      protected String getSubString() {
       return substring;
    }Using this just to access a variable whose contents differ from subclass to subclass is overkill. If you want each subclass to provide a different substring, create a constructor with a substring parameter in the superclass instead:public class Super {
      private String substring;
      protected Super(String substring) {
       this.substring = substring;
      public String getString() {
       return "SuperString" + substring;
    public class Sub extends Super {
      public Sub() {
       super("substring");
    }

  • How to access the int variable in the inner class

    hi all,
    i can't access the int variable in the inner class. can any one help me
    int count = 0;
    MouseMoveListener mouseMove = new MouseMoveListener() {
         public void mouseMove(MouseEvent e) {
              count1++;
              System.out.println(count);
    };how to access count variable
    thanks

    for this how can i access the countIf the count variable is a local variable you can't access it from within the
    inner class. Make it a member variable of the outer class instead:public class Outer {
       private int count;
       MouseMoveListener mouseMove= new MouseMoveListener() {
          public void mouseMove(MouseEvent me) {
             count++;
             System.out.println(count);
    }Alternatively, if you don't need that count variable anywhere else, you
    could simply make it a member variable of the inner class itself:public class Outer {
       MouseMoveListener mouseMove= new MouseMoveListener() {
          private int count;
          public void mouseMove(MouseEvent me) {
             count++;
             System.out.println(count);
    }kind regards,
    Jos

  • Accessing String variables from several JAVA classes

    Hi.
    I have several java classes that accesses the same String variables. Instead of putting the String declarations in every java files, how can I put these declarations in a single file source, and get each java class to get the variables data from this file ?
    Please advice.
    Thanks.

    hi, of course you can solve it by the following methods:
    Method 1. define a superclass including the common string variable, and extend other classes from the superclass.
    Method 2. define a class , and define your common string variable as a static variable in it. In your other classes, you can call the string variable.
    Method 3. define it at your each classes.

  • Catch-22: need to assign a local variable within an anonymous class

    static boolean showMessage(Window parent, String button0, String button1)
        throws HeadlessException {
              final Window w = new Window(parent);
              Panel p = new Panel(new GridBagLayout());
              final Button b[] = new Button[]{new Button(button0), (button1 != null) ? new Button(button1) : (Button)null};
              boolean rval[]; //tristate: null, true, false
              w.setSize(100, 50);
              w.setVisible(true);
              //add b[0
              gbc.fill = GridBagConstraints.HORIZONTAL;
              gbc.gridx = 0;
              gbc.gridy = 3;
              p.add(b[0], gbc);
              //add b[1]
              if (button1 != null) {
                   gbc.fill = GridBagConstraints.HORIZONTAL;
                   gbc.gridx = 1;
                   gbc.gridy = 3;
                   p.add(b[1], gbc);
              w.add(p);
              w.pack();
            w.setVisible(true);
            //actionListener for button 0
              b[0].addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent e) {
                             if (e.getSource() == b[0]) {
                                  w.setVisible(false);
                                  rval = new boolean[1];
                                  rval[0] = true;
              //actionListener for button 1
              if (button1 != null) {
                   b[1].addActionListener(new ActionListener() {
                             public void actionPerformed(ActionEvent e) {
                                  if (e.getSource() == b[1]) {
                                       w.setVisible(false);
                                       rval = new boolean[1];
                                       rval[0] = false;
            while (true) {
                 try {
                      if (rval[0] == true || rval[0] == false) //should trigger NullPointerException
                           return rval[0];
                 } catch (NullPointerException e) { }
         }catch-22 is at
    rval = new boolean[1];
    rval = false;javac whines: "local variable rval is accessed from within inner class; needs to be declared final"
    How do I assign to rval if it's declared final?
    Or at the very least, how do I get rid of this error (by all means, hack fixes are okay; this is not C/C++, I don't have to use sanity checks)?
    I'm trying to make a messagebox in java without using JOptionPane and I'm trying to encapsulate it in one method.
    And I'm far too lazy to make a JNI wrapper for GTK.

    dcminter wrote:
    How do I assign to rval if it's declared final?You don't and you can't. You're not allowed to assign to the local variable of the outer class for extremely good reasons, so forget about trying.
    Or at the very least, how do I get rid of this errorIf you don't want the side effect, then just use an inner class variable or a local variable.
    If you want the side effect then use a named class and provide it with a getter and setter.
    Finally, in this specific case because you're using an array object reference, you could probably just initialise the array object in the outer class. I.e.
    // Outer class
    final boolean[] rval = new boolean[1];
    // Anonymous Inner class
    rval[0] = true; // No need to intialize the array.
    I declared it as an array so that it would be a tristate boolean (null, true, false) such that accessing it before initialization from the actionPerformed would trigger a NullPointerException.
    Flowchart:
    is button pressed? <-> no
    |
    V
    Yes->set and return
    Is there a way to accomplish this without creating a tribool class?

  • How to access variables??

    how to access public variables of any other class??
    suppose i have a file temp.java file ..& i know all the public variables. and
    i want to access the variable of those temp.class file which extends JApplet or Applet..
    and as u know it will declare public void init() .. & in this function only all declaration will be there.
    so now how to invoke this init() function from any mymethod()..to access public variables...

    its not working. for me..
    the variable which i m trying to access is non static.. its displays the error :
    Exception in thread "AWT-EventQueue-1" java.lang.Error: Cannot call invokeAndWait from the event dispatcher thread
    and by one method i have connected database also.. and it has been called from init()..
    i have collected the data from the database..and i m storing the data in one ArrayList ..
    and i want to access that ArrayList..

  • Using Variables/Arrays from one class in another

    Hello all,
    First, to explain what I am attempting to create, is a program that will accept input of employee names and hours worked into an array. The first class will accept a command line argument when invoked. If the argument is correct, it will call another class that will gather information from the user via an input box. After all names and hours have been input for employees, this class will calculate the salary based upon the first letter of each employee name and print the total hours, salary, etc. for each employee.
    What I need to do now is to split the second class into two: one that will gather the data and another that will calculate and print the data. Yes, this is an assignment. However, I am trying to learn and I have gotten this far, but I am stuck on how to get a class to be able to use an array/variables from another class.
    I realize the below code isn't exactly cleaned up...yet.
    Code for AverageSalaryGather class:
    import javax.swing.JOptionPane; // uses class JOptionPane
    import java.lang.reflect.Array;     
    import java.math.*;
    public class AverageSalaryGather {
         public static void gatherData() {     
              char[] alphaArray = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','x','y','z'};
              String[][] empInfoArray = new String[100][4];
              String[] empNameArray = new String[100];
              String finalOutput = "Name - Rate - Hours - Total Pay\n";
              String averageHoursOutput = "Average Hours Worked:\n";
              String averageSalaryOutput = "Average Hourly Salary:\n";
              String averageGroupSalaryOutput = "Average Group Salary:\n";
                        String[] rateArray = new String[26];
                        char empNameChar = 'a';
              int empRate = 0;
              int payRate = 0;
                        for (int i = 0; i < 26; i++) {
                   payRate = i + 5;
                   rateArray[i] = Integer.toString(payRate);
                        int countJoo = 0;
              while (true) {
                   String namePrompt = "Please enter the employee name: ";
                   String empName = JOptionPane.showInputDialog(namePrompt);
                                  if (empName == null | empName.equals("")) {
                        break;
                   else {
                        empInfoArray[countJoo][0] = empName;
                        for (int i = 0; i < alphaArray.length; i++) {
                             empNameChar = empName.toLowerCase().charAt(0);
                                                      if (alphaArray[i] == empNameChar) {
                                  empInfoArray[countJoo][1] = rateArray;
                                  break;
                        countJoo++;
              // DecimalFormat dollarFormat = new DecimalFormat("$#0.00");
              for (int i = 0; i < empInfoArray.length; i++) {
                   if (!(empInfoArray[i][0] == null)) {
                        String hourPrompt = "Please enter hours for " + empInfoArray[i][0] + ": ";
                        String empHours = JOptionPane.showInputDialog(hourPrompt);
                        int test = 0;
                        empInfoArray[i][2] = empHours;
                        // convert type String to double
                        //double tmpPayRate = Double.parseDouble(empInfoArray[i][1]);
                        //double tmpHours = Double.parseDouble(empInfoArray[i][2]);
                        //double tmpTotalPay = tmpPayRate * tmpHours;
                        // create via a string in empInfoArray
                             BigDecimal bdRate = new BigDecimal(empInfoArray[i][1]);
                             BigDecimal bdHours = new BigDecimal(empInfoArray[i][2]);
                             BigDecimal bdTotal = bdRate.multiply(bdHours);
                             bdTotal = bdTotal.setScale(2, RoundingMode.HALF_UP);
                             String strTotal = bdTotal.toString();
                             empInfoArray[i][3] = strTotal;
                        //String strTotalPay = Double.toString(tmpTotalPay);
                        //empInfoArray[i][3] = dollarFormat.format(tmpTotalPay);
                        else {
                             break;
              AverageSalaryCalcAndPrint averageSalaryCalcAndPrint = new AverageSalaryCalcAndPrint();
              averageSalaryCalcAndprint.calcAndPrint();
    Code for AverageSalaryCalcAndPrint class (upon compiling, there are more than a few complie errors, and that is due to me cutting/pasting the code from the other class into the new class and the compiler does not know how to access the array/variables from the gatherData class):
    import javax.swing.JOptionPane; // uses class JOptionPane
    import java.lang.reflect.Array;
    import java.math.*;
    public class AverageSalaryCalcAndPrint
         public static void calcAndPrint() {     
              AverageSalaryGather averageSalaryGather = new AverageSalaryGather();
              double totalHours = 0;
              double averageHours = 0;
              double averageSalary = 0;
              double totalSalary = 0;
              double averageGroupSalary = 0;
              double totalGroupSalary = 0;
              int countOfArray = 0;
              for (int i = 0; i < empInfoArray.length; i++) {
                   if (!(empInfoArray[0] == null)) {
                        totalSalary = totalSalary + Double.parseDouble(empInfoArray[i][1]);
                        totalHours = totalHours + Double.parseDouble(empInfoArray[i][2]);
                        totalGroupSalary = totalGroupSalary + Double.parseDouble(empInfoArray[i][3]);
                        countOfArray = i;
              averageHours = totalHours / (countOfArray + 1);
              averageSalary = totalSalary / (countOfArray + 1);
              averageGroupSalary = totalGroupSalary / (countOfArray + 1);
              String strAverageHourlySalary = Double.toString(averageSalary);
              String strAverageHours = Double.toString(averageHours);
              String strAverageGroupSalary = Double.toString(averageGroupSalary);
              for (int i = 0; i < empInfoArray.length; i++) {
                   if (!(empInfoArray[i][0] == null)) {
                        finalOutput = finalOutput + empInfoArray[i][0] + " - " + "$" + empInfoArray[i][1] + "/hr" + " - " + empInfoArray[i][2] + " - " + "$" + empInfoArray[i][3] + "\n";
              averageHoursOutput = averageHoursOutput + strAverageHours + "\n";
              averageSalaryOutput = averageSalaryOutput + strAverageHourlySalary + "\n";
              averageGroupSalaryOutput = averageGroupSalaryOutput + strAverageGroupSalary + "\n";
              JOptionPane.showMessageDialog(null, finalOutput + averageHoursOutput + averageSalaryOutput + averageGroupSalaryOutput, "Totals", JOptionPane.PLAIN_MESSAGE );

    Call the other class's methods. (In general, you
    shouldn't even try to access fields from the other
    class.) Also you should be looking at an
    instance of the other class, and not the class
    itself, generally.Would I not call the other classes method's by someting similar as below?:
    AverageSalaryCalcAndPrint averageSalaryCalcAndPrint = new AverageSalaryCalcAndPrint();
              averageSalaryCalcAndprint.calcAndPrint(); Well... don't break down classes based on broad steps
    of the program. Break them down by the information
    being managed. I'm not expressing this well...Could you give an example of this? I'm not sure I'm following well.
    Anyway, you want one or more objects that represent
    the data, and operations on that data. Those
    operations include calculations on the data. Other
    classes might represent the user interface, and
    different output types (say, a file versus the
    console).Yes, the requirements is to have a separate class to gather the data, and then another class to calculate and print the data. Is this what you mean in the above?

  • How to access a method of a class which just known class name as String

    Hi,
    Now I have several class and I want to access the method of these class. But what I have is a String which contain the complete name of the class.
    For example, I have two class name class1and class2, there are method getValue in each class. Now I have a String containing one class name of these two class. I want to access the method and get the return value.
    How could I do?
    With Class.forName().newInstance I can get a Object. but it doesn't help to access and execute the method I want .
    Could anybody help me?
    Thanks

    Or, if Class1 and Class2 have a common parent class or interface (and they should if you're handling them the same way in the same codepath)...Class c = Class.forName("ClassName");
    Object o = c.newInstance(); // assumes there's a public no-arg constructor
    ParentClassOrInterface pcoi = (ParentClassOrInterface)o;
    Something result = pcoi.someMethod(); Or, if you're on 5.0, I think generics let you do it this way: Class<ParentClassOrInterface> c = Class.forName("ClassName");
    // or maybe
    Class<C extends ParentClassOrInterface> c = Class.forName("ClassName");
    ParentClassOrInterface pcoi = c.newInstance();
    Something result = pcoi.someMethod();

Maybe you are looking for

  • How do I uninstall QT 7.1.3 on a MacBook Pro?!!

    How do I uninstall QT 7.1.3 on a MacBook Pro? It does not play nice with a very important piece of software I am using. The other post on how to "uninstall" does not apply to my situation. I tried it and got this error when using the 7.0.1 Reinstalle

  • TDS on Outgoing Payment

    Hi All, I have gone through many threads but not able to find proper solution for a general scenario which will be requirement of many customer. Scenario: Is very simple. I have make Payment to Vendor on Acount ( Advance Payment) on which i need to d

  • I cannot verify my credit card payments

    I bought iPad in uk airport and live in another country, when trying to buy apps, my credit card is rejected as not valid.  And help please

  • Schedule a SSRS report as step in SQL SERVER agent

    Hi All, The requirement is that can we schedule a job as a step in SQL Server Agent. Scenario: I got a SQL Agent job which got multiple steps. Executing SP's, running SSIS etc. The last setp i want to setup is run a SSRS report where it gives the rep

  • Easy DMS - Preferences lost

    Hi We have a couple of users that experience some issues with the "Preferences" in the EDMS gui. When they change some of the values i.e. "Timeout for the RFC Connection", the values alway change back to the old value. Certain users' EDMS GUI does no