'Making my own custom class why it gave me an error [duplicate]
I had the following error:
Non-static variable this can not be referenced from a static context
This is the code
cellphone dg = new Cellphone()
public class Oops7 {
class Cellphone {
void ring() {
System.out.println("Your phon is ringing");
}
void sing() {
System.out.println("Your phon is singing");
}
void vibrate() {
System.out.println("Your phon is vibrating");
}
}
public static void main(String[] args) {
Cellphone dg = new Cellphone();
dg.vibrate();
dg.sing();
dg.ring();
}
}
Solution 1:[1]
cellphone dg = new Cellphone()
public class Oops7 {
public static void main(String[] args) {
Cellphone dg = new Cellphone();
dg.vibrate();
dg.sing();
dg.ring();
}
static class Cellphone {
void ring() {
System.out.println("Your phon is ringing");
}
void sing() {
System.out.println("Your phon is singing");
}
void vibrate() {
System.out.println("Your phon is vibrating");
}
}
}
You should put you main method at the beginning of your class, it is easier to read for other people. The correction to your problem is what the comment is, you have to add static to your class.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | AhmedSHA256 |