0

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");         
     }    
  }    
}
3
  • 1
    Your code is quite spacious. Commented Jul 9, 2015 at 11:44
  • i didnt gave that much space in original program @P45Imminent Commented Jul 9, 2015 at 11:46
  • 2
    So you added some for our pleasure? How can I express my gratitude? Commented Jul 9, 2015 at 11:46

2 Answers 2

1

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!");  
      }
  }

}
Sign up to request clarification or add additional context in comments.

1 Comment

thank you very munch for your information @stephen henningsen
0

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.

2 Comments

i am new to java language can u explian me what is refactor?? @p45Imminent
Just "change it to". That is, wack in the word static before your class Laptop

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.