How to get specific instance of class from another class in Java?
I would use a singleton on Application class.
Put a public static
method to return your one and only application instance.
public class Application
{
private Application() { } // make your constructor private, so the only war
// to access "application" is through singleton pattern
private static Application _app;
public static Application getSharedApplication()
{
if (_app == null)
_app = new Application();
return _app;
}
}
You can read more about singleton design pattern here.
Every time you need the one and only Application
instance, you do:
Application app = Application.getSharedApplication();
Access instance variable from another class
Just inherit and user super
to call the parent initializer:
class DailyOrders:
def __init__(self, day):
self.orders = []
# ...
class EggOrder(DailyOrders):
def __init__(self, day, eggs=0, name=""):
super().__init__(day)
# Now self.orders is available.
Keep in mind that if the parent initializer receives any parameter, the child must receive it as well in order to be able to pass it.
Not providing a day param ...If you don't want to provide a day param you should have another class with the interface/functionality that's common to the others, and the inherit from such base class:
class BaseOrders:
def __init__(self):
self.orders = []
# ...
class DailyOrders(BaseOrders):
def __init__(self, day):
super().__init__()
# Now self.orders is available.
self.day = day
# ...
class EggOrder(BaseOrders):
def __init__(self, eggs=0, name=""):
super().__init__()
# Now self.orders is available.
How to access methods inside another classes through instance of another class in Javascript
class Users { createUser(){ console.log('createUser'); }}
class Cars { createCar(){ console.log('createCar') }}
class Api { Users = new Users; Cars = new Cars;}
var api = new Api()api.Users.createUser()api.Cars.createCar()
Accessing an instance of a class defined in main in another class
The most natural way would be to pass the Foo
object as an argument to the Bar
constructor:
Bar(Foo a)
{
std::cout << a.x << '\n';
}
For the updated question, I might pass the object as a constant reference instead of by value:
Bar(Foo const& a)
: copy{ a }
{
}
This will initialize the member variable copy
to be a copy of the Foo
object that a
references.
For the Qt special case, you should almost never make copies of QObject
-derived objects. Instead you should have pointers to them:
class Bar
{
public:
Bar(Foo* a)
: pointer{ a }
{
}
private:
Foo* pointer;
};
In Java, can a class reference the instance of another class which contains it?
Here A composes B.
class A {
private B b = new B();
}
And here B composes A :
class B {
private A a;
public void setA(A a){
this.a = a
}
}
No design judgement, supposing that you are in a case where the bidirectional dependency is needed, you should avoid initializer or constructor to create instances of this class since you need an instance from A to create B and reversely. Making this in an asymmetric way as in your sample code hides in a some way the relationship between these two classes.
So you could use a setter or a factory approach to make it clearer.
Setter approach :
class A {
private B b;
public void setB(B b){
this.b = b;
}
}
class B {
private A a;
public void setA(A a){
this.a = a
}
}
A a = new A();
B b = new B();
a.setB(b);
b.setA(a);
Or with a factory approach where you can rely on A or B class to expose the factory method according to the client need POV :
class A{
// ...
public static A ofWithB(){
A a = new A();
B b = new B();
a.setB(b);
b.setA(a);
return a;
}
}
A a = A.ofWithB();
B b = a.getB();
Java how to access methods using an instance from another class
In your method attack you need to add 1 more argument which can be used to pass your instance of Zombie class to attack method.
Make your method signature as
public int attack( int attackStyle, Zombie zombie )
Now in switch block when you call defaultPlayer.attack pass the int value as you was passing earlier and instance of your Zombie class like this
defaultPlayer.attack ( your int value, zombie)
This will pass the zombie instance to attack method then you can the same zombie instance there to call your removeHealth(damage) method.
Hope this solve your query.
Accessing an instance of a variable from another class in Java
Add a getter:
public class Whatever {
private BlockingQueue<byte[]> buffer = new LinkedBlockingQueue<byte[]>();
public BlockingQueue<byte[]> getBuffer() {
return buffer;
}
}
Then if you have an instance of Whatever:
Whatever w = new Whatever();
BlockingQueue<byte[]> buffer = w.getBuffer();
Related Topics
Validate Indian Phone Number With Optional +91 or 0 Preceeding 10 Digits
How to Convert Json Date to .Net Datetime During Deserialization
Reload Page After Jquery.Get to MVC Controller Action
What Is the Purpose of a Question Mark After a Type (For Example: Int Myvariable)
Add Spaces Before Capital Letters
C# How to Simply Encrypt a Text File With a Pgp Public Key
Newtonsoft Json Dynamic Property Name
How to Create a Dynamic Email Template That Can Be Modified Without Changing Code in C# .Net MVC
How to Check Byte Array Empty or Not
How to Generate a System (Pc/Laptop) Hardware Unique Id in C#
How to Read Appsettings.Json With Array of Values
How to Remove Carriage Returns from the Json Output of My Webapi Service
Pass Array into ASP.NET Core Route Query String
How to Perform Join Between Multiple Tables in Linq Lambda
Configurationmanager.Appsettings Getting Null
C# Lamba With Datetime and Between