-1

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();
    }
}
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
  • 3
    That's because class `Cellphone` is an [inner class](https://docs.oracle.com/javase/tutorial/java/javaOO/nested.html). To make this work, make it a `static` nested class: `static class Cellphone`. – Jesper May 11 '22 at 08:09

1 Answers1

0
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.

AhmedSHA256
  • 525
  • 2
  • 20