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.
Related
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.
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
I am amateur in Java please help me.
I have a class: Account
public class Account {
protected String fullName;
protected String accontNumber;
protected String password;
protected int balance;
public Account(String name, String acc_num, String pass, int b){
fullName = name;
accontNumber = acc_num;
password = pass;
balance = b;
}
}
and I going to create a new class Account2 that inherit from Account
public class Account2 extends Account{
public Account2(String l){
String[] temp = l.split(",");
super.fullName = temp[0];
super.accontNumber = temp[1];
super.password = temp[2];
super.balance = Integer.parseInt(temp[3]);
}
}
But I receive an error message that say: Actual and formal argument list are differ in length
how can I solve this problem?
When the base class has a non-default constructor (one or more parameter), the derived class must call the base class constructor in its constructor with super(paramters). And also notice for constructor, you must have the first line with the super statement, so you must declare a construct with the same parameter, or correctly pass in the parameter within one line, though this is not recommended:
public Account2(String l) {
super(l.split(",")[0],l.split(",")[1],l.split(",")[2],Integer.parseInt(l.split(",")[3]));
}
do like this
public class Account2 extends Account{
public Account2(String l){
super(l.split(",")[0],l.split(",")[1],l.split(",")[2],Integer.parseInt(l.split(",")[3]))
}
}
You haven't placed the super constructor call. So by default it will try to pick super() i.e. no-argument constructor which is not present in Account class
Your current subclass constructor sets the values of the superclass parameters after superclass construction. If you would like to keep that approach, add a no-arg constructor to the superclass that sets default values.
It would be better to use setters rather than accessing the fields directly.
IMHO in this case you sholudn't use a constructor. Create a static method that takes your String input, validates it, splits it into some logical parts and then uses "normal" constructor to create an object:
class Account2 extends Account {
Account2(String name, String acc_num, String pass, int b) {
super(name, acc_num, pass, b);
}
public static Account2 createFromString(String input) {
String[] temp = l.split(",");
if (temp.length != 4) {
throw new RuntimeException("...");
}
return new Account2(temp[0], temp[1], temp[2], Integer.parseInt(temp[3]));
}
}
Your code will be a lot cleaner in my personal opinion:
Account2 acc1 = new Account2("abc", "def", "ghi", 2);
Account2 acc2 = Account2.createFromString("abc,def,ghi,2");
The probelm:
Actual and formal argument list are differ in length
To understand this, a basic understanding of constructors and their behavior under inheritance will help you.
When we define a class without constructors, the compiler inserts a zero argument constructor by itself.
If we write our own constructor with some argument then this default constructor is not inserted by compiler and if required, it has to be added explicitly.
When an instance of a subclass is created , there is an implicit call (very first thing to get executed during constructor invocation) to the superclass constructor by default.
So, if there is no default constructor in superclass (which will be the case when we define our own custom constructor with argument), the compiler will complain.
To get around this, you need to call the constructor with argument as very first line in the subclass constructor or define a default constructor explicitly.
Consider -
public class Class_A {
public void func() {...}
public void func(int a){...}
All three -
Class_A a = new Class_A(); // legal
a.func(); // legal
a.func(1); // legal
But After constructor with arg like public Class_A (int a){...} is added to Class_A , the default constructor become to be -
Class_A a = new Class_A(); // The constructor Class_A() is undefined
Thats force me to add public Class_A() {/*Do Nothing*/} into Class_A .
Since each class has default constructor , why doesn't both default constructor and constructor with arg can exist together just same func() and func(int a) are ?
it has default constructor unless you define your own constructor, in this case you need to re define default constructor
Because If you write a constructor, compiler wouldn't write a default constructor for you. you have to write one explicitly.
From JLS:
If a class contains no constructor declarations, then a default
constructor with no formal parameters and no throws clause is
implicitly declared.
It's the other way around.
If you don't have any constructor you get the no-arg one by default.
The name "default constructor" implies that it is provided when you don't provide one yourself. As soon as you provide your own constructor, the compiler will not generate a default constructor for you.
Be careful not to confuse the default constructor with the no-arg constructor. These are two entirely different things.
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