Search code examples
javacompiler-errorsjavac

Java error: class, interface, or enum expected


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?


Solution

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