Java error: class, interface, or enum expected

80,953

Solution 1

For example:

public class Example {

    public static void main(String...args) {
        new C();
    }

    public static class A {
        public A() {
            System.out.println("A");
        }
    }
    public static class B extends A {
        public B() {
            System.out.println("B");
        }
    }
    public static class C extends B {
        public C() {
            System.out.println("C");
        }
    }
}

Also note that this might not print what you would expect. It would actually print:

A
B
C

Why? Constructors are always chained to the super class.

Solution 2

Put your main method in a class.

Filename : DemoClass.java

class A 
{ 
    public A() 
    {
        System.out.println ("A");
    }
}
class B extends A 
{
    public B() 
    {
        System.out.println ("B");
    }
}
class C extends B 
{ 
    public C() 
    {
        System.out.println ("C");
    }
}

public class DemoClass {

   public static void main(String args[]) {

       A a = new A();  
       B b = new B();  
       C c = new C();  
   }
}

Another point here is, you can have only public class in a file, so your A B and C all class can't be public in same java file.

Your java file name must be same as public class name. i.e. here DemoClass is public class so file name will be DemoClass.java

Java doc for getting started : getting started with java

Share:
80,953
Z9z9z9
Author by

Z9z9z9

Updated on July 09, 2022

Comments

  • Z9z9z9
    Z9z9z9 almost 2 years

    I need to know the output of this code. But it's not working. Maybe the code is wrong. I'm still learning how to use Java, and I tried fixing this for hours but still no luck.

    Here is the code:

    public class A 
    { 
        public A() 
        {
            System.out.println ("A");
        }
    }
    public class B extends A 
    {
        public B() 
        {
            System.out.println ("B");
        }
    }
    public class C extends B 
    { 
        public C() 
        {
            System.out.println ("C");
        }
    }
    
    public static void main(String args[]) {
    
        A a = new A();  
        B b = new B();  
        C c = new C();  
    }
    

    Can anyone tell me what is wrong or missing in the code?