Reputation: 13
Q)i got one compile error 10::non-static variable this can not be refferenced from the static content
what to do now??
class Computer
{
void method()
{
System.out.println("this i objects");
}
public static void main(String[] args)
{
Laptop mtd = new Laptop();
Computer mtd1 = new Computer();
mtd.method();
mtd1.method();
}
class Laptop
{
void method()
{
System.out.println("using laptop method");
}
}
}
Upvotes: 0
Views: 70
Reputation: 3783
Laptop is an inner class of Computer, thus you have to instantiate Laptop from a Computer instance. Or you can mark your inner Laptop class as static, then you can instantiate it directly. My example demonstrates both approaches:
class Computer
{
public static void main(String[] args)
{
Computer computer = new Computer();
computer.method();
// Instantiate normal inner class from instance object.
Laptop laptop = computer.new Laptop(); // Or: new Computer().new Laptop();
laptop.method();
// Instantiate static inner class directly.
StaticLaptop staticLaptop = new StaticLaptop();
staticLaptop.method();
}
void method()
{
System.out.println("I'm Computer!");
}
class Laptop
{
void method()
{
System.out.println("I'm Laptop!");
}
}
static class StaticLaptop
{
void method()
{
System.out.println("I'm StaticLaptop!");
}
}
}
Upvotes: 1
Reputation: 8591
You've put Laptop
inside the Computer
class.
You should refactor to static class Laptop
. Otherwise you are tying a Laptop instance to a specific Computer instance, which you probably don't want to do. (If you really wanted to do that, you'd have to write new Computer().new Laptop();
)
Although I think, in reality, you want to write
class Laptop extends Computer
which is called inheritance.
Upvotes: 0