Calling a non-static method outside the package without using extends
Hello everyone,
I am currently refactoring my codes and as much as possible i don't want to use static methods to avoid any conflicts when it comes to class instantiation.
Here's my problem,
MyClass extends OtherClass{
private myvar;
public getMyvar{
return myvar
}
}
OtherClassOutsidePackage {
//How to call getMyvar?? without declaring it as static
}
Your idea will be very helpful. Thanks!
Re: Calling a non-static method outside the package without using extends
Create a MyClass object and call the getMyvar() method.
Re: Calling a non-static method outside the package without using extends
OtherClassOutsidePackage
MyClass object = new MyClass();
object.getMyVar()
is this what you mean?
this is not safe because the class is instantiated everytime it is called. I want only one instance created for my class to preserve the values of my instance variables.
Re: Calling a non-static method outside the package without using extends
Then it needs to be static.
Re: Calling a non-static method outside the package without using extends
Ok, I know it needs to be static.
Is there anyway where I can force the compiler to get the current instance of a class ??
What I mean is, only MyClass can instantiate an object for MyClass. Other classes must go through MyClass before they can call getMyVar()?
In this way, it will be fine to declare getMyVar() as static.
Re: Calling a non-static method outside the package without using extends
Sounds to me like you want MyClass to be a Singleton Object.
That would look like:
Code java:
public class MyClass {
private static MyClass ref;
private myvar;
//Private constructor for restricted initialization
private MyClass() {
//do something, perhaps set myvar
}
//Method to get MyClass object
public static synchronized MyClass getMyClassObject() {
if(ref==null)
ref = new MyClass();
return ref;
}
//Secure against cloning
@Override
public Object clone() throws CloneNotSupportedException {
throw new CloneNotSupportedException();
}
//Your method
public getMyvar() {
return myvar;
}
}
Then, to get the myvar variable from anywhere in your program, simply call:
Code java:
//Get MyClass object
MyClass myClass = MyClass.getMyClassObject();
//Get variable
myClass.getMyvar();
It will always return the EXACT same MyClass object, regardless of how many times you call that from where ever in your program.
Re: Calling a non-static method outside the package without using extends
wow..this is what i'm looking for!
thanks!