Extending a class in Java without initializing - java

public class LinkedListStructs {
public LinkedList l1 = new LinkedList();
public LinkedListStructs(){
ListNode h1 = new ListNode(4);
ListNode h2 = new ListNode(3);
ListNode h3 = new ListNode(12);
ListNode h4 = new ListNode(9);
ListNode h5 = new ListNode(9);
ListNode h6 = new ListNode(4);
l1.head = h1;
h1.next = h2;
h2.next = h3;
h3.next = h4;
h4.next = h5;
h5.next = h6;
}
}
Then I extend this in my other class:
public class Tester extends LinkedListStructs{
public void removeDupsTest(){
l1.printList();
l1.removeDups();
l1.printList();
}
}
I didn't initialize a new instance of LinkedListStructs. My question is, when I extend a class, is an instance automatically created?
I am confused because I used LinkedList l1 in my tester class, but the object itself needs to be initialized with a constructor as you see with public LinkedListStructs(){}
So, how does it work? If I don't create an instance, initialize properties of linked list then how is it possible to use it?
Thanks

To use your Tester, you have to create an instance of it. When you create it, you are calling its constructor.
Since you haven't specified a constructor, the compiler creates one for you. Your empty constructor will call the superclass constructor.
To test this, add an empty constructor to your Tester class and printLns in both the Tester and LinkedListStructs constructor. You will see the tester constructor called, which in turn will call the superclass constructor.
Note that your empty constructor must call super(), which calls the superclass constructor.

Java figures it out for you: when you extend a class that has a parameterless constructor, and do not define a constructor, your derived class automatically gets a default constructor:
JLS section 8.8.9:
If a class contains no constructor declarations, then a default constructor with no parameters is automatically provided.
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.
When you construct an instance of Tester, the constructor of its base class LinkedListStructs gets called, initializing the list l1.

To answer your doubt:
Since you have extended the LinkedListStructs and created a new class Tester (meaning of 'public class Tester extends LinkedListStructs')
All the behaviour will be available in the derived(or extended) class. This is the fundamental of Inheritance (and hence reusability). You may choose to override it as well. This is for polymorphism (you can have 'implements' to achive this).
Since, there is no explicit constructor in Tester class. The default constructor will be called, which in turn will call all its super classes constructor. Default constructor documentation can be found here.
I guess that's the direct answer to your question.

Related

Java LinkedList has empty constructor in its source code

Is what I write below about LinkedList.java in jdk-8u111 correct?
/**
* Constructs an empty list.
*/
public LinkedList() {
}
We can see there exists no code in the constructor and the purpose of
such a strange constructor is for later subclasses. As we know that
the compiler would automatically provide a no-argument super() to
a subclass constructor if the constructor has no explicit super()
call. The compiler would report an error if the parent class had no such
no-argument constructor.
Error:(x, y) java: no suitable constructor found for parent class(no arguments)
We can conclude that the empty constructor of LinkedList is for subclass use.
No, it's nothing to do with subclasses.
If you don't define any constructors then Java will automatically add a default constructor. However, if you do define other constructors then the default constructor must be written out. Because this constructor exists:
LinkedList(Collection<? extends E> c);
The default constructor must be explicitly defined:
LinkedList();
It works and has no error if I do not write out an explicit empty default constructor. The compiler executes successfully. So it is okay not to write it out? What is the need to write it out if we already have another constructor?
With no constructors, a default one is added and we can successfully call new Thing():
class Thing {
}
Thing t = new Thing();
With a non-default constructor added, Java no longer adds a default constructor on its own. Now new Thing() is an error.
class Thing {
public Thing(int foo) { }
}
Thing t = new Thing();
Result:
Test.java:7: error: constructor Thing in class Thing cannot be applied to given types;
Thing t = new Thing();
^
required: int
found: no arguments
reason: actual and formal argument lists differ in length
1 error
We must write out the default constructor for the code to compile:
class Thing {
public Thing() { }
public Thing(int foo) { }
}
Thing t = new Thing();

can you use default and parameter constructor at the same time?

I have been assigned to make a class using both default and parameter constructor but the thing is, is that even possible? I don't get how it can even work..both are supposed to assign values to variables
Borrowed from this answer from #bohemian
public class Person
...
public Person() {
this("unknown", 0); // you can call another constructor
}
public Person(String nm, int ag) {
name = nm;
age = ag;
}
...
}
In this example if the no-args constructor is called then unknown and 0 will be passed to the other constructor
When you define another constructor in your class, you do not get the "usual" default constructor (public and without arguments) anymore.
However, you can add it back in:
class MyClass{
MyClass(String param){} // custom constructor
MyClass(){} // bring back the non-arg one
}
Of course, when creating an object instance using new you have to choose which one to call (you cannot have both):
MyClass instanceA = new MyClass("a string");
MyClass instanceB = new MyClass();
The constructors can call each-other (using this(parameters)) or shared methods if there is common functionality in them that you want to keep in one place.
Actually you can't do that in Java, by definition.JLS §8.8.9, http://docs.oracle.com/javase/specs/jls/se8/html/jls-8.html#jls-8.8.9 says, "If a class contains no constructor declarations, then a default constructor is implicitly declared." So as soon as you add any constructor declaration, even a no-arg constructor, you don't get a default constructor.

Does a subclass in Java need a constructor if there is one for the superclass? [duplicate]

What exactly is a default constructor — can you tell me which one of the following is a default constructor and what differentiates it from any other constructor?
public Module() {
this.name = "";
this.credits = 0;
this.hours = 0;
}
public Module(String name, int credits, int hours) {
this.name = name;
this.credits = credits;
this.hours = hours;
}
Neither of them. If you define it, it's not the default.
The default constructor is the no-argument constructor automatically generated unless you define another constructor. Any uninitialised fields will be set to their default values. For your example, it would look like this assuming that the types are String, int and int, and that the class itself is public:
public Module()
{
super();
this.name = null;
this.credits = 0;
this.hours = 0;
}
This is exactly the same as
public Module()
{}
And exactly the same as having no constructors at all. However, if you define at least one constructor, the default constructor is not generated.
Reference: Java Language Specification
If a class contains no constructor declarations, then a default constructor with no formal parameters and no throws clause is implicitly declared.
Clarification
Technically it is not the constructor (default or otherwise) that default-initialises the fields. However, I am leaving it the answer because
the question got the defaults wrong, and
the constructor has exactly the same effect whether they are included or not.
A default constructor is created if you don't define any constructors in your class. It simply is a no argument constructor which does nothing. Edit: Except call super()
public Module(){
}
A default constructor is automatically generated by the compiler if you do not explicitly define at least one constructor in your class. You've defined two, so your class does not have a default constructor.
Per The Java Language Specification Third Edition:
8.8.9 Default Constructor
If a class contains no constructor
declarations, then a default
constructor that takes no parameters
is automatically provided...
Hi. As per my knowledge let me clear the concept of default constructor:
The compiler automatically provides a no-argument, default constructor
for any class without constructors. This default constructor will call
the no-argument constructor of the superclass. In this situation, the
compiler will complain if the superclass doesn't have a no-argument
constructor so you must verify that it does. If your class has no
explicit superclass, then it has an implicit superclass of Object,
which does have a no-argument constructor.
I read this information from the Java Tutorials.
Java provides a default constructor which takes no arguments and performs no special actions or initializations, when no explicit constructors are provided.
The only action taken by the implicit default constructor is to call the superclass constructor using the super() call. Constructor arguments provide you with a way to provide parameters for the initialization of an object.
Below is an example of a cube class containing 2 constructors. (one default and one parameterized constructor).
public class Cube1 {
int length;
int breadth;
int height;
public int getVolume() {
return (length * breadth * height);
}
Cube1() {
length = 10;
breadth = 10;
height = 10;
}
Cube1(int l, int b, int h) {
length = l;
breadth = b;
height = h;
}
public static void main(String[] args) {
Cube1 cubeObj1, cubeObj2;
cubeObj1 = new Cube1();
cubeObj2 = new Cube1(10, 20, 30);
System.out.println("Volume of Cube1 is : " + cubeObj1.getVolume());
System.out.println("Volume of Cube1 is : " + cubeObj2.getVolume());
}
}
General terminology is that if you don't provide any constructor in your object a no argument constructor is automatically placed which is called default constructor.
If you do define a constructor same as the one which would be placed if you don't provide any it is generally termed as no arguments constructor.Just a convention though as some programmer prefer to call this explicitly defined no arguments constructor as default constructor. But if we go by naming if we are explicitly defining one than it does not make it default.
As per the docs
If a class contains no constructor declarations, then a default constructor with no formal parameters and no throws clause is implicitly declared.
Example
public class Dog
{
}
will automatically be modified(by adding default constructor) as follows
public class Dog{
public Dog() {
}
}
and when you create it's object
Dog myDog = new Dog();
this default constructor is invoked.
default constructor refers to a constructor that is automatically generated by the compiler in the absence of any programmer-defined constructors.
If there's no constructor provided by programmer, the compiler implicitly declares a default constructor which calls super(), has no throws clause as well no formal parameters.
E.g.
class Klass {
// Default Constructor gets generated
}
new Klass(); // Correct
-------------------------------------
class KlassParameterized {
KlassParameterized ( String str ) { //// Parameterized Constructor
// do Something
}
}
new KlassParameterized(); //// Wrong - you need to explicitly provide no-arg constructor. The compiler now never declares default one.
--------------------------------
class KlassCorrected {
KlassCorrected (){ // No-arg Constructor
/// Safe to Invoke
}
KlassCorrected ( String str ) { //// Parameterized Constructor
// do Something
}
}
new KlassCorrected(); /// RIGHT -- you can instantiate
If a class doesn't have any constructor provided by programmer, then java compiler will add a default constructor with out parameters which will call super class constructor internally with super() call. This is called as default constructor.
In your case, there is no default constructor as you are adding them programmatically.
If there are no constructors added by you, then compiler generated default constructor will look like this.
public Module()
{
super();
}
Note: In side default constructor, it will add super() call also, to call super class constructor.
Purpose of adding default constructor:
Constructor's duty is to initialize instance variables, if there are no instance variables you could choose to remove constructor from your class. But when you are inheriting some class it is your class responsibility to call super class constructor to make sure that super class initializes all its instance variables properly.
That's why if there are no constructors, java compiler will add a default constructor and calls super class constructor.
When we do not explicitly define a constructor for a class, then java creates a default constructor for the class. It is essentially a non-parameterized constructor, i.e. it doesn't accept any arguments.
The default constructor's job is to call the super class constructor and initialize all instance variables. If the super class constructor is not present then it automatically initializes the instance variables to zero. So, that serves the purpose of using constructor, which is to initialize the internal state of an object so that the code creating an instance will have a fully initialized, usable object.
Once we define our own constructor for the class, the default constructor is no longer used. So, neither of them is actually a default constructor.
When you don’t define any constructor in your class, compiler defines default one for you, however when you declare any constructor (in your example you have already defined a parameterized constructor), compiler doesn’t do it for you.
Since you have defined a constructor in class code, compiler didn’t create default one. While creating object you are invoking default one, which doesn’t exist in class code. Then the code gives an compilation error.
When you create a new Module object, java compiler add a default constructor for you because there is no constructor at all.
class Module{} // you will never see the default constructor
If you add any kind of constructor even and non-arg one, than java thing you have your own and don't add a default constructor anymore.
This is an non-arg constructor that internelly call the super() constructor from his parent class even you don't have one. (if your class don't have a parent class than Object.Class constructor will be call)
class Module{
Module() {} // this look like a default constructor but in not.
}
A default constructor does not take any arguments:
public class Student {
// default constructor
public Student() {
}
}
I hope you got your answer regarding which is default constructor.
But I am giving below statements to correct the comments given.
Java does not initialize any local variable to any default value. So
if you are creating an Object of a class it will call default
constructor and provide default values to Object.
Default constructor provides the default values to the object like 0,
null etc. depending on the type.
Please refer below link for more details.
https://www.javatpoint.com/constructor

Why superclass constructor Building() is invoked when I say new House("x ")?

I have the following code but I don't get why when I run this it prints "b" before printing "h hn x". Why does "b" get printed at all since I am not calling the superclass Building at all when I execute House().
class Building {
Building() {
System.out.print("b ");
}
Building(String name) {
this();
System.out.println("bn " + name);
}
}
public class House extends Building {
House() {
System.out.println("h ");
}
House(String name) {
this();
System.out.println("hn " + name);
}
public static void main(String[] args) {
new House("x ");
}
}
The zero-arg constructor of a superclass is implicitly called by the constructor of its subclass, automatically.
More generally, for
class B extends A
The constructor
public B()
{
//Your code
}
Actually looks like
public B()
{
super(); //Call the superclass constructor
//Your code
}
You can override this behavior by making an explicit call to some other superclass constructor. Note that if the implicit call to the constructor cannot be made (like if your no-arg constructor doesn't exist), then you will see an error.
The superclass constructor is always called whenever a subclass is being constructed. If the superclass constructor does not require any arguments, as is the case here, this call can be made implicitly.
If you were to introduce an argument in the constructor for Building, you'd get an error in House as it will require you to explicitly call the new superclass constructor.
Official resource:
From the Oracle javase tutoriel:
With super(), the superclass no-argument constructor is called. With
super(parameter list), the superclass constructor with a matching
parameter list is called. Note: 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. Object does have such a constructor, so if
Object is the only superclass, there is no problem.
If a subclass constructor invokes a constructor of its superclass,
either explicitly or implicitly, you might think that there will be a
whole chain of constructors called, all the way back to the
constructor of Object. In fact, this is the case. It is called
constructor chaining, and you need to be aware of it when there is a
long line of class descent.
Additional resource:
The section Constructor Chaining From the SCJP 6 book explains clearly what you are looking for with in a simple manner, it provides also a little more informations about this process:
We know that constructors are invoked at runtime when you say new on
some class type as follows: Horse h = new Horse(); But what really
happens when you say new Horse() ? (Assume Horse extends Animal and
Animal extends Object.)
Horse constructor is invoked. Every constructor invokes the constructor of its superclass with an (implicit) call to super(),
unless the constructor invokes an overloaded constructor of the same
class (more on that in a minute).
Animal constructor is invoked (Animal is the superclass of Horse).
Object constructor is invoked (Object is the ultimate superclass of all classes, so class Animal extends Object even though you don't
actually type "extends Object" into the Animal class declaration. It's
implicit.) At this point we're on the top of the stack.
Object instance variables are given their explicit values. By explicit values, we mean values that are assigned at the time the
variables are declared, like "int x = 27", where "27" is the explicit
value (as opposed to the default value) of the instance variable.
Object constructor completes.
Animal instance variables are given their explicit values (if any).
Animal constructor completes.
Horse instance variables are given their explicit values (if any).
Horse constructor completes.
Analogy with your example:
So when you said new House("x "), here is what happens:
The House(String name) invokes House() as specified by the keyword this().
The House() constructor implicitly calls super() which invoks the construcotr Building().
The Building() constructor implicitly calls super() which is the Object constructor.
The Object constructor completes
The Building() constructor will complete and print "b "
The House() constructor will complete and print "h"
The House(String name) constructor will complete and print "hn x ".
The result is "b h hn x "
NB: Building(String name) would be invoked if you added an explicit call from House() to super("someString"), in that case the result will be: "b bn someString h hn x "
In inheritance it is necessary to initialize all the fields present in super-class first, because those fields are get used in subclasses, for this before construction of your subclass super class constructor get called to initialize all the field present in your super class.
Super class constructor called when you construct subclass instance. In your code you are creating new House("x "); Instance of House.
It calls House parametrized constructor House(String name) at this time your super class implicit constructor get called.
If you step through program the call stack shows what's happing:
(you need to follow the call stack from bottom to top):
House(Building).<init>() line: 3
House.<init>() line: 2
House.<init>(String) line: 7
House.main(String[]) line: 12
First Main is called
Then in the House(name) constructor this() is called
This calls the House() constructor (because no argument is provided)
Now comes the interesting part: because the Default constructor is called and House is derived from Building, it is required to construct the Building first which by specification is the default constructor of the parent class Building.

Java default constructor

What exactly is a default constructor — can you tell me which one of the following is a default constructor and what differentiates it from any other constructor?
public Module() {
this.name = "";
this.credits = 0;
this.hours = 0;
}
public Module(String name, int credits, int hours) {
this.name = name;
this.credits = credits;
this.hours = hours;
}
Neither of them. If you define it, it's not the default.
The default constructor is the no-argument constructor automatically generated unless you define another constructor. Any uninitialised fields will be set to their default values. For your example, it would look like this assuming that the types are String, int and int, and that the class itself is public:
public Module()
{
super();
this.name = null;
this.credits = 0;
this.hours = 0;
}
This is exactly the same as
public Module()
{}
And exactly the same as having no constructors at all. However, if you define at least one constructor, the default constructor is not generated.
Reference: Java Language Specification
If a class contains no constructor declarations, then a default constructor with no formal parameters and no throws clause is implicitly declared.
Clarification
Technically it is not the constructor (default or otherwise) that default-initialises the fields. However, I am leaving it the answer because
the question got the defaults wrong, and
the constructor has exactly the same effect whether they are included or not.
A default constructor is created if you don't define any constructors in your class. It simply is a no argument constructor which does nothing. Edit: Except call super()
public Module(){
}
A default constructor is automatically generated by the compiler if you do not explicitly define at least one constructor in your class. You've defined two, so your class does not have a default constructor.
Per The Java Language Specification Third Edition:
8.8.9 Default Constructor
If a class contains no constructor
declarations, then a default
constructor that takes no parameters
is automatically provided...
Hi. As per my knowledge let me clear the concept of default constructor:
The compiler automatically provides a no-argument, default constructor
for any class without constructors. This default constructor will call
the no-argument constructor of the superclass. In this situation, the
compiler will complain if the superclass doesn't have a no-argument
constructor so you must verify that it does. If your class has no
explicit superclass, then it has an implicit superclass of Object,
which does have a no-argument constructor.
I read this information from the Java Tutorials.
Java provides a default constructor which takes no arguments and performs no special actions or initializations, when no explicit constructors are provided.
The only action taken by the implicit default constructor is to call the superclass constructor using the super() call. Constructor arguments provide you with a way to provide parameters for the initialization of an object.
Below is an example of a cube class containing 2 constructors. (one default and one parameterized constructor).
public class Cube1 {
int length;
int breadth;
int height;
public int getVolume() {
return (length * breadth * height);
}
Cube1() {
length = 10;
breadth = 10;
height = 10;
}
Cube1(int l, int b, int h) {
length = l;
breadth = b;
height = h;
}
public static void main(String[] args) {
Cube1 cubeObj1, cubeObj2;
cubeObj1 = new Cube1();
cubeObj2 = new Cube1(10, 20, 30);
System.out.println("Volume of Cube1 is : " + cubeObj1.getVolume());
System.out.println("Volume of Cube1 is : " + cubeObj2.getVolume());
}
}
General terminology is that if you don't provide any constructor in your object a no argument constructor is automatically placed which is called default constructor.
If you do define a constructor same as the one which would be placed if you don't provide any it is generally termed as no arguments constructor.Just a convention though as some programmer prefer to call this explicitly defined no arguments constructor as default constructor. But if we go by naming if we are explicitly defining one than it does not make it default.
As per the docs
If a class contains no constructor declarations, then a default constructor with no formal parameters and no throws clause is implicitly declared.
Example
public class Dog
{
}
will automatically be modified(by adding default constructor) as follows
public class Dog{
public Dog() {
}
}
and when you create it's object
Dog myDog = new Dog();
this default constructor is invoked.
default constructor refers to a constructor that is automatically generated by the compiler in the absence of any programmer-defined constructors.
If there's no constructor provided by programmer, the compiler implicitly declares a default constructor which calls super(), has no throws clause as well no formal parameters.
E.g.
class Klass {
// Default Constructor gets generated
}
new Klass(); // Correct
-------------------------------------
class KlassParameterized {
KlassParameterized ( String str ) { //// Parameterized Constructor
// do Something
}
}
new KlassParameterized(); //// Wrong - you need to explicitly provide no-arg constructor. The compiler now never declares default one.
--------------------------------
class KlassCorrected {
KlassCorrected (){ // No-arg Constructor
/// Safe to Invoke
}
KlassCorrected ( String str ) { //// Parameterized Constructor
// do Something
}
}
new KlassCorrected(); /// RIGHT -- you can instantiate
If a class doesn't have any constructor provided by programmer, then java compiler will add a default constructor with out parameters which will call super class constructor internally with super() call. This is called as default constructor.
In your case, there is no default constructor as you are adding them programmatically.
If there are no constructors added by you, then compiler generated default constructor will look like this.
public Module()
{
super();
}
Note: In side default constructor, it will add super() call also, to call super class constructor.
Purpose of adding default constructor:
Constructor's duty is to initialize instance variables, if there are no instance variables you could choose to remove constructor from your class. But when you are inheriting some class it is your class responsibility to call super class constructor to make sure that super class initializes all its instance variables properly.
That's why if there are no constructors, java compiler will add a default constructor and calls super class constructor.
When we do not explicitly define a constructor for a class, then java creates a default constructor for the class. It is essentially a non-parameterized constructor, i.e. it doesn't accept any arguments.
The default constructor's job is to call the super class constructor and initialize all instance variables. If the super class constructor is not present then it automatically initializes the instance variables to zero. So, that serves the purpose of using constructor, which is to initialize the internal state of an object so that the code creating an instance will have a fully initialized, usable object.
Once we define our own constructor for the class, the default constructor is no longer used. So, neither of them is actually a default constructor.
When you don’t define any constructor in your class, compiler defines default one for you, however when you declare any constructor (in your example you have already defined a parameterized constructor), compiler doesn’t do it for you.
Since you have defined a constructor in class code, compiler didn’t create default one. While creating object you are invoking default one, which doesn’t exist in class code. Then the code gives an compilation error.
When you create a new Module object, java compiler add a default constructor for you because there is no constructor at all.
class Module{} // you will never see the default constructor
If you add any kind of constructor even and non-arg one, than java thing you have your own and don't add a default constructor anymore.
This is an non-arg constructor that internelly call the super() constructor from his parent class even you don't have one. (if your class don't have a parent class than Object.Class constructor will be call)
class Module{
Module() {} // this look like a default constructor but in not.
}
A default constructor does not take any arguments:
public class Student {
// default constructor
public Student() {
}
}
I hope you got your answer regarding which is default constructor.
But I am giving below statements to correct the comments given.
Java does not initialize any local variable to any default value. So
if you are creating an Object of a class it will call default
constructor and provide default values to Object.
Default constructor provides the default values to the object like 0,
null etc. depending on the type.
Please refer below link for more details.
https://www.javatpoint.com/constructor

Categories

Resources