How can I access objects created in one method in other methods?
I want to do this so that I don't have create the same object over and over again every time I create a new method, and want to use that object within it. This is the class I am working on:
import BrandPhone.*;
public class Test {
public static void main(String[] args) {
// Creating the object.
Phone myPhone = new Phone();
//Creating another object.
Color color = myPhone.getColor();
}
}
If I try and access the object color in another new method like the method initialise seen below, I get an error saying "cannot find symbol":
import BrandPhone.*;
public class Test {
public static void main(String[] args) {
// Creating the object.
Phone myPhone = new Phone();
//Creating another object.
Color color = myPhone.getColor();
}
public void initialise() {
color.setNum(120); // This gives an error
}
}
To try and solve this issue, I decided to try and declare the object names as class variables at the beginning of the class, outside of any method. This produces errors saying "non- static variable ('object name') cannot be references from a static context".
import BrandPhone.*;
public class Test {
Phone myPhone;
Color color;
public static void main(String[] args) {
// Creating the object.
myPhone = new Phone(); // Produces error.
//Creating another object.
color = myPhone.getColor(); // Produces error.
}
public void initialise() {
color.setNum(120);
}
}
To attempt to solve this issue, I changed the method so that instead of public static void main(String[] args) {...} I made it public void newObjects() {...}. This produces yet another error when I try to run it, saying "Class "Assignment.Test" does not have a main method."
I'm very new to Java, so I'm not sure how to tackle this- do all classes have to have a main method in the form of public static void main(String[] args) {...}? If so, could I not just start with a main method and leave it empty, and then continue on to make new methods?
Im not fully sure what your are trying to do. But color.setNum(120) should work if you do it after you declared and initialised color.
Color color = myPhone.getColor();
color.setNum(120);
You should also provide your Phone and Color class files, to provide an encapsulated look of your project. However, based on your main; the following will work. If you make a static call from the the main() the other method should also be static if also in the Test class. Instantiate your object, Color, and then make your method call to your setter method; color.setNum(120);
public static void main(String[] args) {
// Creating the object.
Phone myPhone = new Phone();
//Creating another object.
Color color = myPhone.getColor();
color.setNum(120);
}
You are trying to access the color variable out of scope, you can pass it directly to the method (shown below), set it as a static variable or just call setNum in your main() method.
public class Test {
public static void main(String[] args) {
// Creating the object.
Phone myPhone = new Phone();
//Creating another object.
Color color = myPhone.getColor();
initialise(color);
}
public static void initialise(Color colorToSet) {
colorToSet.setNum(120);
}
}
Related
public static void main(String[] args)
{
GUI TestGUI = new GUI();
TestGUI.setVisible(true);
}
public void blahh()
{
TestGUI.setVisible(true);
}
Can not find symbol for TestGUI in blahh, but can be seen in the main method.
How can I access TestGUI from other methods?
This is a scope issue. You could solve this by passing your GUI object to the blahh() method. Currently your blahh method has no way of reaching that variable.
public void blahh(GUI testGui) {
...
}
You can then call this method like this:
blahh(testGui);
Here is some reading you can do on scope, hopefully it will be helpful
Alternatively, you could declare your testGui variable as a field, and it will be accessible from anywhere in the class (make sure to make it static if you must access it in a static method). However, this will offer you less privacy with that variable even though it might seem more convenient.
because you declared TestGUI inside main method as a local varaible to a method , declare it as a class property
static GUI TestGUI;
public static void main(String[] args)
{
Test = new GUI();
TestGUI.setVisible(true);
}
public void blahh()
{
TestGUI.setVisible(true);
}
I want to access an object i created in a new class but it returns that the object " cannot be resolved".
thanks for anyone who helps:)
here is my code :
public class lion {
int weight;
int height;
String color;
double roardecibles;
public void lioncolor() {
System.out.println(color);
}
}
public class blacklion {
lion blackLion;{
blackLion = new lion();
blackLion.weight =4;
blackLion.height =3;
blackLion.color = "black";
blackLion.roardecibles = 5.5;
}
}
public class zoo {
public static void main(String[] args) {
blackLion.lioncolor(); //here it dosent work//
}
}
There's a difference between an object and a class. Think of a class as a blueprint, that's what you did when you defined it in public class blacklion. But you didn't actually build something with the blueprint. To create an object you have to instantiate it, using the new keyword.
public static void main(String[] args) {
blacklion lion = new blacklion();
lion.lioncolor(); //here it dosent work//
}
Usually, you want to instantiate an Object of your class that you can then access from where u created it. If you want to access methods or variables of a class directly you want to declare those as public and static.
Hey looks like you should check out this resource:
https://docs.oracle.com/javase/tutorial/
Specifically the section of how classes work:
https://docs.oracle.com/javase/tutorial/java/concepts/class.html
this code
public static void main(String[] args)
{
blackLion.lioncolor(); //here it dosent work//
}
needs an instance of the object in order to call the lioncolor() method
class BooleanWrap{
boolean b = new Boolean("true").booleanValue();
}
When I try to do the same with the code below, it doesn't work:
class TestCode {
public static void main(String[] ar) {
TestCode tc = new TestCode().go();
}
void go() {
//some code
}
}
Compile error:
TestBox.java:6: error: incompatible types
TestBox t = new TestBox().go();
When I change the return type of method go() from void to class type, then I do not get the error anymore.
class TestCode2 {
public static void main(String[] ar) {
TestCode2 tc2 = new TestCode2().go();
}
TestCode2 go() {
//some code
}
}
What happens to the object I just created in above code (referenced by tc2)? Will it get abandoned?
TestCode tc = new TestCode().go() would only work if the go() method returns a TestCode, since you are assigning it to a variable of TestCode type.
In the case of TestCode2 tc2 = new TestCode2().go();, if the go() method returns a reference to a different instance of TestCode2 (i.e. not the one for which you called go()), the original instance won't be referenced anywhere and would be eligible for garbage collection. In other words, tc2 would refer to the instance returned by go(), which doesn't have to be the same instance as the one created in the main method with new TestCode2().
This should work just fine:
class TestCode{
public static void main(String[] ar){
new TestCode().go();
}
void go() {
System.out.println("Hello World");
}
}
Edit: Additional info
This way you can't save the created instance. It will get destroyed right away in the next garbage collection. So normally, to avoid this unneccessary creation and destruction a static method would be used if the instance itself is not needed.
class TestCode{
public static void main(String[] ar){
TestCode.go();
}
static void go() {
System.out.println("Hello World");
}
}
As Eran said, the method go() returns nothing, and you're trying to assing that nothing to a variable, your method needs to return something, a TestCode object in this case
I want this code to generate a random number between one and five and then, using that number, chose a symbol out of my arraylist and print it. Whenever I try to call the printSymbol() method it tells me to change it and the arraylist to static. When I do it gives me two errors on the method call line in my main method and the line where it says that String y = list.get(x); I want to know how to make it so I can call this method and get it to print String y for me.
import java.util.*;
import java.lang.Math;
public class study {
public static void main(String[] args) {
printSymbol();
}
ArrayList<String> list = new ArrayList<String>();
public void addSymbols(){
list.add("あ");
list.add("い");
list.add("う");
list.add("え");
list.add("お");
}
public String printSymbol(){
int x=(int) Math.floor(Math.random()*5)+1;
String y = list.get(x);
return y;
}
}
You're messing up by mixing static and non-static contexts.
The printSymbol() method is part of the class study. (Use Study instead, that's the proper convention. For more information on these conventions, look here).
The main method is in a static context. This means that you need to make an object of the class Study and then call the printSymbol method on that object.
public static void main(String[] args)
{
Study study = new Study(); // create a new object of the class Study
study.printSymbol(); // call the printSymbol method on this object
}
You could also make the printSymbol() method and the ArrayList static, but that is bad practice in Java, which is an object oriented language.
Your main method is static, which means it can be called without creating an object. Main methods always have to be static, because on startup of the program you don't have an object yet.
The thing about static methods is, you can only access other static members from it unless you create an object you work with.
You have two possible solutions:
Make the other members static, which I wouldn't recommend as you are already using a field, or use an object:
public static void main(String[] args) {
study myObject = new study();
study.printSymbol();
}
import java.util.*;
import java.lang.Math;
public class study {
public static void main(String[] args) {
study newStudy = new study();
newStudy.addSymbols();
newStudy.printSymbol();
}
ArrayList<String> list = new ArrayList<String>();
public void addSymbols(){
list.add("a");
list.add("b");
list.add("c");
list.add("d");
list.add("e");
}
public String printSymbol(){
int x=(int) Math.floor(Math.random()*4)+1;
String y = list.get(x);
return y;
}
}
Your random was also wrong, its needs to be Math.random()*4.
I just replaced your symbols with ASCII for my machine to understand.
Like every one suggested, avoid static method and create an object then call your methods.
And dont forget to add the symbols to the arraylist, you can do it in the constructor or in the main method after creating the object and before calling printSymbol()
public static void main(String[] args) {
new study().printSymbol();
}
public study() {
// add symbols to the array list
addSymbols();
}
Or
public static void main(String[] args) {
study s = new study();
// add symbols to the array list
s.addSymbols();
s.printSymbol();
}
Also by convention Classnames should start with an upser case letter.
main is a static method and from it you may either call static methods, or you have to create an instance of the class and call instance methods of it. Also in your case list is an instance variable and thus it can not be accessed from static methods.
I believe the best option for you is to do something like:
public static void main(String[] args) {
study s = new study();
s.printSymbol();
}
Also please use capital names for classes.
public `static` String printSymbol(){
public `static` void addSymbols(){
The main method is in static context, so all other method its calling needs to be as well.
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 .