Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

JAVA!!! You can have many classes in a single Java file. Only one of them can be

ID: 3859112 • Letter: J

Question

JAVA!!! You can have many classes in a single Java file. Only one of them can be public, and the file must be named the same as that class. This is not usual practice – except for experimenting with many small classes so you can more easily see how the inheritance is working. Create a small project with this code. (must be called C.java if you put them all in one file): class A { public A(int x) { } } class B extends A { public B() { } } public class C { public static void main(String[] args) { B b = new B(); } } What is the compilation error on this line? public B() Explain it. There are 2 possible fixes. What are they? Take a screen shot of your fixed code and paste it in your submission.

Explanation / Answer

Hey,

Given below is your code which I have reformatted.

The problem with the above code is that class A don't has a default constructor (A default constructor is a type of constructor which takes no arguments). So Any class which extends A has to call the constructor of the superclass. Here B is the superclass without default constructor. A's constructor accepts an argument of type int. B is the subclass of A which is trying to provide a default constructor without calling superclass constructor and it's the problem. B being the subclass, has to call the superclass implementation of the constructor. In order to fix this, you can make B's constructor accept a parameter of type int and then call A's constructor using the keyword super.

Below is the fixed code.

If you don't want B constructor to accept a parameter, then you can also call A's constructor with some default value like

...

...

Queries are welcomed so do comment if you have any. Also give a thumbs us if this answer helped you.