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?
You can, but it is not recommended, nest your classes in a file. It is perfectly valid.
Notice in the output below that each successive child calls its parent's default constructor (
super()
) implicitly.I recommend you create the files:
A.java
,B.java
,C.java
, andInheritenceTest.java
.Output:
Warning: You shouldn't have more than 1 public classes in 1 java file, not recommended. However, it could still work if you didn't use the 'public' identifier (or by using static or inside another class). But for a starter, I would recommend you to have them all in separate files.
Error: Your main method does not belong to any class. I propose you create another class that includes the public static void main method to test your application.
Info: keep a look at inheritance as your printings might not be what you expect. (Constructor of class B calls the constructor of A, and constructor of class C calls the constructor B which in turn calls the constructor of A).
That's why you get
In your case, I would try the following:
Put your main method in a class.
Another point here is, you can have only public class in a file, so your
A
B
andC
all class can't bepublic
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 beDemoClass.java
Java doc for getting started : getting started with java
For example:
Also note that this might not print what you would expect. It would actually print:
Why? Constructors are always chained to the super class.