OOP - access vars in classes

Another boring topic about classes. I know.
The thing is, that I want to know how to make a connections between classes for a large project. I have created a rpg game but it's start to be too complicated for a non OOP programming, so I have to transfer all of code into oop. So my question is how to architect classes for that project.
I know how to do visual things for example like enemies. Class AllEnemies take all general action for every enemy in a game. Different enemies extends main class AllEnemies ect. All that's pretty simple. But what to do, if I want create class that is not a representation of a display object like statistics? Lets say I have vars: xp, lvl, str. All that vars I want to change during the game in a different way and in a different place. So how to design a classes for that? Should I use global vars in a main document class ? Or should I create class Statistics and then extends that class in every other classes that needs that vars? But class can only extends one class, so that is going to limit my functionality. Or is it way to import class to another class and then refer to var inside it? And if so, how to do it? Because I tried that and there is an error that I want to refer to var that is not exist.
Thanks

I feel your question is not much about classes but application architecture. Although I am not a big fan of out of the box design patterns and frameworks, perhaps you should look into MVC as a concept of managing different aspects of application. MVC allows for separation of presentation, information and business logic - very important time tested approach in effective application development. In other words, your program should be highly modular.
As for the technical aspects of implementation, it depends on your application needs. You may need singleton pattern/static class features approaches or, with well thought out architecture, you can employ a registry/subscription model (when classes subscribe to particular services in your application - say information).
AS3 offers many convenient ways to make objects communicate. In particular, look into event model - this is a single important thing to understand about AS3 in order to implement modularity and sophisticated logic

Similar Messages

  • How to access var in outter class inside inner class

    I've problem with this, how to access var number1 and number2 at outter class inside inner class? what statement do i have to use to access it ? i tried with " int number1 = Kalkulator1.this.number1; " but there no value at class option var y when the program was running...
    import java.io.*;
    public class Kalkulator1{
    int number1,number2,x;
    /* The short way to create instance object for input console*/
    private static BufferedReader stdin =
    new BufferedReader( new InputStreamReader( System.in ) );
    public static void main(String[] args)throws IOException {
    System.out.println("---------------------------------------");
    System.out.println("Kalkulator Sayur by Cumi ");
    System.out.println("---------------------------------------");
    System.out.println("Tentukan jenis operasi bilangan [0-4] ");
    System.out.println(" 1. Penjumlahan ");
    System.out.println(" 2. Pengurangan ");
    System.out.println(" 3. Perkalian ");
    System.out.println(" 4. Pembagian ");
    System.out.println("---------------------------------------");
    System.out.print(" Masukan jenis operasi : ");
    String ops = stdin.readLine();
         int numberops = Integer.parseInt( ops );
    System.out.print("Masukan Bilangan ke-1 : ");
    String input1 = stdin.readLine();
    int number1 = Integer.parseInt( input1 );
    System.out.print("Masukan Bilangan ke-2 : ");
    String input2 = stdin.readLine();
    int number2 = Integer.parseInt( input2 );     
         Kalkulator1 op = new Kalkulator1();
    Kalkulator1.option b = op.new option();
         b.pilihan(numberops);
    System.out.println("Bilangan yang dimasukkan adalah = " + number1 +" dan "+ number2 );
    class option{
    int x,y;
         int number1 = Kalkulator1.this.number1;
         int number2 = Kalkulator1.this.number2;
    void pilihan(int x) {
    if (x == 1)
    {System.out.println("Operasi yang digunakan adalah Penjumlahan");
            int y = (number1+number2);
            System.out.println("Hasil dari operasi adalah = " + y);}
    else
    {if (x == 2) {System.out.println("Operasi yang digunakan adalah Pengurangan");
             int y = (number1-number2);
             System.out.println("Hasil dari operasi adalah = " + y);}
    else
    {if (x == 3) {System.out.println("Operasi yang digunakan adalah Perkalian");
             int y = (number1*number2);
             System.out.println("Hasil dari operasi adalah = " + y);}
    else
    {if (x == 4) {System.out.println("Operasi yang digunakan adalah Pembagian ");
             int y = (number1/number2);
             System.out.println("Hasil dari operasi adalah =" + y);}
    else {System.out.println( "Operasi yang digunakan adalah Pembagian ");
    }

    Delete the variables number1 and number2 from your inner class. Your inner class can access the variables in the outer class directly. Unless you need the inner and outer class variables to hold different values then you can give them different names.
    In future place code tags around your code to make it retain formatting. Highlight code and click code button.

  • Cannot access Graphics - bad class file

    Hey.
    When I try to compile my source I get an error saying...
    .\Man.java:146: cannot access Graphics
    bad class file: .\Graphics.java
    file does not contain class Graphics
    Please remove the files or make sure it appears in the correct subdirectory.
    It's on a different computer so that's not exactly it, but it's close enough. Compiler was working fine until the other day when i found out that all the source files were zipped up in src.zip, I had to extract Graphics.java so I could open it in emacs, and after I did that it started giving me that error message. There's nothhing wrong with my source, and I didn't move Graphics, it's still in the correct place exactly as it was, and i looked at it, all the right stuff is still inside. I'm quite confused.
    So do I have to reinstall? That would mean a massive download on my 56k and I kinda wanna carry on with my work.

    You should not need to unzip src.zip to use the Graphics class or any class that comes with j2sdk. The compiled classes are in jar files that are installed in certain directories when you install the j2sdk.
    You should only need to have a line "import java.awt.Graphics;" near the start of your source code.
    The error most likely occurred when the compiler found a Graphics.class file but inside the file is java.awt.Graphics class, not a plain Graphics class.

  • Why eclipse gives me warning if I access in inner class a parent  field ?

    I have a class
    class A{
    private Map fValues;
    A(){
    fValues= new HashMap();
    prrotected class B {
    B(){
    fValues.get("String");
    Above class is only for an example to expalin my problem.
    Inner class B wants to access fValues from class A .
    The eclipse gives me a warning
    Access to enclosing method fValues from the type A is emulated by a synthetic accessor method. Increasing its visibility will improve your performance
         I order to get rid of this warning I must make fValues public is this the only solution ?
    miro

    miro_connect wrote:
    I have a class
    class A{
    private Map fValues;
    A(){
    fValues= new HashMap();
    prrotected class B {
    B(){
    fValues.get("String");
    Above class is only for an example to expalin my problem.
    Inner class B wants to access fValues from class A .
    The eclipse gives me a warning
    Access to enclosing method fValues from the type A is emulated by a synthetic accessor method. Increasing its visibility will improve your performance
         I order to get rid of this warning I must make fValues public is this the only solution ?
    miroWhat happens if you remove the modifier? (That is uses default)

  • Local variable can't be accessed from inner class ???????? Why ??????

    Plesae help, help, help. I have no idea what to do with this bug.........
    <code>
    for ( int i = 0; i <= 2; i++ ) {
    for ( int j = 0; j <= 2; j++ ) {
    grids[i][j] = new MyButton ();
    grids[i][j].setBorder(but);
    getContentPane().add(grids[i][j]);
    MyButton sub = grids[i][j];
    sub.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    if ( sub.getState() == 0 ) {
         sub = new MyButton( (Icon) new ImageIcon(imageFile));
         if ( imageFile.equals("cross.jpg") ) {
              sub.changeState(1);
         else {
              sub.changeState(2);
    </code>
    The compiler complains that "sub" is in the inner class, which is the ActionListener class, must be declared final. Please tell me what to do with it. I want to add an ActionListener to each MyButton Object in the array. Thanks ......

    OK, now I changed my code to this :
    for ( int i = 0; i <= 2; i++ ) {
      for ( int j = 0; j <= 2; j++ ) {
        grids[i][j] = new MyButton ();
        grids[i][j].setBorder(but);
        getContentPane().add(grids[i][j]);
        grids[i][j].addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent e) {
            if ( grids[i][j].getState() == 0 ) {
               grids[i][j] = new MyButton( (Icon) new ImageIcon(imageFile));
              if ( imageFile.equals("cross.jpg") ) {
               grids[i][j].changeState(1);
              else {
              grids[i][j].changeState(2);
    [/cpde]
    Thanks for your advice !!!!!!
    Now the compiler says that i and j are local variables accessed from inner classes, needs to be declared final. How can I solve this then ???

  • Accessing a Java class from C when class is in a package

    I'm accessign a java class from C using JNI: The JVM exists and I can access the class fine:
    jclass cls; //java class
    cls = (*env)->FindClass(env, "MyClass");
    However when I put the class in a package I can't access it
    cls = (*env)->FindClass(env, "mypackage.MyClass");
    Does anyone know How I can access a java class in a package using JNI.
    Thanks
    ..

    Been a while since I've done anything with JNI, But... Did you try this:
    cls = (*env)->FindClass(env, "mypackage/MyClass");

  • JSP page access regular Java class

    I am new to JSP. But most of the time people say JSP page access Java Bean classes.
    I want to know what if I want to access regular Java classes?? Should I do like this
    in the code:
    <%
         NormalJavaClass cl = new NormalJavaClass();
         cl.process();
    %>
    <%-- JSP page access Java Bean -- %>
    <jsp:useBean scope="session" id="formDataBeanObj" class="formdatatest.FormDataBean"/>
    <jsp:setProperty name="formDataBeanObj" property="*"/>
    <HTML>
    <HEAD>
    <TITLE>page1.jsp</TITLE>
    <BODY>
    <FORM METHOD="POST" ACTION="page2.jsp">
         <H2>User Name = <jsp:getProperty name="formDataBeanObj" property="username"/></H2>
    <%
         NormalJavaClass cl = new NormalJavaClass();
         cl.process();
    %>
    <P><INPUT TYPE="SUBMIT" VALUE="submit here">
    </FORM>
    </BODY>
    </HTML>
    Please advise. Thanks!!

    Yes, you can instantiate and reference any class visible to the Java runtime from within a JSP just as you can in an "ordinary" Java class. Behind the scenes, a JSP is converted into Java source code for a servlet class, and then compiled into the .class file. When you insert code into JSPs using either taglibs or code delimiters (<% %>, <%= %>), the JSP/servlet "engine" inserts this code into the servlet source code verbatim, and all non-Java text from the JSP is inserted into the source code inside of JspWriter.write(xxx) statements.
    If you'd like to see the source code that your JSP is converted into, run your JSP in Tomcat and look in the "work" folder within the Tomcat folder after you access it the first time. Experiment around with the JSP and see how code within the <% %> and <%= %> blocks is inserted into the .java file.

  • Accessing inner protected class with .new

    My weak understanding is that inner classes are no different in terms of access modification as other class members, thus I was expecting the following to compile:
    package A;
    public class ClassA {
        protected void protectedMethod() {}
        protected class ProtectedInnerClass {}
    }is being used over here in package B
    package B;
    import A.*;
    public class ClassB extends ClassA {
    public static void main(String[] args) {
    ClassB b = new ClassB();
    b.protectedMethod(); // works fine. I am inheriting ClassA and calling the protected method.
    ClassB.ProtectedInnerClass c = b.new ProtectedInnerClass(); // compiler error: ProtectedInnerClass is protected
    }Why can I not access the protected inner class when ClassB is inheriting it as is the case with the protected method?
    thanks in advance!

    So classes that inherit other classes with protected inner classes will not be able to instantiate these inner classes regardless of the inheritance relationship.No, that's not true. Example:
    package A;
    public class ClassA {
         protected void protectedMethod() {
         protected class ProtectedInnerClass { // class is protected
              public ProtectedInnerClass() { } // <-- nota bene
    package B;
    import A.ClassA;
    public class ClassB extends ClassA {
         public static void main(String[] args) {
              ClassB b = new ClassB();
              b.protectedMethod(); // works fine.
              ClassB.ProtectedInnerClass c = b.new ProtectedInnerClass(); // works fine, too.
    }It's section 6.6.2.2 that describes this behavior, as I quoted above. The last bullet point of that section reads (to repeat): "A protected constructor can be accessed by a class instance creation expression (that does not declare an anonymous class) only from within the package in which it is defined."
    ~

  • My java program runs fine even if i don't specify access specifier of class

    Hi,
    My java program runs fine even if i don't specify access specifier of class as public .
    Then why do they say that atleast one class should be specified as public.
    please help.

    public access specifier is the default access
    specifier
    so if you dont give the access specifier before the
    class name it is not wrong.I think that you are wrong. The default specifier is package or "package-private".
    See here:
    http://java.sun.com/docs/books/tutorial/java/javaOO/accesscontrol.html
    Message was edited by:
    petes1234

  • Can anyone help me simplify this into a var or class? I'm quite new to this!

    sym.$("UKstandardbuttons").fadeToggle();
    sym.$("AUSstandardbuttons").fadeOut();
    sym.$("Hongkongstandardbuttons").fadeOut();
    sym.$("Switzerlandstandardbuttons").fadeOut();
    sym.$("Irelandstandardbuttons").fadeOut();
    sym.$("Indiastandardbuttons").fadeOut();
    sym.$("Japanstandardbuttons").fadeOut();
    sym.$("Netherlandsstandardbuttons").fadeOut();
    sym.$("Spainstandardbuttons").fadeOut();
    into a var or class? so i don't have to list similar code for each element (UKstandardbutton)'s action
    thanks!
    James

    Thanks, can you help me understand how to make an array work?
    I need to fade toggle a different country png for each country button and fade out the rest of the country images i.e.: when i click the UK button i need to fade toggle the UK png and fade out the other countries
    when i click the USA button i need to fade toggle the USA ing and fade out the other countries and so on
    sym.getSymbol("Countries").$("UK").fadeToggle();sym.getSymbol("Countries").$("USA","AUS","Hongkong","Switzerland","Ireland","Indias","Japa n","Netherlands","Spain").fadeOut();
    sym.getSymbol("Countries").$("USA").fadeToggle();sym.getSymbol("Countries").$("UK","AUS","Hongkong","Switzerland","Ireland","Indias","Japan ","Netherlands","Spain").fadeOut();
    but it doesn't seem to work how i have it and i have been told to do an array but I'm not sure how?
    etc
    can you help?

  • How to access a Java class from view controller?

    Hi All,
    I have created a Test.java class file from Navigator view under
    Src --> Packages --> com.sap.MyProject.
    When I try to access the Test class from view controller,
    I getting this error "Test cannot be resolved or is not a type".
    How do I fix this?
    Thanks
    Sundar

    Hi,
    I have created a Test.java class file from Navigator view under
    Src --> Packages --> com.sap.MyProject.
    After this you can goto the context of your View and define the VA goto the type of VA and click on the right side button and go to java native type and type your java file name click you name .
    that means the jave file s assigned to VA.
    U can utilize thrut that VA.
    Thanks,
    Lohi.

  • How to restrict the accessibility of a class to specific class(es)

    How can I restrict accessibility of a class (instantiating or using) to a specific class or a set of classes. For example, I have a class 'CreditCard'. I want to limit its accessibility to a specific class 'CreditCardManager'. i.e., anyone could only create or use objects of 'CreditCard' class from 'CreditCardManager' class only.
    This may look like 'friend' functionality in c++. But it is not. The private members should not be accessed from the manager class.

    Define a CreditCard interface:
    public interface CreditCard {
    }Put the implementation inside CreditCardManager:
    public class CreditCardManager {
        private /* static (?) */ class CreditCardImpl implements CreditCard {
        public CreditCard newCreditCard(...) {
            CreditCard  cc = new CreditCardImpl();
            return cc;
    }Since you are going on about it, I assume CreditCard is a key concept in your app, so there are probably other reasons to make it an interface too. For example, so that youi can mock it in unit tests.

  • Accessing the inner class written inside the method

    Hi all,
    Can any of you tell me how to access the inner class's method which is written inisde the outer class's method. THe code fragment is
    class Outer
    private static final int ID = 3;
    public String name;
    public void methodA( int nn )
    final int serialN = 11;
    class inner
    void showResult()
    System.out.println( "Rslt= "+ID );
    } // end class inner
    // new inner().showResult();
    } // end methodA
    class Sample
    public static void main(String a[])
    //access the showResult of Inner class??
    Thanks in advance.
    aah

    class Outer {
      private static final int ID = 3;
      public String name;
      public void methodA( int nn ) {
        final int serialN = 11;
        class inner {
          void showResult() {
            System.out.println( "Rslt= "+ID );
        } // end class inner
        new inner().showResult();
      } // end methodA
    class Sample {
      public static void main(String a[]) {
        new Outer().methodA(5);
    }

  • Accessing view object class (impl) method from bean (or vice versa)

    Halo everyone, I am using JDeveloper 11.1.2.1.0
    I have a UsersViewImpl class with a method which refresh the user table like below.
    public void resetEmployeeSearch() {
    removeApplyViewCriteriaName("viewCriteria");
    executeQuery();
    and I have a UserBean class with a method which reset the search fields values like below.
    public void resetInput(ActionEvent actionEvent) {
    ........RichInputText = input ...
    input.setValue("");
    AdfFacesContext.getCurrentInstance().addPartialTarget(searchForm);
    I would like to implement it in such a way that, once I press a button, both methods will be called.
    I have tried to call from bean method using UsersViewImpl vs = new UsersViewImpl ..... which is wrong and wont work.
    I have read about doing something like ViewObject vo = am.findViewObject("DeptView1") but I duno how to use it because I cant have a proper example.
    Any suggestion on accessing view object class (impl) method from bean (or vice versa)?
    Or is there any way to combine both method in the same class ?
    Thank you :(

    User, if you get class not found exceptions you need to tell us which classes you can't find. The JSFUtils and ADFUtils classes needing some other libraries which should already be part of your Fusion Web Application template (which your adf application should be based on). If you did not use this application template, you may have to add some libraries yourself.
    What is the diff of using the ADFUtils and OperationBinding way?
    The ADFUtils can get you access to the application module which you then use to call exposed methods on. The disadvantage of doing this is that you have to implement your own exception framework which then handles exceptions thrown by the application module. An other thing is that if you e.g. alter a VO which you use on the page this changes are not seen on the page until you refresh the page. The binding layer does not know about these changes so the iterators (which are used on the page to show the data) are not refreshed and so you don't see the changes.
    In general you should avoid using the application modul in a managed bean method and always use the binding layer (OperationBinding) to call methods. This ensures that exceptions are all handled the same way and that changes to the data model are reflected in the GUI.
    Timo

  • How can a textInput variable access a document Class?

    I have a document class which creates a body of text on-the-fly at runtime.  I am trying to figure out (though I haven't taken any steps to do so yet) how to use a textinput field on the stage of a Flash document that calls the Document Class "MyClass" (just for example's sake").  The class file is MyClass.as and is located in the same directory as the FLA and resultant SWF.  I would like that textInput.text value to change the body text of the MyClass text.  The reason I am using MyClass is because I am performing special visualizations with the text that are encapsulated in MyClass.
    Thanks in advance for any feedback.
    -markerline

    I hadn't realized that this import was what was necessary.  Thank you.  However now with the imported property and my EnterFrameEvent, the rendered text is still not updating.
    Here is my complete Document Class:
    package
        import away3d.containers.ObjectContainer3D;
        import away3d.extrusions.TextExtrusion;
        import away3d.primitives.TextField3D;
        import flash.events.Event;
        import flash.display.MovieClip;
        import wumedia.vector.VectorText;
        import flash.text.TextField;
        import flash.text.TextFieldType;
        public dynamic class FontExtrusionDemo extends Away3DTemplate
            [Embed(source="Fonts.swf", mimeType="application/octet-stream")]
            protected var Fonts:Class;
            protected var container:ObjectContainer3D;
            protected var extrusion:TextExtrusion;
            protected var text:TextField3D;
            public var txtFld:TextField;
            public var myString:String;
            public function FontExtrusionDemo()
                super();
            protected override function initEngine():void{
                super.initEngine();
                this.camera.z=0;
                VectorText.extractFont(new Fonts());
            public function setString():void{
                this.myString=myString;
                txtFld= new TextField();
                txtFld.x=txtFld.y=20;
                txtFld.width =100;
                txtFld.height=20;
                txtFld.border=txtFld.background=true;
                txtFld.type=TextFieldType.INPUT;
                addChild(txtFld);
                stage.focus=txtFld;
            protected override function initScene():void{
                super.initScene();
                myString="1";
                setString();
                text = new TextField3D("Vera Sans",{
                    text:myString,
                    align: VectorText.CENTER}
                extrusion = new TextExtrusion(text, {
                    depth: 10,
                    bothsides:true}
                container = new ObjectContainer3D(text, extrusion, { z:300 });
                scene.addChild(container);
            protected override function onEnterFrameEvent(event:Event):void{
                super.onEnterFrameEvent(event);
                text = new TextField3D("Vera Sans",{
                    text:String(txtFld.text),
                    align: VectorText.CENTER}
                extrusion = new TextExtrusion(text, {
                    depth: 10,
                    bothsides:true}
                //container = new ObjectContainer3D(text, extrusion, { z:300 });
                //scene.addChild(container);  // IF I UNCOMMENT THIS THEN A NEW CHILD WILL BE ADDED AT EVERY FRAME, which is not desired.
                container.rotationY=(container.rotationY+1)%360;
                if (container.rotationY>90&&container.rotationY<270){
                    text.screenZOffset=10;
                } else {
                    text.screenZOffset=-10;

Maybe you are looking for

  • Migration to new macbook aluminum

    I have recently purchased the latest macbook and its a happy upgrade from my ibook g4. My current problem is when doing the original migration over the wireless network after many hours, the connection failed. I then went to attempt the process again

  • How to Merge ADF Table Column Header in ADF Table ?

    Hi All, We need to have ADF Table Column header to be "Merged", e.g : There are two columns Header : | Qty (Case) | Qty (Pack) |, can we customize it to display like this : | ----- Qty -------| | Case | Pack | where there are two rows in column heade

  • Highlight on Playback bar

    Hi Folks Is there a way to remove/hide the yellow highlight on Playback when TAB is used. I can change/hide the glow when mouse is over buttons when using an SWF . But TAB highlights yellow around buttons and moves to next box each time used and it b

  • EclipseLink JPA 2: Missing Descriptor

    Hi All, I have a SessionBean that, when initialized, also initializes a LookupJpaController class. Here is the code for LookupJpaController: public class LookupJpaController { private static final String _QueryGetLookupForUI = "SELECT l " + "FROM loo

  • SSRS XML Errors when exporting to .xlsx from Dynamics NAV Database

    We use Dynamics NAV for our ERP and have many SSRS reports.  We get xml Errors when exporting to Excel .xlsx.  I've seen this happen since SQL 2008 R2 and have posted in many places trying to find an answer, but was hoping MS would solve the issue.