This question already has answers here:
JAVA cannot make a static reference to non-static field
(4 answers)
Closed 4 years ago.
Ok, so I am revisiting java after many years and I was just trying out some random program when I found out that I was having an error in the following snippet. Can someone give me any heads on how to solve this? I know that static methods will not be able to access non static variables but I created an instance for it right? Also I am not getting any heads on reading some other questions so try to help me.
import java.io.*;
public class phone
{
int x=6;
int getx()//I also tried using this function but everything in vain
{
return x;
}
}
public class Testing_inheritance extends phone
{
public static void main (String args[])throws IOException
{
phone xy=new phone();
int y=phone.x;
y+=10;
System.out.println("The value of x is " +y);
}
}
You probably intended to access the instance variable of the instance you created :
phone xy = new phone();
int y = xy.x;
Since x is not a static variable it can't be accessed without specifying an instance of the phone class.
Of course this will also fail, unless you change the access level of x to public (which is possible but not advisable - you should use getter and setter methods instead of directly manipulating instance variables from outside the class).
x is not static. You need to access it through an object reference.
Do
int y = xy.getx(); //could do xy.x, but better to access through method
Also, it's better to stick with Java naming conventions
Almost there, I made small but very important changes, I hope you get this otherwise just ask ;-)
Phone.java
public class Phone //<--- class with capital letter always
{
int x=6;
int getx()//I also tried using this function but everything in vain
{
return x;
}
}
Testing_inheritance.java
import java.io.*;
public class Testing_inheritance extends Phone
{
public static void main (String args[])throws IOException
{
Phone xy=new Phone();
int y= xy.getx(); //<--- principle of encapsulation
y+=10;
System.out.println("The value of x is " +y);
}
}
OR private inner class :
import java.io.IOException;
public class Phone {
int x = 6;
int getx()// I also tried using this function but everything in vain
{
return x;
}
private static class Testing_inheritance extends Phone {
public static void main(String args[]) throws IOException {
Phone xy = new Phone();
int y = xy.getx();
y += 10;
System.out.println("The value of x is " + y);
}
}
}
Related
I would like to pass a reference to a primitive type to a method, which may change it.
Consider the following sample:
public class Main {
Integer x = new Integer(42);
Integer y = new Integer(42);
public static void main(String[] args) {
Main main = new Main();
System.out.println("x Before increment: " + main.x);
// based on some logic, call increment either on x or y
increment(main.x);
System.out.println("x after increment: " + main.x);
}
private static void increment(Integer int_ref) {
++int_ref;
}
}
The output running the sample is:
x Before increment: 42
x after increment: 42
Which means int_ref was past to the function by value, and not by reference, despite my optimistic name.
Obviously there are ways to work around this particular example, but my real application is way more complex, and in general one would imagine that a "pointer" or reference to integer would be useful in many scenarios.
I've tried to pass Object to the function (then casting to int), and various other methods, with no luck. One workaround that seems to be working would be to define my own version of Integer class:
private static class IntegerWrapper {
private int value;
IntegerWrapper(int value) { this.value = value; }
void plusplus() { ++value; }
int getValue() { return value; }
}
Doing this, and passing a reference to IntegerWrapper does work as expected, but to my taste it seems very lame. Coming from C#, where boxed variable just remain boxed, I hope I just miss something.
EDIT:
I would argue my question isn't a duplicate of Is Java "pass-by-reference" or "pass-by-value"?, as my question isn't theoretical, as I simply seek a solution. Philosophically, all method calls in all languages are pass-by-value: They either pass the actual value, or a reference to the value - by value.
So, I would rephrase my question: What is the common paradigm to workaround the issue that in java I'm unable to pass a reference to an Integer. Is the IntegerWrapper suggested above a known paradigm? Does a similar class (maybe MutableInt) already exist in the library? Maybe an array of length 1 a common practice and has some performance advantage? Am I the only person annoyed by the fact he can store a reference to any kind of object, but the basic types?
Integer is immutable, as you may notice.
Your approach with private static class IntegerWrapper is correct one. Using array with size 1 is also correct, but in practice I have never seen using array for this case. So do use IntegerWrapper.
Exactly the same implementation you can find in Apache org.apache.commons.lang3.mutable.MutableInt.
In your example you also can provide Main instance to the static method:
public class Main {
private int x = 42;
public static void main(String[] args) {
Main main = new Main();
incrementX(main);
}
private static void incrementX(Main main) {
main.x++;
}
}
And finally, from Java8 you could define an inc function and use it to increment value:
public class Main {
private static final IntFunction<Integer> INC = val -> val + 1;
private int x = 42;
public static void main(String[] args) {
Main main = new Main();
main.x = INC.apply(main.x);
}
}
I was wandering how to make custom classes that can be used through out all of java eclipse. For example if you make any basic program you can call pre determined classes, like you can just type Math.abs(x); instead of having to go out of your way and typing
if (x<0) x = x * -1;
else x = x;
I would like to design my own custom classes for basic functions that I use a lot that i can use I in any program regardless of if they are in the same project or not.
custom classes that can be used through out all of java eclipse...
you can do that with any class as soon as you import that and define the right visibility for its data....
class MyRandom{
public static int MultiplybyTwo(int number){
return number * 2;
}
public static int DividebyTwo(int number){
return number / 2;
}
}
import MyRandom;
class Test{
public static void main(string[] args){
int x = MyRandom.MultiplyByThow(9);
System.out.println("the result is: " + x);
}
}
on the other hand, this makes no sense:
else x=x;
This question already has an answer here:
Returning a value from one method to another method
(1 answer)
Closed 4 years ago.
public static void main(){
getNumber();
printNumber();
int x;
}
public static int getNumber(){
int x = 5;
return(x);
}
public static void printNumber(){
System.out.println(x);
}
I am a total beginner, sorry for such a simple question. The above fragment of code is what I tried.
public class Test {
public static void main(String[] args) {
int x = getNumber();
printNumber(x);
}
public static int getNumber() {
int x = 5;
return x;
}
public static void printNumber(int x) {
System.out.println(x);
}
}
First of all:
public static int getNumber(){
int x = 5;
return(x);
}
Creates another local variable x. So that assignment affects only the x that "belongs" to getNumber(). The static field x of your enclosing class stays at its initial value of 0.
But there you go:
public static void printNumber(){
x = getNumer();
System.out.println(x);
}
Of course, a first step for writing more reasonable code: you decide whether you want to have that "global" field that all methods of your class can use, or if you want to not do that.
Meaning: either you use that field, then your method just updates x, and the other method prints it. Or your class doesn't have that field, and your two methods work by getNumber() returning a value, and then printing that returned result.
Can you firstly explain, what you want to do by this code?
Let's go through your code:
I concider method printNumber() to be excess because It's just wrapper for System.out.println method, we can use it derectly in our code.
Method getNumber() could receive some paramater, for example getNumber(int a). With such improvement we would be able to call getNumber from our main method and pass to it variable that we define in main method. Than getNumber could perform some operation, forexample a * a and return this result.
Also main method of java programm must look like below.
public static void main(String[] args) {
int x = 5;
int resultOfGetNumber = getNumber(x);
System.out.println(resultOfGetNumber);
}
public static int getNumber(int a){
return(a * a);
}
So we define variable x in our main method and passes it to the getNumber method, which returns the square of received variable. Then in main method we assing result of getNumber method to the int variable resultOfGetNumber. Then we pass resultOfGetNumber to the System.out.println method, which prints this variable to the console.
i made a small program for summing two numbers
if i used a void type method it will be like this
import java.util.Scanner;
public class NewClass {
public static void main(String[] args) {
Scanner input = new Scanner (System.in);
System.out.println("enter x");
int x = input.nextInt();
System.out.println("enter y");
int y = input.nextInt();
getSum(x,y);
}
public static void getSum(int x, int y)
{
int sum = x + y;
System.out.println("sum = " + sum);
} }
here if i used a method that returns a value i will get same output!
import java.util.Scanner;
public class NewClass {
public static void main(String[] args)
{
Scanner input = new Scanner (System.in);
System.out.println("enter x");
int x = input.nextInt();
System.out.println("enter y");
int y = input.nextInt();
int r = getSum(x,y);
System.out.println("sum = " + r);
}
public static int getSum(int x, int y)
{
int sum = x + y;
return sum;
}}
so i'm confused what is the benefit of returning a value if i can finish my program with a void type method?
The point is not to get the result but the way we get the result
consider
public static void getSum(int x, int y)
{
int sum = x + y;
System.out.println("sum = " + sum);
}
will print the output to the screen after calculation
but when we use return
as you have done it later
public static int getSum(int x, int y)
{
int sum = x + y;
return sum;
}
this function will respond back the sum. that sum can be stored in a variable
can be used afterwards
like in recursion
In small programs, you won't get the difference but while writing the big programs you have to make several functions which are being called several times and you may need the output of one function into other.
In that case, you will require return so that the output of one function can be used into other.
Hope this helps!!
I think the answer is that, if you're calling getSum() method with a return type in any other class.. you would get a returned value which can be used for further processing. .
Where as in void that's not possible... Hope this helps... Reply if any doubts..
I can understand why you have this question.
First of all, you should know that in real development, we do not use console logs.
System.out.Println();
This is used only for debugging and that too in very rare cases.
The whole point of a function is to take some input and convert to something else.
So,
public static int getSum(int x, int y) {
return x+y;
}
public static void main(String[] args) {
System.out.Println(getSum(5,10));
}
This is the better solution.
Best Regards,
Rakesh
When you use the keyword void it means that method doesn't return anything at all. If you declare a return type different to void at the method statement instead, that method must return obligatorily a valid value to the declared return type using the keyword return followed by a variable/value to send back to the class that called the method.
Defining methods here you have the java documentation for a method declaration
Answering your question, in small programs that work with primitive values it doesn't really matter but in complex program when you usually need to return specifics object types, i.e an ArrayList or actually an instance of a class you created you can't simply put it into a System.out.println and send it to the console, mostly you'll want to get something from a method and that something usually can be a more complex object than an integer or a string, the way to get that something is through the return type defined by the method's statement.
A common use of return types is when your method is static and it can't interact with the non-static instance variables of the class, this type of static methods usually get values from their arguments, do a certain kind of progress and then return a result that the method's caller can use.
Returning a value enables you to use that value in whichever way you want, including printing it or assigning it to variable for further processing. If on the other hand you print the value in the method and not return anything, i.e. making the method of type void, then that's all you can do with that method.
Let's say I have something like this :
public class obj{
public int x;
public obj(int x){
this.x = x;
}
}
and this :
public class main{
obj o = new obj(1);
public static void main(String[] args){
//get the value of OBJ
//add 1 to the value got from above(let's just say I wanted to. no reason why)
}
}
is there a possible way to get the value of the obj's x value without changing the x to static? And make it so that you can change it? when I try to do something like this, it always says to change the x to static. why? I know this may be a weird question but i just wanted to know :)
You need to change your object to static first since you are accessing it directly from static main.
private static obj o = new obj(1);
// You can get the value of `x` from `o` as follows:
int x = o.x;
// You can increment the value in the object `o` as follows:
o.x++;
First of all, your class declaration is wrong. You don't use parenthesis in class declaration.
Also, in Java you write class names big. (The class Object already exists, don't make a class "Obj" because it would mean the same and is an abbreviation.)
public class MyObject {
public int x;
public MyObject(int x){
this.x = x;
}
}
public class Main {
MyObject myInstance = new MyObject(1);
public static void main(String[] args){
// You can just do ++ behind the variable. This adds +1.
myInstance.x++;
// If you want to get the value of the (public) variable x:
int temp = myInstance.x;
}
}
Yes you can get it by using
o.x
It is not telling you to change x to static. It is telling you to make o to static. o is non-static and cannot be used in the static main method.
Non-static instances can't be assessed in static method directly. Since o is an instance variable rather than static variable, you will need to create an instance of Main to access it's non-static variable.
public class Main {
Obj o = new Obj(1);
public static void main(String[] args){
Main main = new Main();
main.o.x += 1;
}
}