I am new to Java and trying to do a simple program to help me further understand object-orientated programming.
I decided to do a phone program. However on line 5 of the following program where I’m trying to create an instance of a phone class I am getting the following error:
“No enclosing instance of type OOPTutorial is accessible. Must qualify the allocation with an enclosing instance of type OOPTutorial (e.g. x.new A() where x is an instance of OOPTutorial).”
Here is the program:
public class OOPTutorial {
public static void main (String[] args){
phone myMobile = new phone(); // <-- here's the error
myMobile.powerOn();
myMobile.inputNumber(353851234);
myMobile.dial();
}
public class phone{
boolean poweredOn = false;
int currentDialingNumber;
void powerOn(){
poweredOn = true;
System.out.println("Hello");
}
void powerOff(){
poweredOn = false;
System.out.println("Goodbye");
}
void inputNumber(int num){
currentDialingNumber = num;
}
void dial(){
System.out.print("Dialing: " + currentDialingNumber);
}
}
}
This may not make sense to you if you’re new to Java, but a instantiating a non-static inner class (
phone) requires an instance of the enclosing class (OOPTutorial).In plain English, this roughly means that you either
Can only do
new phone()inside a OOPTutorial-method that is not marked asstatic, oryou need to make
phonea top level class (i.e. move it outside the scope ofOOPTutorial), oryou need to make the inner class
phoneas static (by puttingstaticin front of the class declaration)