super class not having a no-argument constructor [duplicate] - java

This question already has answers here:
I don't understand this part in Oracle docs?
(4 answers)
Closed 3 years ago.
According to Oracle's documentation https://docs.oracle.com/javase/tutorial/java/IandI/super.html, its written that If the super class does not have a no-argument constructor, you will get a compile-time error.
But in my case, I have a super class without any constructor. In my baseclass, I am writing super() in its no-arg constructor. Here, I don't have a no-arg constructor in super class, but its not showing any error.
class Person {
}
/* subclass Student extending the Person class */
class Student extends Person {
Student() {
// invoke or call parent class constructor
super();
System.out.println("Student class Constructor");
}
}
// Driver class
class Practice {
public static void main(String[] args) {
Student s = new Student();
}
}

This assumption is wrong:
Here, I don't have a no-arg constructor in super class, but its not showing any error.
If a class has no explicit constructor then it will have an implied no-argument constructor.
Please check out this related Stack Overflow question for more: Java default constructor
Also check out the Java Language Specification: §8.8.9. Default Constructor:
If a class contains no constructor declarations, then a default constructor is implicitly declared. The form of the default constructor for a top level class, member class, or local class is as follows:
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.

Related

How to declare a constructor in a subclass when the superClass does not have a constructor

I am trying to implement a constructor for a subclass, however I keep getting "error: class, interface, or enum expected" when I compile.
My code for the overall looks like this:
public class Super{
//methods go here, no constructor.
}
Here is what I tried but it did not work:
public class Sub extends Super{
private boolean myCondition;
public Sub(boolean condition){
super();
myCondition = condition;
}
}
I would assume that I would not need to call super() in the subs constructor as the compiler should implicitly call it.
Thanks.
Every class has a constructor. If you do not specify one, you get a default constructor. JLS-8.8.9 Default Constructor
If a class contains no constructor declarations, then a default constructor with no formal parameters and no throws clause is implicitly declared.
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.
It is a compile-time error if a default constructor is implicitly declared but the superclass does not have an accessible constructor (§6.6) that takes no arguments and has no throws clause.
In a class type, if the class is declared public, then the default constructor is implicitly given the access modifier public (§6.6); if the class is declared protected, then the default constructor is implicitly given the access modifier protected (§6.6); if the class is declared private, then the default constructor is implicitly given the access modifier private (§6.6); otherwise, the default constructor has the default access implied by no access modifier.
So Super (a public class) has a default constructor inserted by the compiler that looks something like
public Super() {
super();
}

How Can newInstance() Work If There Is No Constructor Written?

I've come across an interesting snippet of Java code. I researched what newInstance() is, and it's meant to be a way to avoid calling a constructor and create a new instance of an object. But looking at the example code I don't understand one thing: Why is there no constructor needed?
public class SimpleContentFragment extends WebViewFragment {
protected static SimpleContentFragment newInstance(String file) {
SimpleContentFragment f=new SimpleContentFragment();
Bundle args=new Bundle();
args.putString(KEY_FILE, file);
f.setArguments(args);
return(f);
}
}
No where else in this code is there a constructor created. There is no
public SimpleContentFragment() {
// Required empty public constructor
}
as I would expect.
So could you clarify what is going on in the static method with newInstance? How come it can call new SimpleContentFragment() when the constructor was never written?
This is because Java will create a default, no-arguments constructor if none is provided. It will set all reference fields to null, numeric types to 0, and booleans to false, and invoke the superclass constructor.
JLS 8.8.9:
If a class contains no constructor declarations, then a default
constructor is implicitly declared. The form of the default
constructor for a top level class, member class, or local class is as
follows:
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 error: Implicit super constructor is undefined. Must explicitly invoke another constructor [duplicate]

This question already has answers here:
Java error: Implicit super constructor is undefined for default constructor
(12 answers)
Closed 4 years ago.
I have a BaseClass in a external jar, it has a constructor setting Implementation class(JerseyClientImpl) to jerseyClient.
public BaseClass(AuthDetails auth, String ID) {
setListID(D);
this.jerseyClient = new JerseyClientImpl(auth);
}
I am extending the BaseClass to set my own Implementation class to jerseyClient , but i am getting the error mentioned. Changing the BaseClass to add default constructor is not in my control as i said its an external jar.Can you suggest how can i overcome this error.
Since BaseClass has a non default constructor, it doesn't have the automatically generated parameterless default contstructor.
Therefore your sub-class can't rely on the default constructor (since it won't be able to call the non-existing default constructor of the base class), so your sub-class must have an explicit constructor that calls the constructor of the base class.
Either a constructor with the same parameters :
public SubClass(AuthDetails auth, String ID) {
super(auth,ID);
...
}
Or a constructor without parameters that gives default values for the base-class's constructor :
public SubClass() {
super(null,"something");
...
}
In Java, if you don't explicitly provide a call to a superclass constructor as the first statement in a constructor, then it will insert an implicit call to the default superclass constructor. If there is no default superclass constructor, then you get the error you have mentioned.
The JLS, Section 8.8.7, states:
If a constructor body does not begin with an explicit constructor invocation and the constructor being declared is not part of the primordial class Object, then the constructor body implicitly begins with a superclass constructor invocation "super();", an invocation of the constructor of its direct superclass that takes no arguments.
You must explicitly call the superclass constructor, passing all arguments, with something like this:
public JerseyClientImpl(AuthDetails auth, String ID) {
super(auth, ID);
// Rest of constructor code
}
First of all, if you are writing some parameterized constructor in a class...the default no arg constructor of the class does not exist anymore.
And, when you try to create constructor of its child class, the no-arg constructor of parent class is always called first.If it doesn't exist, you get compiler error.
So, define the no arg constructor in your parent class, OR just call the parameterized constructor of parent class with some value inside the child class constructor.

Code calls new GenericObject() but GenericObject.java doesn't have a constructor

I'm looking through some code that I'm working with and one bit of it strikes me in particular:
In the file there is a block:
public void prepare(){
if (this.GenericObjectID != null)
doStuff();
else{
this.GenericObjet = new GenericObject();
}
However, when I look through GenericObject.java there is no constructor at all. The code runs, but I didn't write it, so I'm not positive how (yet!). So my question is: how is this possible? What is the java compiler doing when it sees this call but then no constructor in the file that describes the object?
If there are no explicit constructors, then the compiler creates an implicit default constructor, with no arguments, that does nothing but implicitly call the superclass constructor.
Section 8.8.9 of the JLS talks about default constructors:
If a class contains no constructor declarations, then a default constructor is implicitly declared. The form of the default constructor for a top level class, member class, or local class is as follows:
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.
new GenericObject(); is the default constructor for the class GenericObject. It is automatically created by the compiler unless you explicitly define a constructor in your class.
This constructor will call the parent class' constructor, and will initialize class member variables to their default values.

Default constructor can be overloaded in a subclass? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
This is question (and answer) from OCJP test exam. And I was very confused about it.
Here is a question review (on Kaplan SelfTest site):
Reviewing Answered
Item 64 of 90Ref: 1Z0-803.6.5.6
Which statement is true about constructor overloading?
A default constructor can be overloaded in the same class.
A default constructor can be overloaded in a subclass.
The constructor must use a different name.
The constructor must use the this keyword.
Explanation:
A default constructor can be overloaded in a subclass. If no constructor is defined for a class, then the compiler will automatically provide the default constructor. Because a subclass can define its own constructors without affecting the superclass, a constructor with parameters can be defined that invokes the superclass constructor, implicitly or explicitly.
A default constructor cannot be overloaded in the same class. This is because once a constructor is defined in a class, the compiler will not create the default constructor. Thus, an attempt to overload the default constructor will effectively remove it from the class.
The constructor must not use a different name. In the same class, an overloaded constructor uses the same name. Because subclasses differ in name from their superclass, an overloaded constructor will have a different name.
The constructor does not need to use the this keyword. The this keyword allows a constructor to reference other constructor methods and/or instance context. Using the this keyword is not required in an overloaded constructor.
Objective:
Working with Methods and Encapsulation
Sub-Objective:
Create and overload constructors
You are getting your terminology wrong.
Overloading only takes place for methods with the same name but different parameters within a specific class.
Overriding takes place for subclasses which have methods with the same "signature" (same name and parameters) as a method in the Superclass.
Note that constuctors aren't "Overridden" (by definition they have different signatures than methods in the superclass).
Instead, the compiler makes a constructor implicitly call the default constructor of its superclass (if one exists) unless you explicitly call a specific constructor of a superclass using the super keyword.
Similarly you cannot "Overload" the constructor of a superclass in a subclass (overloading doesn't work across inheritance), but you can "overload" another constructor within your specific class.
Here is an example of implicit and explicit calls to superclass constructors and overloading constructors:
public class X {
// no default constructor defined so
// compiler adds implicit default constructor here: public X(){}
}
public class Y extends X {
// explicitly declared default-constructor for class Y
public Y() {
// compiler automatically calls implicit X default constructor here
System.out.println("constructing a Y instance");
}
// explicitly declared constructor which overloads the default constructor for Y
public Y(String s) {
// compiler automatically calls implicit X default constructor here
System.out.println("constructing a Y instance with param " + s);
}
}
public class Z extends Y {
// explicitly declared default constructor for Z
public Z() {
super("Z"); // explicitly call the non-default constructor in Y here
System.out.println("constructing a Z instance");
}
}
thus constructing a Z ends up calling X(), then Y("Z") and results in this output:
Z z = new Z();
// outputs: constructing a Y instance with param Z
// constructing a Z instance
And from the docs: (http://docs.oracle.com/javase/tutorial/java/IandI/super.html)
If a constructor does not explicitly invoke a superclass constructor, the Java compiler automatically inserts a call to the no-argument constructor of the superclass. If the super class does not have a no-argument constructor, you will get a compile-time error.
Hope that helps clarify things for you. If in doubt read the docs, write some code, and use System.out.println() to see what's happening.
Constructors are not technically member functions, so they aren't really inherited, and thus cannot be "overloaded". However, they can still be called from the subclass using the super keyword.
//the class being inherited
public class superclass
{
//the constructor
public superclass(some_parameter)
{
//do stuff
}
}
public class subclass extends superclass
{
public subclass(some_parameter)
{
//the super keyword here is used to access the inherited class
super(some_parameter); //this calls the constructor of the inherited class;
}
}
First, overload is not the same as override. Example:
class Foo {
void overloadedMethod() {}
void overloadedMethod(int i) {}
void overridenMethod() {}
}
class Bar extends Foo {
#Override
void overridenMethod() {}
}
Constructor can be overloaded, just as ordinary methods, but cannot be overriden.
For more info see here: link

Categories