I am naive to java programming.
How to access an object created in one class into another class.
Class A
{
Obj
}
Class B
{
//Here i want to use Obj
A.Obj
}
For the above i declare Obj as public static, but when i use it in Class B as A.Obj, it is returning a syntax error saying
"Cannot make a static reference to the non-static field A.Obj".
Am i missing something here? Are there any other ways?
Yes you cant access without having an instance of A. You could do something like:
System.out.println(new A().Obj);//or define Obj as static in A class.
Note - You should encapsulate your Obj and access it via getter method.
You should use provide a get method or use that object in static method as well. for your information static will not garbage collected unless the execution gets stopped for more about your answer use this answer's reference
You need first to declare your Obj in class A as static
class A {
static Object object = new Object();
}
Then you can use it
class B {
A.object //in the class cannot be accessed directly
Object x = A.object; //can use it to assign a value
public Object Foo() {
A.object //in a method can be accessed directly
return A.object; //here as expression result
}
}
Related
I have created an instance of an object in one of my classes for a Java program. How can I pass the same instance of that object to another class?
Would I need to do something like creating some type of a getter method in the original class to pass the object through to the other class?
To "pass" it you need a method or a constructor in the other class that can accept it:
public class Other {
// either
public Other(MyClass obj) {
// do something with obj
}
// or
public void method(MyClass obj) {
// do something with obj
}
}
Then call the constructor/method:
MyClass x = new MyClass();
Other other = new Other();
other.method(x);
There are many ways to pass the reference for one object to another object. The simplest and most common ways are:
as a constructor parameter,
as a parameter of a setter method; e.g. setFoo(Foo foo) to set the "foo" attribute, or
as an "add" method in the object being passed is going to be added to a collection; e.g. addFoo(Foo foo).
Then there are a variety of more complicated patterns where objects are passed using publish/subscribe, call-backs, futures, and so on.
Finally there are some tricks that can be used to "smuggle" objects across abstraction boundaries ... which are generally a bad idea.
You can pass the object via the constructor of the other class.
Simple Example:
Class A{
}
Class B{
A a;
public B(A obj){
this.a=obj
}
}
Let's assume you want to pass an object of class A to class B. Now you have created the object like this:
A object = new A ();
And now in your B class, you can write a method to accept a A object. It should be public and you can make it static if you like.
If you want to pass object to B, you must want to do something with it, right? So you should name your method accordingly. You probably want to assign a field of type A (Let's call this fieldA) in B. (or maybe that isn't what you want, but I'll use this for the example)
Let's look at the method:
public void setFieldA (A a) {
fieldA = a;
}
You can call this method as follows:
anObjectOfClassB.setFieldA (object);
Of course you don't need anObjectOfClassB if it is static.
I have the following code:
public static boolean isRelated(Animal first, Animal second){
boolean result=false;
if(first(parentA).equals(second(parentA)))
result=true;
return result;
}
basically, I need to be able to access the parent A instance variable that is in the Animal class from this static method.
I understand that, to access instance variables in a static method, you need to create an object but I already have 2 brought in.(Parent A and Parent B)
Could you guys tell me what the problem here is?
In order to access instance variable, you need to use an instance. You don't have to create it each time you need it, as long as you have one.
And for your code:
if(first.getParentA().equals(second.getParentA()))
In this case you need to make sure than first.getParentA() isn't null before comparing (or else you'll get NPE)
if(first(parentA).equals(second(parentA)))
basically, I need to be able to access the parent A instance variable that is in the Animal class from this static method.
That is not the correct syntax to access instance members
should be
if(first.parentA.equals(second.parentA))
More over use setters and getters to access the data such that
public class Animal {
private String parentA;
// code
public String getParentA() {
return parentA;
}
public void setParentA(String parentA) {
this.parentA = parentA;
}
}
}
Then use the line if(first.getParentA().equals(second.getParentA()))
Static methods are created in method area, and is the first to be created. Instance variables are created in heap after static methods are created. Hence, accessing instance variables directly is not possible. Always make use of an object to access such variables.
Whenever we use static, we need not create a reference variable of a class. We can directly access class with the help of <class_name>
But when we write the following code:
class Abc
{
static void show()
{
System.out.println("Hey I am static");
}
}
class Test
{
public static void main(String args[])
{
Abc.show(); //1
new Abc().show(); //2
}
}
How does both the lines 1 & 2 work. what is the significance of
new Abc().show();
Using an instance (although it works) is the wrong way of invoking a static method (or access static fields) because static denotes its a member of the class/type and not the instance.
The compiler would therefore replace the instance with the Class type (due to static binding). In other words, at runtime, ABC.show() gets executed instead of new ABC().show().
However, your source code would still look confusing. Hence, it's considered a bad practice and would even result in warnings from IDEs like Eclipse.
Since your ABC class did'nt override the default constructor.
It's equivalent to :
class Abc{
public Abc(){super();}
static void show(){
System.out.println("Hey I am static");
}
}
Hence by doing new Abc().show(); you're just creating a new Abc object of your class and call the static method of the ABC class throught this object (it will show a warning because this is not the proper way to call static method).`
You CAN use static methods from an instance, as in new Abc().show(), but it's potentially confusing and not recommended.
Stick to className.staticMethod() for static methods and classInstance.instanceMethod() otherwise.
It simple means that you are creating object to ABC and than trying to accessing this variable through object.
However, at the time of compilation,
new Abc().show();
is converted to Abc.show().
Static keyword suggests only one copy per class now you have created method static and you are accessing using Classname.methodname() that is appropriate way because when class is loaded into JVM its instance will be created so no need to exlicitly create new Object of the class. hope it make sense.
I'm loading a class with following statement:
Class classToLoad = Class.forName("com.somePackage.SomeotherPackage.classname" );
Later i wd use reflection to get the methods of this class. now for invoking the methods with methodname.invoke() function i'd require the object of the loaded class. thus i want to create the object of the loaded class. I try to do it this way:
Object obj = classToLoad.newInstance();
but the problem in this is that this way i don't get the object of the class loaded but i get object of Object class.
Now if i want to call the functions of the loaded class, i do it like:
methodName.invoke(obj);
it throws an exception:
java.lang.IllegalArgumentException: object is not an instance of declaring class
can anybody please help?
Update on the problem:
The problem is that i need the left hand side of the assignment to be of a different class type and that class type will be decided on run time
For the below statement:
Object instance = clazz.newInstance();
"instance" should be of the "clazz" type and not the "Object" class.
How can i achieve this?
It works fine when everything's set up correctly:
import java.lang.reflect.Method;
class Foo {
public Foo() {
}
public void sayHello() {
System.out.println("Hello");
}
}
public class Test {
public static void main (String[] args) throws Exception {
Class<?> clazz = Class.forName("Foo");
Method method = clazz.getMethod("sayHello");
Object instance = clazz.newInstance();
method.invoke(instance); // Prints Hello
}
}
My guess is that the method you've fetched (methodName) wasn't actually fetched from classToLoad.
You can also just cast the return type and invoke the method directly.
public class Foo{
void HelloReflection(){
System.out.println("Hello reflection");
}
public static void main(String[] args){
try{
Foo o = (Foo) Class.forName("Foo").newInstance();
o.HelloReflection();
}catch(Exception e){
e.printStackTrace();
}
}
}
java.lang.IllegalArgumentException: object is not an instance of declaring class
This can be thrown if the method has no arguments and not found in your object's class. Probably You are calling the invoke method on the wrong object or your fetched method is wrong for your object.
The problem is that i need the left hand side of the assignment to be of a different class type and that class type will be decided on run time. ... How can i achieve this?
Use some language other than Java. Java is statically typed, which basically means you're not allowed to do exactly what you just asked how to do. The other answers here correctly show how to invoke a method without knowing the type of an object at compile time, but you'll never be able to set the type of a variable at runtime.
I have a class that creates the object of type Smo. The object then calls a static method from another class. The static method requires that I pass the object to it that is calling it. How do I designate the calling object as the parameter to pass.
For example:
class Smo {
Smo() {
}
void sponge() {
car.dancing(??????); //////< ----------- how do I refer to self?
}
void dance() {
//// do a little dance
}
}
class Car() {
Car() {
}
dancing(Smo smo) {
smo.dance();
}
}
Use the this keyword.
car.dancing(this);
use the keyword this
Within an instance method or a constructor, this is a reference to the
current object — the object whose method or constructor is being
called. You can refer to any member of the current object from within
an instance method or a constructor by using this.
Use this to have an object refer to itself. So,
car.dancing(this);
yup: car.dancing(this);
been there done (this) :D