Java: Extending a Class that has Explicit Constructors
In the following code, why it doesn’t compile, but does when B() is defined?
class B < int x; //B () B (int n) int returnMe () return x;> > class C extends B < >public class Inh3 < public static void main(String[] args) < >>
Solution
the answer to the constructor mystery is that, if one provides any constructor, one must define all constructors.
Peter Molettiere on Apple’s Java forum gave excellent answers:
Because there is no default constructor available in B, as the compiler error message indicates. Once you define a constructor in a class, the default constructor is not included. If you define *any* constructor, then you must define *all* constructors.
When you try to instantiate C, it has to call super() in order to initialize its super class. You don’t have a super(), you only have a super(int n), so C can not be defined with the default constructor C() < super(); >. Either define a no-arg constructor in B, or call super(n) as the first statement in your constructors in C.
So, the following would work:
class B < int x; B() < >// a constructor B( int n ) < x = n; >// a constructor int returnMe() < return x; > > class C extends B
class B < int x; B( int n ) < x = n; >// a constructor int returnMe() < return x; > > class C extends B < C () < super(0); > // a constructor C (int n) < super(n); > // a constructor >
If you want to make sure that x is set in the constructor, then the second solution is preferable.
8.8.9. Default Constructor
- The default constructor has the same accessibility as the class (§6.6).
- The default constructor has no formal parameters, except in a non-private inner member class, where the default constructor implicitly declares one formal parameter representing the immediately enclosing instance of the class (§8.8.1, §15.9.2, §15.9.3).
- The default constructor has no throws clauses.
- If the class being declared is the primordial class Object, then the default constructor has an empty body. Otherwise, the default constructor simply invokes the superclass constructor with no arguments.
Java
Java Basics
Class, Inheritance
Java — Extending Classes
I have a Meeting class and I want to create a BusinessMeeting class which extends Meeting. This is my Meeting class:
public class BusinessMeeting extends Meeting < public BusinessMeeting() < super(); >>
In my BusinessMeeting class, I am getting the error: constructor Meeting in class Meeting cannot be applied to given types; required: String,String,int,int found: no arguments I am not really sure why I am getting that error message. Shouldn’t the BusinessMeeting class inherit all of the variables from my Meeting class?
7 Answers 7
Now say you want to extend your BusinessMeeting class with a businessId .
public class BusinessMeeting < private Integer businessId; public BusinessMeeting(String name, String location, int start, int stop, int business) < // because super calls one of the super class constructors(you can overload constructors), you need to pass the parameters required. super(name, location, start, stop); businessId = business; >>
The constructor you created accepts 4 arguments and you call it without any. If you want it to be initialized without parameters as well — add an empty constructor to Meeting :
Adding an empty constructor to BusinessMeeting won’t help when he calls super(); to a super class that lacks a 0-argument constructor.
You are calling super class constructor with empty argument:
But your super class has the constructor: Meeting(String, String, int, int) .
With super(), the superclass no-argument constructor is called(If it exists). With super(parameter list), the superclass constructor with a matching parameter list is called. So either you have to add an constructor with empty argument to Meeting e.g., public Meeting()<> or you need to call super(String, String, int, int)
public class Meeting < // your variable declaration public Meeting(String name, String location, int start, int stop) < // your assignment >public Meeting()<> > public class BusinessMeeting extends Meeting < public BusinessMeeting() < // super(); un-comment if you need to check by commenting below super("name", "loc", 1, -1); >>
By declaring a constructor, your Meeting class does not have a 0 argument constructor, which is what you’re trying to call with super(); . You need to call a super constructor that matches the available constructors in your super class.
To fix this, add a 0-argument constructor to Meeting class, or call the 4-argument constructor you already have.
As alfasin stated, you have created a constructor. The standard states that this constructor is created if no other constructor is defined. You must create a parameterless constructor yourself if you would like to call super()
Yes and no. It depends on how you declare the variables.
Private variables in the super class are not accessible by the subclass. Usually you add protected getter and setter-Methods to the superclass. Those methods can be used in the subclass to access the variables. (a sometimes sloppy way would be to declare the variables themselve as protected)
A subclass does not inherit the private members of its parent class. However, if the superclass has public or protected methods for accessing its private fields, these can also be used by the subclass. Java Inheritance Webpage
But concerning the error you mentioned: You are calling super() . This means you are calling the default constructor of the superclass. As you have written your own constructor in the superclass, there is no default constructor. Latter one is only created when you do not define a constructor.
Hence, when calling the constructor of the superclass — which takes in your case four arguments — you have to pass these arguments via super() like this:
super(«a name», «a location», 0, 1)
How to extend a class with a constructor
error: constructor calCir in class calCir cannot be applied to given types; class Main extends calCir Im fairly new to Java so im still confused as to how I would use inheritance Here is the full code if needed https://repl.it/NA5S/8
4 Answers 4
This error is due to following reason:
when you create a constructor for a class, there won’t be any default constructor created for that class. so if you extend that class and if the subclass tries to call the no-arg constructor of its super class then there will be an compile-time error.
You have created an explicit constructor for your class. Any explicitly defined constructor will eliminate the default no-args constructor that Java will use implicitly.
Here is the constructor you have created:
In order to use inheritance as requested, you can do any of the following.
- Remove the explicit constructor from the parent class.
- Insert a second construction with no parameters into the parent class:
public class MainSubClass extends CalCir < public MainSubClass() < // Set the radius to default of zero super(0); >public static void main(final String args[]) < // Insert program here >>
First, it is meaningless to have Main extend CalCir in this case.
Second, go back to the specific question you asked.
When you have a class (e.g. Child ) extend from another (e.g. Parent ), in the ctor of Child , it ALWAYS needs to invoke constructor of its parent. If you are not EXPLICITLY invoking any, compiler will automatically assume you are invoking the no-arg constructor of parent.
class Child extends Parent < Child() < // do something >>
class Child extends Parent < Child() < super(); // do something >>
If in Parent , a constructor with arguments is declared, but there is no-arg ctor declared:
it is illegal for Child to invoke the no-arg ctor of Parent , because it simply does not exists.
So you need to explicitly tell the compiler which ctor you want to invoke:
class Child extends Parent < Child() < super(123); // do something >>
Any particular reason why you need to extend CalcCir? Your CalCir has a constructor which requires 2 args, if you are to extend it to your main class, then you would have create a constructor in main like:
Based on the link you provided though, it seems to be more appropriate this way:
Your main class which contains your starting point:
public class Main < public static void main(String[] args) < Scanner b = new Scanner(System.in); while (true) < try < System.out.println("Determining the area/perimeter of a 2D shape."); System.out.println("Choose a shape:\n\nRectangle -->(Type a or rectangle)\nCircle --> (Type b or circle)"); String shape = b.nextLine(); if ((shape.equalsIgnoreCase("Rectangle")) || (shape.equalsIgnoreCase("a"))) < System.out.println("Input Length"); double length = b.nextDouble(); System.out.println("Input width"); double width = b.nextDouble(); Shape rectangle = new Rectangle(length, width); System.out.println("Area of rectangle is " + rectangle.getArea()); System.out.println("The perimeter is " + rectangle.getPerimeter()); if (length == width)< System.out.println("This is a special type of reactangle, a square!"); >break; > else if ((shape.equalsIgnoreCase("circle")) || (shape.equalsIgnoreCase("b"))) < System.out.println("Input Radius"); double radius = b.nextDouble(); Shape circle = new Circle(radius); System.out.println("Area of circle is " + circle.getArea()); System.out.println("The circumference is " + circle.getPerimeter()); break; >else < System.out.println("Not valid choice\n"); >> catch (Exception e) < System.out.println("Not valid choice\n"); >> > >
Then your Circle and Rectangle classes:
public class Circle extends Shape < private double radius; public Circle(double radius) < this.radius = radius; >@Override double getArea() < return Math.PI * (radius * radius); >@Override double getPerimeter() < return 2 * Math.PI * radius; >> public class Rectangle extends Shape < private double length; private double width; public Rectangle(double length, double width) < this.length = length; this.width = width; >@Override double getArea() < return length * width; >@Override double getPerimeter() < return 2 * (length + width); >>
Of which both inherited from shape
public abstract class Shape