Java - how to use the same object in many classes - java

I'm new here so please forgive possible mistakes :)
I'm writing a game as a final project for my coding classes. And...I'm really stuck. I want to create one object of certain class BUT later on I need to pass there different data from different other classes so I can save all data at the end of using a program.
For example I create an object in MainFrame and get a name of a user from there. Then I go to NextFrame and get age of a user etc etc.
I'd appreciate the answers in as simple english as possible, I'm not fluent :)
I'm using netbeans btw.
Thanks a lot !

Simply try the Singleton Design Pattern.
Simple Example for that:
class SingletonClass {
private static SingletonClass instance = null;
private String customAttribute;
public SingletonClass() {
//default constructor stuff here
}
//important singleton function
public static SingletonClass getInstance() {
if(instance == null)
instance = new SingletonClass();
return instance;
}
// getter and setter
}
now, in your frame or any other class you just do the following:
SingletonClass myObject = SingletonClass.getInstance();
when this function is called for the first time, a new Object is created. Later, it returns the first created. With the help of the Singleton Pattern you can easily save data in one object across multiple classes.
for more information about Singleton:
http://en.wikipedia.org/wiki/Singleton_pattern
hope this helps.

just pass the object to the class you want to, and use it accordingly in a method that you want to ! Here is an example with two classes:
class oneClass {
void oneMethod() {
Class1 myClass1 = new Class1();
Class2 myClass2 = Class2 Class2();
myClass2.setMyClass1(myClass1);
}
}
class Class2 {
Class1 myClass1;
//...
void setMyClass1(Class1 myClass1) {
this.myClass1 = myClass1;
}
//...
void doSomething() {
// do something with instance variable myClass1
}
}
In your case Class1 can be MainFrame and Class2 can be NextFrame or however you want to call them...
As you can see from my code, you pass the class myClass1 to myClass2 using the following line of code : myClass2.setMyClass1(myClass1); and then you can work in this object any way you want

Just send the object of your MainFrame class using a method to wherever you want. The object will contains all data from whenever you change it from different method.
If you need a single object MainFrame all over the class then you may consider of using singleton pattern for creating the object.

to save things to a file(or stream) you can use interface serializable:
import java.io.Serializable;
import java.util.ArrayList;
public class Test implements Serializable {
public ArrayList<Object> urDiferentKindOfThings = new ArrayList<Object>();
public boolean add(Object o) {
if (o != null) {
urDiferentKindOfThings.add(o);
return true;
}
return false;
}
}
Now, just add anything (Object!) that you want to save, then at the end of your game just save the object of type TEST that should contain all your stuff (you may need to read about serializable as it make life easy)
Good Look

You pass class instances into a managing class
public class Game {
private MainFrame mainframe = null;
private NextFrame nextframe = null;
public Game(){
this.mainFrame = new MainFrame();
this.nextFrame = new NextFrame();
}
public Game(MainFrame mainFrame, NextFrame nextFrame){
this.mainframe = mainFrame;
this.nextframe = nextFrame;
}
public String getName(){
return mainFrame.getName();
}
public int getAge(){
return nextFrame.getAge();
}
}
public class MainFrame {
private String name = "John"
public String getName(){
return name;
}
}
public class NextFrame{
private int age = 25;
public int getAge(){
return age;
}
}

class a{
function dosomething(){
//code goes here
}
}
class b{
a firstobject=new a();
c secondobject=new c(a objtopass); //passing object of a to c
function donext(){
//next code
}
}
class c{
a receivedobj=null;
public c(a objtoreceive){
//constructor
receivedobj=objtoreceive;
}
function doAdd(){
//function code
}
}

Related

android accessing object inside extended class

I have some problems using this keyword. If I have a couple of classes implementing another class, how can I use their values without calling the class itself? I explain.
//this is my first class
public class Foo extends FooHelper{
public int fooInt;
public String fooString;
//getter/setter below
}
//this is my second class
public class Foo2 extends FooHelper{
public double fooDouble;
public float fooFloat;
}
//this is my main method, i'm using it for calling the value.
//I omit all the thrash code before.
//This is how i want to call the method:
//imagine before there are onCreate, activity,...
Foo foo = new Foo().GetFooInt();
//this is the class extended from the firsts
public class FooHelper{
public void GetFooInt(){
//here is my problem, i need to call the Foo class and the fooInt value.
//I want also to be able to edit the Foo object, for example:
if(((Foo)this).getFooInt() == 0){
(Foo) this.setFooInt(5);
}
}
}
This is what i want to achieve, acces a class which extends another class with the only this keyword from the extended class. How can I do it?
EDIT:
I badly explained i think.
My problem is that i want to access my Foo object inside the FooHelper, not FooHelper's method inside Foo object.
Example:
after using this code:
Foo foo = new Foo();
foo.HelperClassMethod();
I need (in HelperClass) to access Foo object which invoked it.
public HelperClass<Foo> {
public void HelperClassMethod(){
//HERE i need to use the "foo" object which invoked this method
}
}
I added the <Foo>, probably I was missing it, is this correct? and how can i use this foo object in the method from the helper class? thanks all
EDIT2: i totally failed on my question i thinkm lets ignore the above code and just check below:
I Have to access an object inside the extended class's method.
I have this class:
public class Foo extends FooToExtend{
public int fooInt;
}
the class which is extended is this:
public class FooToExtend{
public void MethodOne(){
//HERE i need to access the calling object
}
}
now, in my main activity, I want to do this:
Foo foo = new Foo();
foo.MethodOne();
My doubt is how i can access foo object i created in main inside my MethodOne.
I have to change my FooToExtend in
public class<Foo> FooToExtend{
...
}
but I don't still know how to access the foo object inside it.
I see 2 problems here, understanding this keyword, and extending clases
PROBLEMS WITH this KEYWORD
Imagine you have a class and you are executing some code: keyword this refers to the class itself, if you where the object this would be the equivalent to me. Check here and here longer explanations, examples and tutorials.
PROBLEMS WITH extend
Also you must extend from top (interfaces or abstract classes) to bottom (extended) classes and implement in bottom part:
//this is the PARENT (FIRST) class extended from the CHILDREN (SECOND)
public abstract class FooHelper{
public abstract void GetFooInt();
}
//this is the CHILD (SECOND!!!) class
public class Foo extends FooHelper{
public int fooInt;
public String fooString;
#Override
public void GetFooInt() {
// are you sure you getFooInt method can return a null???
if(this.getFooInt() == null){
this.setFooInt(5);
}
//getter/setter below
}
EDIT 1
Oh ok, this was useful. one more question, a way is to use abstract, as you said, but is there a way to do the same without implementing it all times? just for info, my objective is to use Foo.FooHelperMethod() and be able in "FooHelperMethod()" to access Foo class. I hope i explained it, i don't know how to do it.. if it's impossible i will use abstract as you suggested :)
Sure, this is inheritance, simply don't declare abstract the parent, and implement the methods AND the attributes there, all the children will have this methods and attributes by extending the parent class.
Lets see this example:
//this is the PARENT (FIRST) class extended from the CHILDREN (SECOND)
class FooHelper {
int theIntCommonValue;
public int getTheIntCommonValue() {
return theIntCommonValue;
}
public void setTheIntCommonValue(int theIntCommonValue) {
this.theIntCommonValue = theIntCommonValue;
}
}
// CHILDREN CLASS, look how calling this.getTheIntCommonValue() (the parent method)
// doesn't throw any error because is taking parent method implementation
class Foo extends FooHelper {
public void getFooInt() {
if (this.getTheIntCommonValue() == 0)
this.setTheIntCommonValue(5);
}
}
class Foo2 extends FooHelper {
public void getFooInt() {
if (this.getTheIntCommonValue() == 3)
this.setTheIntCommonValue(8);
}
}
EDIT2:
My doubt is how i can access foo object i created in main inside my MethodOne.
ANSWER:
Passing the object as a parameter. But then, you need static class, not an extended one, lets see an
EXAMPLE:
Foo.java
public class Foo {
public int fooInt;
}
FooHelper.java
public static class FooHelper {
public static void methodOne(Foo foo){
//HERE i need to access the calling object
// for example, this?
if (foo.fooInt == 2)
}
}
Now, how do you execute it?
Main.java
public static void main(String[] args) throws Exception {
Foo foo = new Foo();
FooHelper.methodOne(foo);
}
NOTES
conventions say, methods in java start in LOWECASE and class name starts in UPPERCASE.
you must put both classes in sepparated files in order to allow static public class
I'm not sure I completely understand. But it looks as though you want GetFooInt to perform something differently depending on the class that extended it. So I think the best here to check the instanceof.
public class FooHelper{
public void GetFooInt(){
if(this instanceof Foo)
{
((Foo) this).fooInt = 5;
}
}
}
By the situation you want to named one class "Helper" I assume you will use it as a helper-class.
public class Helper {
public static int screenHeight = 500;
}
public class AnyOtherClass {
testSomething() {
System.out.println(Helper.screenHeight);
Helper.screenHeight = 510;
System.out.println(Helper.screenHeight);
}
}
For some basic understanding: this is the keyword you use in a non-static context to access the variables and methods of the Object you're currently inside. Proper use of this example:
public class SomeClass {
private int someInt;
public void setSomeInt(int someInt) {
this.someInt = someInt;
}
}
In this example the this is necessary because the local variable (/parameter) someInt has the same name as the global class variable someInt. With this you access the class varaible of the Object you're "in".
Example of unnecessary use of this:
public class SomeClass {
private int someInt;
public int squareSomeInt() {
return this.someInt * this.someInt;
}
}
Here you don't need the keyword this since there is no local variable called someInt.
On the other hand super is a keyword which accesses the variables and methods of the parent class (the class, your class is derrived from). Example:
public class SomeClass {
private int someInt;
public int squareSomeInt() {
return someInt * someInt;
}
}
the derrived class:
public class Other extends SomeClass {
public int squarePlusSquare() {
return super.squareSomeInt() + super.squareSomeInt();
}
}

Copy an object that contains a super class of another object

I would like to create a copy of an object that contains a super class of another object. In this example I want to make a copy of the Box that contains a Toy. But all kind of toys can be in the box. What would be the best way to create the copy constructor in Toy?
class Box {
Toy toy;
public Box(Toy toy) {
this.toy = toy;
}
public Box(Box box) {
this.toy = new Toy(box.getToy());
}
}
abstract class Toy {
public Toy(String name) {
// ...
}
}
class Car extends Toy {
public Car(String name) {
super(name);
// ...
}
}
class Puppet extends Toy {
public Puppet(String name) {
super(name);
// ...
}
}
I don't really have an idea how to approach this problem.
Make Toy have an abstract method copy() with return type Toy. Then you will be forced to override this in Car and Puppet. In the copy constructor for Box you can use box.getToy().copy().
You can override the clone method of each Toy's subclass and then :
public Box(Box box) {
this.toy = (Toy) box.getToy().clone();
}
Alternatively, if you have a constant number of types of toy, you can use an enumeration instead of a class.
i think this structure can help you to have an idea,in this case we pass an Object toy using Box Constructor to SuperClass(Toy) and in Toy Class we have a Constructor to Accept an Object from Toy Class then it's call getInstance Method for Initialize toy object(just for example).
class Box extends Toy
{
public Box(Toy toy)
{
super(toy);
}
}
Class Toy
{
private static Toy toys = new Toy();
Toy(){}
Toy(Toy toy)
{
toy = Toy.getInstance();
}
public static Toy getInstance()
{
return toys;
}
}
and either,if you don't want other Classes(sub class) to don't see a specified methods and attributes just make them private,and if you want sub classes haven't access to set and get methods too,make them private only!

How to return an object from enum in Java?

I am have a number of classes which implement same interface. The objects for all those classes have to be instantiated in a main class. I am trying to do it in a manner with which this thing could be done in an elegant manner (I thought through enum). Example code :-
public interface Intr {
//some methods
}
public class C1 implements Intr {
// some implementations
}
public class C2 implements Intr {
// some implementations
}
...
public class Ck implements Intr {
// some implementations
}
public class MainClass {
enum ModulesEnum {
//Some code here to return objects of C1 to Ck
FIRST {return new C1()},
SECOND {return new C2()},
...
KTH {return new Ck()};
}
}
Now in the above example for some elegant way with which I can get instances of new objects of Class C1 to Ck. Or any other better mechanism instead of enum will also be appreciated.
enum ModulesEnum {
FIRST(new C1()), SECOND(new C2()); // and so on
private ModulesEnum(Intr intr) { this.obj = intr; }
private Intr obj;
public Intr getObj() { return obj; }
}
Hope that helps. The trick is to add an implementation to every enum. If you want to access the object, use the getter.
ModulesEnum.FIRST.getObj();
If your Intr and its implementations are package protected, you can make ModulesEnum public to expose the implementations. This way you can have only one instance per implementation, making them singleton without using the pattern explicitly.
You can of course use a Factory too if you intend to have multiple instances for every implementation.
What you need is the Factory pattern. Whether or not you need want to use the Enum class as the factory itself is another issue. You could do something like this:
public enum Module {
FIRST, SECOND, ..., KTH
}
public class ModuleFactory {
public Intr createModule(Module module) {
switch (module) {
case FIRST:
return new C1();
case SECOND:
return new C2();
...
case KTH:
return new Ck();
...
}
}
}
Without knowing how you plan on using these objects, I can't really say which is the more appropriate approach.
Use a static factory.
public IntrFactory {
static Intr first() {
return new C1();
}
static Intr second() {
return new C2();
}
...
}

Java: share object reference without passing as parameter

I have an ObjectFactory and a specialized case of implementation of that factory. I can't change the interface, that has 0 argument.
In one of the implementation I have to read a file and load some data. To pass the filename I can use the system properties because all I need to share is a string.
But in the other implementation I must start not from a file but from a memory structure. How can I do to pass the object (then I think the object reference) to the factory? Other methods? No way I serialize the object on a file and after I read it again because what I want to avoid is right the I/O footprint.
Thanks
OK, more informations:
This is the interface and the abstract factory I have to implement
public abstract interface A
{
public abstract Set<Foo> getFoo();
public abstract Set<Bar> getBar();
}
//this is otherpackage.AFactory
public abstract class AFactory
{
public static AccessFactory newInstance()
{
return a new built instance of the factory
}
public abstract A newA();
}
This is my implementation with my problem:
public class AFactory extends otherpackage.AFactory
{
#Override
public Access newA()
{
return new AA();
}
}
public class AA implements A
{
protected AA()
{
this.objectReferenceIWantToSaveHere = I retrieve from the shared memory zone;
use the object
}
}
Now I'd like to do something like this:
B b = something I built before
save b in a shared memory zone or something like that
otherpackage.AFactory f = mypackage.AccessFactory.newInstance();
A a = f.newA();
And inside the f.newA() call I'd like to access to the b object
Can't you simply use a constructor?
interface ObjectFactory { Object create(); }
class SpecialFactory implements ObjectFactory {
private final Object data;
public SpecialFactory(Object data) { this.data = data; }
#Override public Object create() { return somethingThatUsesData; }
}
Ass assylias proposes, you can pass the reference to the constructor. Or if you know where to find the reference, you could just ask for it before you use it? E.g. data = dataBank.giveMeTheData()
Agree it would help to get some more context around what you are doing... but could you use a shared static class in which your calling code places info into the static class, and your interface implementation references this same static class to obtain either the object and/or instructions?
So here's a client class. It has the entry point..and wants to pass an object to the interface implementer but it can't pass it directly...So it set's object it wants to pass in the MyStaticHelper.SetSharedObject method.
public class Client {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String mySharedObject = "Couldbeanyobject, not just string";
// Set your shared object in static class
MyStaticHelper.SetSharedObject(mySharedObject);
InterferfaceImplementer myInterfaceImplementer = new InterferfaceImplementer();
//
myInterfaceImplementer.RunMyMethod();
}
Here is the code for the static helper...
public class MyStaticHelper {
private static Object _insructionsObject;
public static void SetSharedObject(Object anObject)
{
_insructionsObject = anObject;
}
public static Object GetSharedObject()
{
return _insructionsObject;
}
}
and finally the the class that you call that uses the static helper to get the same object.
public class InterferfaceImplementer {
// no objects
public void RunMyMethod()
{
System.out.println(MyStaticHelper.GetSharedObject());
}
}
Again this works in a very simple scenario and wouldn't stand up if more than one implementer needs to be called simultaneously as this solution would only allow one obj to be in the static helper class.

Getting a reference to an instantiating object from the parameter object

I instantiate two dependent classes:
//Create and set up the content pane.
ImportTablePanel surveyTablePanel = new ImportTablePanel(genErrorDescArray);
SurveyTree surveyTreePanel = new SurveyTree(surveyTablePanel,genErrorDescArray);
The SurveyTree class has a method setImportOK() that I wish to access from the ImportTablePanel class.
public class SurveyTree extends JPanel
implements TreeSelectionListener {
...
public void setImportOK(){
// my code here
}
The problem I have is that instantiation of a SurveyTree object takes the ImportTablePanel as a parameter. This makes it very difficult to get a reference to the SurveyTree object.
After many attempts, I finally have managed to get this to work by navigating upwards from the table container - see code below.
I am sure there is a much better way to get a container reference - ideally something like table.getContainer(int indexFromTop) can anyone make a suggestion?
public class ImportTablePanel extends JPanel implements TableModelListener {
...
SurveyTree surveyTree = (SurveyTree) table.getParent().getParent().getParent().getParent().getParent().getParent().getParent().getParent();
surveyTree.setImportOK();
}
Many thanks..
In the end I used a singleton design pattern.
public class SwingUtility {
private static SwingUtility instance;
private static SurveyTree surveyTreePanel;
SwingUtility() {
}
public static synchronized SwingUtility getInstance(){
if (instance == null){
instance = new SwingUtility();
}
return instance;
}
public SurveyTree getSurveyTreePanel() {
return surveyTreePanel;
}
public void setSurveyTreePanel(SurveyTree surveyTreePanel) {
SwingUtility.surveyTreePanel = surveyTreePanel;
}
}
create singleton instance with main method
// set up singleton instance of survey form
SwingUtility swingUtility = new SwingUtility();
swingUtility.setSurveyTreePanel(surveyTreePanel);
Then reference the SurveyTree from the Import Table Panel
SurveyTree surveyForm = SwingUtility.getInstance().getSurveyTreePanel();
surveyForm.setImportOK();

Categories