Access object that is created in another class - java

I don't know if this is possible, and that is why I need your help.
What I want to do is that I want to add objects to a Vector. The problem is that the objects are created in another class.
Is it possible?
Here is my code:
class Factory {
public Factory() {
Action run = new RunAction();
Action climb = new ClimbAction();
}
}
public class Game {
private Vector<Action> actions = new Vector<Action>();
public Game(Factory fact) {
actions.add(XXXX); ****//What to write here to add the actions created in Factory? Somehow I want to use fact for this.**
}
}
class ClimbAction extends Action {
public ClimbAction() {
super("Try to climb\n");
}
}
class RunAction extends Action {
public RunAction() {
super("Try to run\n");
}
}
class TestClass {
Factory f = new Factory();
Game game = new Game(f);
}

Change your factory class to this:
class Factory {
private Action run;
private Action climb
public Factory() {
run = new RunAction();
climb = new ClimbAction();
}
public Action getRunAction(){ return run; }
public Action getClimbAction(){ return climb; }
}
From that, you can access run and climb through a provided instance of the factory class. e.g. factory.run.
Your code defines the two variables run and climb only in the scope of the Factory class' constructor. Therefore, they can only be accessed from there.
EDIT
Also, you seem to want to add all the actions from the Factory to your game. I would therefore advise you add a vector of actions to your factory and add the run and climb actions through the constructor:
class Factory {
private Vector<Action> actions = new Vector<Action>();
public Factory() {
actions.add(new RunAction());
actions.add(new ClimbAction());
}
public Vector getActions(){ return actions; }
public void setActions(Vector v){ actions = v; }
}
public class Game {
private Vector<Action> actions = new Vector<Action>();
public Game(Factory fact) {
//add every action in factory to game actions.
for(Action a : fact.getActions())
actions.add(a);
}
}
I hope this helped!

Your Factory class is not very useful yet: It creates two objects on construction...which can be garbage collected immediately.
Consider a Factory class like this:
final class Factory {
public [static] Action createRun() {
return new RunAction();
}
public [static] Action createClimb() {
return new ClimbAction();
}
}
This class looks a little more "Factory-Pattern-like", and it(static)/an instance can be used to populate your vector.

Create variables in the Factory class, and provide access to them (below demonstrates doing so by defining the variables as private, with access via a getter methods).
class Factory {
private Action run;//Access modifier is private
private Action climb;
public Factory() {
run = new RunAction();
climb = new ClimbAction();
}
public Action getRunAction(){
return run;
}
public Acti8on getClimbAction(){
return climb;
}
}
In the Constructor, use the getter methods of Factory to access the variables:
public Game(Factory fact) {
actions.add(fact.getRunAction()); ****//What to write here to add the actions created in Factory? Somehow I want to use fact for this.**
}

Related

Subclass constructor with different values

I have parent class Hammer and then his child class Mjolnir. I want to set the remainingUsage for Mjolnir to 4. I managed to do it by creating method in Hammer classs called setUsage and then use it in Mjolnir constructor. Is it possible to do it in more easy way without that setUsage method?
public class Hammer extends AbstractActor {
private int remainingUsage;
private Animation image;
public Hammer() {
this.remainingUsage = 1;
image = new Animation("sprites/hammer.png");
setAnimation(image);
}
}
public class Mjolnir extends Hammer {
Mjolnir(){
super();
this.setUsage(4);
}
}
You can do something like this:
...
private remainingUsages;
public Hammer() { this(1); }
public Hammer(int remainingUsages) { this.remainingUsages = remainingUsages; }
And then just call super(4) from your subclass. Calling other methods within your constructor is not good practice.

How to override the behavior of a class if I have only its object?

The question may be a stupid one to ask but, kindly help me on this.
I need to override the behavior of a class, but I will get only the object of it.
Following is the code sample.
I want to use the method Util.newChildComponent(String id) itself in all the places.
class ParentComponent{
public ParentComponent(String id){}
protected void someBehavior(){}
}
class ChildComponent extends ParentComponent{
public ChildComponent(String id){
super(id);
}
protected void childsBehavior(){}
}
public class Util {
public static ParentComponent newChildComponent(String id)
{
ParentComponent fc = new ChildComponent(id);
// Initialize the object, and performs some common configuration.
// Performs different operations on the generated child object.
// The child class has many members apart from childsBehavior().
return fc;
}
}
// The above classes belongs to a jar, so I cannot edit the code.
// I need to use Util.newChildComponent(String id)
// But I need to override the behavior as mentioned below.
public void f1()
{
// TODO: How to override childsBehavior() method using the object
// I have it in pc? Is it possible?
// Util.newChildComponent(id) method decorates the ChildComponent
// So I need to use the same object and just override childsBehavior() method only.
ParentComponent pc = Util.newChildComponent("childId");
// I need to achieve the result below
/*
ParentComponent pc = new ChildComponent(id){
#Override
protected void childsBehavior(){
super.someBehavior();
// Do the stuff here.
}
}; */
}
Thanks in advance.
Sounds like you are looking for a DynamicObjectAdaptorFactory.
Here's a use of his excellent object.
static class ParentComponent {
protected void someBehavior() {
System.out.println("ParentComponent someBehavior");
}
}
static class ChildComponent extends ParentComponent {
private ChildComponent(String id) {
}
protected void childsBehavior() {
System.out.println("childsBehavior");
}
}
public static class Util {
public static ParentComponent newChildComponent(String id) {
ParentComponent fc = new ChildComponent(id);
// Initialize the object, and performs some common configuration.
return fc;
}
}
interface Parent {
void someBehavior();
}
// The adaptor.
public static class Adapter implements Parent {
final ParentComponent parent;
private Adapter(ParentComponent pc) {
this.parent = pc;
}
// Override the parent behaviour.
public void someBehavior() {
System.out.println("Adapter invoke someBehaviour()");
parent.someBehavior();
System.out.println("Adapter finished someBehaviour()");
}
}
public void test() {
ParentComponent pc = Util.newChildComponent("childId");
Parent adapted = DynamicObjectAdapterFactory.adapt(pc, Parent.class, new Adapter(pc));
adapted.someBehavior();
}
Prints:
Adapter invoke someBehaviour()
someBehavior
Adapter finished someBehaviour()
Have a look at Java's Dynamic Proxy. This should allow you to change the behavior at runtime by creating invocation handlers to handle a call to a method. You can even then forward it to the original method if you want.
Declare a new class that extends the one with the method you want to change
public class MyClass extends ChildComponent {
#Override
protected void childsBehavior()
{
.....
}
}
Then in your code you can use casting, which is a feature we get to enjoy thanks to inheritance
MyClass pc = (myClass) Util.newChildComponent("childId");
But then you would have to create the new object like so
MyClass pc = new MyClass("childId");
and do the configurations by hand that would have been done at Util. Unless you extend Util and crete a method that creates an object of MyClass and copy the configuration code there.
And now pc will have all the methods of ParentComponent and ChildComponent, but the childsBehavior will be what you declared.
If you don't want to change the code that uses Util to instantiate the objects you need, you could rewrite the Util class with the behavior you need (i.e. instantiating a class that extends ChildComponent with the overridden method), just remember to put it in a package of the same name in your project (so that the import of its clients doesn't change). This way no other code should change at all.

Java - how to use the same object in many classes

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
}
}

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();

Calling methods from objects which implement an interface

I am trying to wrap my head around interfaces, and I was hoping they were the answer to my question.
I have made plugins and mods for different games, and sometimes classes have onUpdate or onTick or other methods that are overridable.
If I make an interface with a method, and I make other classes which implement the method, and I make instances of the classes, then how can I call that method from all the objects at once?
You'll be looking at the Observer pattern or something similar. The gist of it is this: somewhere you have to keep a list (ArrayList suffices) of type "your interface". Each time a new object is created, add it to this list. Afterwards you can perform a loop on the list and call the method on every object in it.
I'll edit in a moment with a code example.
public interface IMyInterface {
void DoSomething();
}
public class MyClass : IMyInterface {
public void DoSomething() {
Console.WriteLine("I'm inside MyClass");
}
}
public class AnotherClass : IMyInterface {
public void DoSomething() {
Console.WriteLine("I'm inside AnotherClass");
}
}
public class StartUp {
private ICollection<IMyInterface> _interfaces = new Collection<IMyInterface>();
private static void Main(string[] args) {
new StartUp();
}
public StartUp() {
AddToWatchlist(new AnotherClass());
AddToWatchlist(new MyClass());
AddToWatchlist(new MyClass());
AddToWatchlist(new AnotherClass());
Notify();
Console.ReadKey();
}
private void AddToWatchlist(IMyInterface obj) {
_interfaces.Add(obj);
}
private void Notify() {
foreach (var myInterface in _interfaces) {
myInterface.DoSomething();
}
}
}
Output:
I'm inside AnotherClass
I'm inside MyClass
I'm inside MyClass
I'm inside AnotherClass
Edit: I just realized you tagged it as Java. This is written in C#, but there is no real difference other than the use of ArrayList instead of Collection.
An interface defines a service contract. In simple terms, it defines what can you do with a class.
For example, let's use a simple interface called ICount. It defines a count method, so every class implementing it will have to provide an implementation.
public interface ICount {
public int count();
}
Any class implementing ICount, should override the method and give it a behaviour:
public class Counter1 implements ICount {
//Fields, Getters, Setters
#Overide
public int count() {
//I don't wanna count, so I return 4.
return 4;
}
}
On the other hand, Counter2 has a different oppinion of what should count do:
public class Counter2 implements ICount {
int counter; //Default initialization to 0
//Fields, Getters, Setters
#Overide
public int count() {
return ++count;
}
}
Now, you have two classes implementing the same interface, so, how do you treat them equally? Simple, by using the first common class/interface they share: ICount.
ICount count1 = new Counter1();
ICount count2 = new Counter2();
List<ICount> counterList = new ArrayList<ICount>();
counterList.add(count1);
counterList.add(count2);
Or, if you want to save some lines of code:
List<ICount> counterList = new ArrayList<ICount>();
counterList.add(new Counter1());
counterList.add(new Counter2());
Now, counterList contains two objects of different type but with the same interface in common(ICounter) in a list containing objects that implement that interface. You can iterave over them and invoke the method count. Counter1 will return 0 while Counter2 will return a result based on how many times did you invoke count:
for(ICount current : counterList)
System.out.println(current.count());
You can't call a method from all the objects that happen to implement a certain interface at once. You wouldn't want that anyways. You can, however, use polymorphism to refer to all these objects by the interface name. For example, with
interface A { }
class B implements A { }
class C implements A { }
You can write
A b = new B();
A c = new C();
Interfaces don't work that way. They act like some kind of mask that several classes can use. For instance:
public interface Data {
public void doSomething();
}
public class SomeDataStructure implements Data {
public void doSomething()
{
// do something
}
}
public static void main(String[] args) {
Data mydataobject = new SomeDataStructure();
}
This uses the Data 'mask' that several classes can use and have certain functionality, but you can use different classes to actually implement that very functionality.
The crux would be to have a list that stores every time a class that implements the interface is instantiated. This list would have to be available at a level different that the interface and the class that implements it. In other words, the class that orchestrates or controls would have the list.
An interface is a contract that leaves the implementation to the classes that implements the interface. Classes implement the interface abide by that contract and implement the methods and not override them.
Taking the interface to be
public interface Model {
public void onUpdate();
public void onClick();
}
public class plugin implements Model {
#Override
public void onUpdate() {
System.out.println("Pluging updating");
}
#Override
public void onClick() {
System.out.println("Pluging doing click action");
}
}
Your controller class would be the one to instantiate and control the action
public class Controller {
public static void orchestrate(){
List<Model> modelList = new ArrayList<Model>();
Model pluginOne = new plugin();
Model plugTwo = new plugin();
modelList.add(pluginOne);
modelList.add(plugTwo);
for(Model model:modelList){
model.onUpdate();
model.onClick();
}
}
}
You can have another implementation called pluginTwo, instantiate it, add it to the list and call the methods specified by the interface on it.

Categories