Is it possible to access an object created in one class from another class without using parameters/arguments?
For example:
public class Main {
public static void main(String[] args) {
Two make = new Two(); // Object I created.
make.ham();
}
}
class Two {
public void ham() {
System.out.println("Ham.");
}
}
class Three {
public static void accessObject() {
// Can I access the object make here without parameters?
}
}
What I understood is that you want to access to make object, created inside Main class (Two make = new Two());. And yes, it's possible to do it.
You have to create your variable make as global and static (and it's recommended be public or protected, in case you have your classes in separate files).
So, inside your Main class, you will have to do something like:
public class Main {
public static Two make;
public static void main(String[] args) {
make = new Two(); // Object I created.
make.ham();
Three.accessObject();
}
}
As you can see, I created the make variable as static and global. This is necessary because your main method is static, and it's global to be able to be recognized by other classes. And to can call to accessObject method, I did it with the class name (because that method is static)(Three.accessObject();)
And finally inside your Three class, in the accessObject method it's necessary call to the static variable make from Main class:
class Three {
public static void accessObject() {
System.out.println("using make object from Main class in Three class...");
Main.make.ham();
}
}
As you can see now, I called the variable make with the name class Main because it's static, and finally, you will be able to call the ham method by this way.
You could you inheritance to solve your problem. For example, you would write:
class Three extends Two {
public static void accessObject() {
// You can now access the "Two" object since you have now made
// Three a subclass of Two.
}
}
EDIT:
If you wanted to say, change the implementation of the ham() method, you could do something like this:
class Two {
public void ham() {
System.out.println("Ham.");
}
}
class Three extends Two {
#Override
public void ham() {
System.out.println("I'm inside ham, but inside the Three class.);
}
}
Related
I was revising some of the old school concepts of Java in order to solve one problem . I have written the following code where i am trying the create objects of multiple class in that same classes and calling the methods with those objects from the main.
class a {
public void display() {
System.out.println("inside class a");
a a1= new a();
}
}
class b {
public void display() {
System.out.println("inside class b");
b b1= new b();
}
}
public class one {
void display() {
System.out.println("inside class one");
}
public static void main(String[] args) {
one o = new one();
a1.display();
b1.display();
o.display();
}
}
I am getting object cannot be resolved error. My question is what i need to change to let the above code work. And, do i need to always declare objects inside the main().
Any help will be highly appreciated
I'm not really sure why you would want to do that, but assuming you're just wondering about the possibility to implement such a thing - yes, it can be done.
You can create an instance of a class inside that same class, like so:
public class A {
public static A instance = new A();
public void display() {
System.out.println("inside class A");
}
}
Pay attention to the static modifier in the above code; it allows you now to access instance from another place (class, method, main) like so:
A.instance.display();
If you want to know whether you can declare a variable inside a method, and not a class, and make it accessible from another method, then the answer is - no, you cannot.
Yes you need to declare objects inside the main()
class a {
public void display() {
System.out.println("inside class a");
}
}
class b {
public void display() {
System.out.println("inside class b");
}
}
public class one {
void display() {
System.out.println("inside class one");
}
public static void main(String[] args) {
a a1= new a();
b b1= new b();
one o = new one();
a1.display();
b1.display();
o.display();
}
}
Don't know what you want to achieve and yes you should create object of class a and class b inside main functions to use instance methods of these classes.
package com.stack.overflow;
class a
{
public void display()
{
System.out.println("inside class a");
//a a1= new a(); ---> No need of this line as you can
// directly access instance variables and methods directly without
// creating any object or you can also use **this** keyword for the same
}
}
class b
{
public void display()
{
System.out.println("inside class b");
//b b1= new b(); ---> No need of this line as you can
// directly access instance variables and methods directly without
// creating any object or you can also use **this** keyword for the same
}
}
public class one
{
void display()
{
System.out.println("inside class one");
}
public static void main(String[] args) {
one o = new one();
a a1=new a();
b b1=new b();
a1.display();
b1.display();
o.display();
}
}
You may find the answer to your confusion easily - #ratul-sharker : a1 & b1 must be declared and instantiated inside the main. as well as other answers here correcting your code.
The real question is your notion of scoping and lifetime of variables - Not only a1 and b1 lie inside the classes a and b but they have been instantiated inside methods so they are local. So, try to understand the difference between field variables and local variables - their lifetimes and scopes are vastly different.
Accessing a local variable directly like that(which will be instantiated when the method is called) is like asking asking for a result from future in the present. Note that field variables will remain as long as object is alive but the local variables will remain only for the duration of the method call.
Hope it is clear to you now.
Also, your question:
My question was is it possible to create an object of an class in the
same class and call it from main?
Yes. Because main is a static method so it is not bound to an object like non-static method does. static methods are class level while non-static methods are object level. You can also create an instance in a non-static method for that matter.
I would like to access one variable that is a part of my GUI class. Should I instantiate my GUI class outside of that GUI class? Right now it is instantiated inside of main which I believe makes it inaccessible for me.
So is the best way to access variables in this class to instantiate this object in a different class and in that class create getters and setters for it?
public class NormalDistributionUI extends JFrame {
public static void main(String args[]) {
new NormalDistributionUI().setVisible(true);
}
}
Should it be like e.g.
public class Main {
static NormalDistributionUI ndUI;
public NormalDistributionUI getndUI() {
return ndUI;
}
public static void main(String args[]){
ndUI = new NormalDistributionUI();
}
}
EDIT: a different idea
public class NormalDistributionUI extends JFrame {
static NormalDistributionUI ndUI;
public static void main(String args[]) {
ndUI = new NormalDistributionUI()
ndUI.setVisible(true);
}
}
Does that make more sense than creating a separate class?
It depends on what you want. The second alternative would work as well, assuming that you called the method setVisible somewhere else.
The difference between the two of them is that in the second case the GUI object will be named and, hence, accessible afterwards. In the first case, it is anonymous.
You don't need a whole separate class. The first one is fine. If you want to manipulate the NormalDistributionUI object, you can use a local variable.
public class NormalDistributionUI extends JFrame {
public static void main(String args[]) {
NormalDistributionUI ndUI = new NormalDistributionUI();
ndUI.setSomeProperty(foobar);
ndUI.setVisible(true);
}
}
I am trying to re factor some code by breaking a class into several other classes.
to do so i want to move some methods already existing in my old class to new class.
But these methods are being referred in a lot of places and manually updating the references seems tiresome. So is there any way to move methods as well as update their references in eclipse?
I would do it this way:
Ensure that your tests work and the code to be re-factored is covered. If you don't have tests write tests. They are your safety rope.
Use the re-factoring pattern extract superclass to create the new class that you want to move some methods to.
Use the re-factoring pattern pull up methods to move the methods along with the variables that they need to the superclass. Now you will see if the methods you want to move and the instance variables have dependencies to the other methods that you don't want to move. If so you must first break this dependencies.
Find all client code that should use the new extracted class instead of the "old" class and rewrite it to the new extracted class.
Remove the "extends" relationship between the two classes. Now the client code should work or you missed something.
Also a good book for learning how to apply re-factoring patterns is Working Effectively with Legacy Code
if you using eclipse IDE then refactor will help you.
I will show you the process I follow.
Consider such code:
public class GodClass {
public someInstanceMethodToMove() {
// some code 1
}
public static someStaticMethodToMove() {
// some code 2
}
public static void main(String[] args) {
GodClass c = ...;
c.someInstanceMethodToMove();
GodClass.someStaticMethodToMove();
}
}
Create the new class:
public class SingleResponsibilityClass {
}
The static method can be directly moved to the SingleResponsibilityClass by using Eclipse's Refactor > Move... refactoring as described by Prabhakaran:
public class GodClass {
public someInstanceMethodToMove() {
// some code 1
}
public static void main(String[] args) {
GodClass c = ...;
c.someInstanceMethodToMove();
SingleResponsibilityClass.someStaticMethodToMove();
}
}
public class SingleResponsibilityClass {
public static someStaticMethodToMove() {
// some code 2
}
}
For the instance method, the process is a little more complex. Read below.
Extract a method out of someInstanceMethodToMove() and let's name it someInstanceMethodToMove2():
public class GodClass {
public someInstanceMethodToMove() {
someInstanceMethodToMove2();
}
private someInstanceMethodToMove2() {
// some code 1
}
// ...
}
Use the SingleResponsibilityClass in the original method:
public class GodClass {
public someInstanceMethodToMove() {
someInstanceMethodToMove2(new SingleResponsibilityClass());
}
private someInstanceMethodToMove2(SingleResponsibilityClass obj) {
// some code 1
}
// ...
}
Note: it is important that SingleResponsibilityClass is a parameter of the instance method to move, otherwise Eclipse will not move it to this type.
From there, right click on someInstanceMethodToMove2(), and select Refactor > Move..., select SingleResponsibilityClass type in the wizard, then apply:
public class GodClass {
public someInstanceMethodToMove() {
new SingleResponsibilityClass().someInstanceMethodToMove2();
}
// ...
}
public class SingleResponsibilityClass {
private someInstanceMethodToMove2() {
// some code 1
}
public static someStaticMethodToMove() {
// some code 2
}
}
Then right click on SingleResponsibilityClass' someInstanceMethodToMove2() method and Refactor > Rename it to someInstanceMethodToMove():
public class GodClass {
public someInstanceMethodToMove() {
new SingleResponsibilityClass().someInstanceMethodToMove();
}
// ...
}
public class SingleResponsibilityClass {
private someInstanceMethodToMove() {
// some code 1
}
public static someStaticMethodToMove() {
// some code 2
}
}
Then right click on GodClass' someInstanceMethodToMove() method and Refactor > Inline:
public class GodClass {
public static void main(String[] args) {
GodClass c = ...;
new SingleResponsibilityClass().someInstanceMethodToMove();
SingleResponsibilityClass.someStaticMethodToMove();
}
}
public class SingleResponsibilityClass {
private someInstanceMethodToMove() {
// some code 1
}
public static someStaticMethodToMove() {
// some code 2
}
}
does it have any of your satisfaction
package com.hussi.stackOverFlow;
class ClassOne {
public void methodInClassOne(String stringParam)
{
ClassTwo classTwoObj = new ClassTwo();
classTwoObj.methodInClassTwo(stringParam);
}
}
class ClassTwo {
public void methodInClassTwo(String stringParam)
{
System.out.println(stringParam);
}
}
public class ClassThree {
public static void main(String[] args)
{
ClassOne objClassOne = new ClassOne();
// calling method of class two in class one
objClassOne.methodInClassOne("pass this String value");
}
}
Copy the method into the new class.
Replace the method body in the old class with a call into the new class.
Inline the old method.
That's all you need. It may not be quite that simple, because in steps 1 and 2 you may need to add arguments and/or make the method static, but that is the essence of how to do it.
If you use any of the standard IDEs (e.g., Eclipse or IntelliJ IDEA), they all have a simple menu option to do that (depending on how the code is organized).
If you go to each method and right-click on its name, the menu has a "Refactor" option, which leads to a "Move" option. Select that and follow the instructions.
The above is especially easy for static methods. For the non-static ones, you may need to do subclassing, or pass references to the appropriate objects around. Even so, the "Refactor -> Move" option is a good start.
This question already has answers here:
Static Classes In Java
(14 answers)
Closed 3 years ago.
So, in short. I have two classes.
package rpg;
public class Engine {
public void main(String args[]) {
Start.gameStart();
System.out.println(menuResult);
}
}
and
package rpg;
public class Start {
int menuResult = 3;
public int gameStart()
{
return menuResult;
}
public int getMenuResult()
{
return Start.menuResult;
}
}
It keeps throwing up the error 'Cannot make static reference to non-static method gameStart()'.
I'm sure I'm missing something simple, but can't find it.
Thanks!
You need to create instance of Start class and call gameStart() method on that instance because gameStart() is instance method not static method.
public void main(String args[]) {
new Start().gameStart();
..................
}
Only static methods can be accessed by using class name as perfix.
public int gameStart() <--- Instance method not static method
call it on instance
Start start = new Start();
start.gameStart();
So finally your classes should look like below
public static void main(String args[]) {
Start start = new Start();
start.gameStart();
System.out.println(start.getMenuResult());
}
public class Start {
private int menuResult = 3;
public int gameStart() {
return this.menuResult;//Don't know why there are two methods
}
public int getMenuResult() {
return this.menuResult;
}
}
first of all the main method should be
public static void main(String args[]) {
}
I assume you can have multiple games, and hence you should be able to start multiple instances so you should create a non static class that can be created and then actions performed against.
to answer your original question, you need to have a static variable that have static getters and setters..
public class Start {
private static int menuResult = 3;
public static int gameStart()
{
return menuResult;
}
public static int getMenuResult()
{
return Start.menuResult;
}
If you need the method to be static, just add the keyword static in the function definition. That would get rid of the error. But if you want to keep the class Start the way it is, then you should create an instance of Start in the main function and then call the method. Hope that helps!
you are trying to invoke a method on its class name. you should be creating a new object and invoke its method
public void main(String args[]) {
new Start().gameStart();
System.out.println(menuResult);
}
Start.gameStart() refers to a method which would be public static int gameStart() because Start is the class and not an instance of the object.
If you declare a method on an object, you need to apply it to instance of the object and not its class.
When to use static or instanciated methods ?
instanciated : whenever you need to apply the method to the object you're in. example : mycake.cook();
static : when the actions you do inside your method have nothing to do with an object in particular. example : Cake.throwThemAll();
mycake is an instance of a Cake, declared this way : Cake mycake = new Cake();
Cake is the class representing the object.
You should, i guess, have a read at some object oriented programmation course if you still have a doubt about objects, classes and instances.
While Other answers are Correct , that remains the Question that Why you Can't access Instance
method Directly from Class name , In Java all static (methods , fields) bind with Class Name and when Class Is Loading to the Memory (Stack) all static members are Loading to the Stack , and this time Instance Method is not visible to Class. instance Method will Load into Heap portion in the memory and can only be access by Object references .
I want to make a convenient super class that will make an instance of whatever subclass it is ran from, without having to hard-code the name of the sub class. What is the fastest way to do this?
We can assume that the subclasses' constructors will have same signature, e.g. no parameters.
class Main {
public static void main (String [] args) {
Main m = new NAME-OF-SUBCLASS();
}
}
class MainSub1 extends Main { /*...*/ }
class MainSub2 extends Main { /*...*/ }
So when invoking main from MainSub1 ($ java MainSub1 from the command line), a MainSub1 object is created, etc.
As I wrote this, i found this thread where the accepted answer says it can't be done, but of course it can, somehow, through reflection or something, right?
Not that I'd really recommend it, but there's a dirty trick to it:
class Main {
static Main m;
public static void main (String [] args) {
// use m
}
}
class MainSub1 extends Main { static { m = new MainSub1(); } }
class MainSub2 extends Main { static { m = new MainSub2(); } }
A serious answer would be to write a separate main for each subclass, but let it call a common inherited method that accepts an appropriate instance.