I created an instance of a class in java as following:
ABC ab = new ABC();
I want to access this instant ab in another class XYZ. How to make this Object available in class XYZ?
It is difficult to answer your question without more specific information about your problem, but this would certainly work:
You can use a setter to initialize an instance variable in your other class if you want to use it everywhere in that class:
class someClass {
void someMethod() {
ABC ab = new ABC();
XYZ xyz = new XYZ();
xyz.setABC(ab);
}
}
class XYZ {
ABC ab;
//...
void setABC(ABC ab) {
this.ab = ab;
}
//...
void doSomething() {
// do something with instance variable ab
}
}
There are several ways to do what you want to achieve. Some of them might be as follows:
Passing the object reference through a constructor
Here, you would explicitly pass the reference of your reference class when you're creating an object of the actual class.
public class ActualClass{
private ReferenceClass refClassObject;
/**
* Passing through a constructor
*/
public ActualClass(ReferenceClass refClassObject){
this.refClassObject = refClassObject;
}
}
class ReferenceClass{
/**
* Your implementation of the class
*/
}
Using getter/setter methods
In this approach, you would pass the reference of your object through explict public setXX() methods. This approach is more flexible because you can update the reference object as and when you want to (think polymorphism). As an example:
public class ActualClass{
private ReferenceClass refClassObject;
public ActualClass(){
}
public void setReferenceClass(ReferenceClass refClassObject){
this.refClassObject = refClassObject;
}
public ReferenceClass getReferenceClass(){
return refClassObject;
}
}
class ReferenceClass{
/**
* Your implementation of the class
*/
}
Using a combination of constructors and getters/setters
For added flexibility, you might want to initialize your Actual class object with a reference. However if you would also want to keep the option of changing the reference at object at a later stage, go for a combination of both #1 & #2 that I specified above.
public class ActualClass{
private ReferenceClass refClassObject;
public ActualClass(){
}
public ActualClass(ReferenceClass refClassObject){
this.refClassObject = refClassObject;
}
public void setReferenceClass(ReferenceClass refClassObject){
this.refClassObject = refClassObject;
}
public ReferenceClass getReferenceClass(){
return refClassObject;
}
}
class ReferenceClass{
/**
* Your implementation of the class
*/
}
Which one should you choose? Well it would depend on your implementation and requirement.
This answer is exactlty same as Doug Ramsey this link
I tried to explain with the same logic.
public class A {
public void m1() {
System.out.println("inside m1 method");
ABC ab = new ABC(); // 2 object is made and reference is given to ab
XYZ xyz = new XYZ(); 3 object is made and reference is given to xyz
xyz.send(ab); // 4 THIS IS WHAT YOUR QUESTION MEANS
}
}
class XYZ {
ABC ab;
//...
void send(ABC ab) { // 5
this.ab = ab;
System.out.println("inside send");
callme();
}
//...
void callme() { // 6
System.out.println("A is : "+ab.a);
System.out.println("b is : "+ab.b);
// do something with instance variable ab
}
}
public class ABC {
int a = 10;
static int b= 20;
public static void main(String[] args) // called first
{
A a = new A();
a.m1();
}
}
You have two ways to pass object parameter to one class to another.
Passing parameter to a method
public void passMethod(ABC ab) {
}
Passing parameter to a constructor
public class XYZ {
public XYZ(ABC ab) {
}
}
I know this question is old, but If I'm correct you want to transfer an Object into another class to be used.
In order to do that you need a few things
Class XYZ has to have a constructor to take in the parameter "Object" it would something like
class XYZ{
private Object ab
public XYZ(Object ab){
this.ab = ab;//This is the constructor called when you create an XYZ object, and want to use the Object ab in XYZ
}
package demo;
class ABC{
void disp(xyz arg1){
System.out.println("runing disp method in pratics");
System.out.println("x value:"+arg1.x);
arg1.test();
}
}
class xyz{
int x = 67;
void test(){
System.out.println("runing test method in pratics");
}
}
class pratics {
public static void main(String[] args) {
ABC ab=new ABC();
ab.disp(new xyz());
}
}
Related
public class HelloWorld
{
protected int num = 12;
public void callme()
{
System.out.print(this.num);
}
public static void main(String[] args)
{
HelloWorld myObject1 = new HelloWorld();
myObject1.callme();
OtherClass myObject2 = new OtherClass();
myObject2.callme();
}
}
public class OtherClass extends HelloWorld
{
protected int num = 14;
}
Why the output is "1212" instead of "1214"? In php its "1214" but not viceversa in java. What's the logic behind that?
callme() method is defined only in the base class, and therefore return this.num; returns the instance variable of the base class.
There is no overriding of instance variables in Java.
If you'd override that method in the sub-class, by adding
public void callme()
{
System.out.print(this.num);
}
to OtherClass, myObject2.callme(); will return 14, since it will execute callme() method of the sub-class, and therefore access the sub-class instance variable.
This question already has answers here:
Call a Class From another class [closed]
(5 answers)
Closed 5 years ago.
Actually am new to Java,How to call one class1 from another class2?
Class1 has main() and other methods.Class2 has different methods.
I want to call class1 from Class2. Please provide the syntax.
You need to first create an object of type class2 and call the methods of it from main method of class1.
class2 c = new class2();
c.methodOfClass2();
Say you have the following classes:
public class A {
int a1 = 15;
public void showMessage() {
System.out.println("Hey!");
}
}
public class B {
}
In case you want your class B to be able to read a1 and call showMessage(), you need to create an object of the class they belong, in the class you'll be working in. Like this:
public class A {
int a1 = 15;
public void showMessage() {
System.out.println("Hey!");
}
}
public class B {
public static void main(String[] args) {
A a = new A();
//call either variables or methods by putting
//a. in front of them
}
}
To call methods of Class1 from Class2
If static method, call by className. e.g - Class1.staticMethodToBeCalledFromClass2();
If non-static method, you need to create object of Class1. e.g - Class1 cls1 = new Class1(); cls1.nonStaticMethodToBeCalledFromClass2();
Assuming Your code :
public class Class1{
public static void main(String[] args) {
}
public void nonStaticMethodTobeCalledFromClass2() {
}
public static void staticMethodTobeCalledFromClass2() {
}
}
public class Class2 {
public void callClass1Here() {
Class1 cls1 = new Class1();
cls1.nonStaticMethodTobeCalledFromClass2();
Class1.staticMethodTobeCalledFromClass2();
}
}
If you look at the code, you will see, to call
Consider this example (warning-very bad code):
public abstract class A {
static float foo;
public static void loadfoo(float incomingfoo) {
foo = incomingfoo;
}
public static void displayfoo() {
System.out.println("your foo is" +foo);
}
}
Class B extends Class A
public class B extends A {
static float foo;
//#Override (overide is not allowed for static methods. dis is a problem...)
public static void loadfoo(float incomingfoo){
foo = incomingfoo;
}
}
Class C is pretty much the same as B
public class C extends A {
static float foo;
//#Override
public static void loadfoo(float incomingfoo) {
//I would like a different static variable loaded into this class using this method
foo = incomingfoo;
}
}
finally the main Class runs the thing
public class Main {
public static void main(String whatever[]){
B.loadfoo(5);
C.loadfoo(8);
B.displayfoo();
C.displayfoo();
}
}
so the output of this is :
your foo is0.0
your foo is0.0
and I am aware this is because the displayfoo class reference the static foo in Class A, so please disregard this. I assume I have now been specific enough about describing my problem and goal. solutions anyone?
Edit: I feel like an idiot I completely forgot to actually state what I wanted to accomplish, but really all I want is for B and C to have there own static variables loaded into them without altering A's variable, which should be the default.
It looks like you need static access to two stateful objects with the same structure. In this case, an enum might be a solution:
public enum A {
B, C;
private float foo;
// getter and (optional) setter for foo here
public void displayFoo() { System.out.println("This foo is " + foo); }
}
This way you can still access your object statically, but don't need to duplicate anything else:
A.B.setFoo(5);
A.C.setFoo(8);
A.B.displayFoo(); // 5
A.C.displayFoo(); // 8
If you then need a static default, I would make it a method on A:
enum A {
A getDefault() { return A.B; }
}
A.getDefault().displayFoo();
It seems that first you want to load the values using loadfoo to foo and then display the value of that foo using the displayfoo method. Well, I don't think there is anyway to do it using static methods.You can do this by making displayfoo() method abstract and overriding the same in the subclasses B and C.
Here is the code:
abstract class A {
float foo;
public void loadfoo(float incomingfoo){
foo = incomingfoo;
}
public abstract void displayfoo();
}
class B extends A{
#Override
public void loadfoo(float incomingfoo){
foo = incomingfoo;
}
#Override
public void displayfoo(){
System.out.println("foo is " + foo);
}
}
class C extends A{
#Override
public void loadfoo(float incomingfoo){
this.foo = incomingfoo;
}
#Override
public void displayfoo(){
System.out.println("foo is " + foo);
}
}
public class Main {
public static void main(String whatever[]){
B b = new B();
C c = new C();
b.loadfoo(5);
c.loadfoo(5);
b.displayfoo();
c.displayfoo();
}
}
You can also check the same kind of question here.
Static methods should be used by static method access and not by object instance. It's not supposed to be virtual because it's not belong to the object.
If you call B.loadfoo() then a method of B class is called.
If you call C.loadfoo() then a method of C class is called.
You cannot call a static method if it doesn't exist in the class.
There's no point to use static methods if you want to use polimorphism.
Im very new to programming and want to know if I can somehow get the object from a class where I already used new MyClass(); to use it in another class and that I don't need to use new MyClass(); again. Hope you get the point.
Some very simple example:
class MyFirstClass
{
Something st = new Something();
}
class Something()
{
// some code
}
class MySecondClass
{
// This is where I want to use the object from class Something()
// like
getObjectFromClass()
}
You can use Singleton pattern to achieve this
This is kickoff example of such object. It has a private constructor and public class method getInstance:
static methods, which have the static modifier in their declarations,
should be invoked with the class name, without the need for creating
an instance of the class
When we make a call to getInstance it checks if an object has been created already and will return an instance of already created objected, if it wasn't created it will create a new object and return it.
public class SingletonObject {
private static int instantiationCounter = 0; //we use this class variable to count how many times this object was instantiated
private static volatile SingletonObject instance;
private SingletonObject() {
instantiationCounter++;
}
public static SingletonObject getInstance() {
if (instance == null ) {
instance = new SingletonObject();
}
return instance;
}
public int getInstantiationCounter(){
return instantiationCounter;
}
}
To check how does this work you can use the following code:
public static void main(String[] args) {
SingletonObject object = SingletonObject.getInstance();
System.out.println("Object was instantiated: " + object.getInstantiationCounter() + " times.");
object = SingletonObject.getInstance();
System.out.println("Object was instantiated: " + object.getInstantiationCounter() + " times.");
object = SingletonObject.getInstance();
System.out.println("Object was instantiated: " + object.getInstantiationCounter() + " times.");
}
Since you have just started coding won't give you a term like reflection and all.. here is one of the simple way is have a public getter() method.
Consider this simple example
class Something {
private int a=10;
public int getA() {
return a;
}
}
Here is the First which has a public method which return the object that i created in this class for the Something Class
class MyFirstClass {
private Something st;
public MyFirstClass() {
this.st = new Something();
}
public Something getSt() {
return st;
}
}
Accessing it from another Class
class MySecondClass {
public static void main(String...strings ){
MyFirstClass my =new MyFirstClass();
System.out.println(my.getSt().getA());
}
}
Output: 10
If You wan't to verify
Inject this function in MyFirstClass
public void printHashcode(){
System.out.println(st);
}
and then print the hash codes from both methods in MySecondClass
class MySecondClass {
public static void main(String...strings ){
MyFirstClass my =new MyFirstClass();
System.out.println(my.getSt());
my.printHashcode();
}
}
You will see that indeed you are using the Object created in MyFirstClass in MySecondClass.
Because this will give you same hashcode output.
Output On my machine.
Something#2677622b
Something#2677622b
Instead of using the Singleton pattern, a better pattern to use is dependency injection. Essentially, you instantiate the class you want to share, and pass it in the constructor of every class that needs it.
public class MainClass {
public static void main(String[] args) {
SharedClass sharedClass = new SharedClass();
ClassA classA = new ClassA(sharedClass);
ClassB classB = new ClassB(sharedClass);
}
}
public class ClassA {
private SharedClass sharedClass;
public ClassA(SharedClass sharedClass) {
this.sharedClass = sharedClass;
}
}
public class ClassB {
private SharedClass sharedClass;
public ClassB(SharedClass sharedClass) {
this.sharedClass = sharedClass;
}
}
Singleton pattern lets you have single instance which is 'globally' accessible by other classes. This pattern will 'guarantee' that you have only one instance in memory. There are exceptions to one instance benefit, such as when deserializaing from file unless care is taken and readResolve is implemented.
Note that class Something right now has no state(fields), only behavior so it is safe to share between multiple threads. If Something had state, you would need to provide some kind of synchronization mechanism in multi thread environment.
Given such stateless Singleton, it would be better to replace it with class that contains only static methods. That is, unless you are implementing pattern such as Strategy which requires interface implementation, then it would be good idea to cache instance like bellow with Singleton pattern.
You should rework your Something class like this to achieve singleton:
public class Something {
private static final Something INSTANCE = new Something ();
private Something () {
// exists to defeat instantiation
}
public Something getInstance() {
return INSTANCE;
}
public void service() {
//...
}
public void anotherService() {
//..
}
}
If FirstClass and SecondClass are somehow related, you can extract that common object you're using to a super class, and that's the only scope in which you're planning to use this object.
public class SuperClass{
Something st = new Something();
public Something getObjectFromClass(){
return st;
}
}
public class MyFirstClass extends SuperClass{
getObjectFromClass();
}
public class MySecondClass extends SuperClass{
getObjectFromClass();
}
Otherwise, if you plan to use that instance somewhere else you should use a
Singleton object. The easiest way of doing this is:
enum Singleton
{
INSTANCE;
private final Something obj;
Singleton()
{
obj = new Something();
}
public Something getObject()
{
return obj;
}
}
You use it:
Singleton.INSTANCE.getObject();
Okay firstly you can use inheritance e.g.
class MyFirstClass
{
Something st = new Something();
}
class Something()
{
// some code
}
class MySecondClass extends myFirstClass
{
// This is where I want to use the object from class Something()
// like
MySecondClass obj = new MySecondClass();
obj.method(); //Method from myfirstclass accessible from second class object
}
Or if you dont want any objects and just the method you can implement interfaces e.g.
public interface MyFirstClass
{
//example method
public abstract void saying(); //no body required
Something st = new Something();
}
class Something()
{
// some code
}
class MySecondClass implements MyFirstClass //Have to implement methods
{
public void saying(){ //Method implemented from firstClass no obj
System.out.println("Hello World");
}
getObjectFromClass()
}
Consider a class, hiding member from superclass. If implementing clone, then how to update both members correctly?
public class Wrapper implements Cloneable{
protected Collection core;
protected Wrapper(Collection core) {
this.core = core;
}
public Wrapper clone() {
try {
Wrapper ans = (Wrapper) super.clone();
ans.core = (Collection) core.getClass().newInstance();
for(Object o : core) {
ans.core.add( o.clone() );
}
return ans;
}
catch(CloneNotSupportedException e) {
throw new AssertionError(e);
}
}
}
public class Child extend Wrapper {
protected ArrayList core; // for simpler access
public Child() {
super(new ArrayList());
this.core = (ArrayList) super.core;
}
public Child clone() {
Child ans = (Child) super.clone();
ans.core ... // how to update both core members?
// ans.super.core ... ?
// ans.this.core ... ?
}
}
The standard way is to cast Child to Wrapper in order to access its hidden field.
Simple example:
public class Test {
public static class A {
protected String field = "I'm class A";
}
public static class B extends A {
protected String field = "I'm class B";
}
/**
* #param args
*/
public static void main(String[] args) {
B b = new B();
System.out.println(b.field); // prints "I'm class B"
System.out.println(((A) b).field); //prints "I'm class A"
}
}
But why do you hide the field? This leads to programming errors and makes your code hard to read. I would suggest accessing the field with getters and setters. In fact, i suggest declaring abstract getters and setters in Wrapper in order to force subclasses to provide a corresponding field.
Best regards,
sam