declaring and invoking constructor - java

Below code shows error at line 4
class MyClass{
public MyClass(int a){ } //Line 2
public static void main(String a[]){
MyClass n = new MyClass(); //Line 4
System.out.print("TRUE");
}
}
But, once i remove line 2, it runs without any error. Although, I didn't add default constructor. Why ?

Remember that Compiler provides your class with a default constructor only if you have not given any explicit constructor. As soon as you declare your own constructor, parameterized or 0-arg, the compiler won't give you the default constructor.
Now in your code, you have declared a parameterized constructor, compiler won't give a default one. So, you actually don't have any 0-arg constructor, and hence you cannot use it.
once i remove line 2, it runs without any error. Although, I didn't
add default constructor. Why ?
Of course if you remove your line 2, then you haven't declared any explicit constructor, in which case Compiler adds a default 0-arg constructor, and hence your code succeeds. Also note that the default constructor is the one give by compiler. When you declare your 0-arg constructor, it's not called a default one, but just a 0-arg constructor.
So, whenever you are declaring a parameterized constructor, make sure that you also declare a 0-arg constructor explicitly, if of course you are using it.
public MyClass() {
}

Each class will have an implicit default constructor, which takes no arguments. However, when you declare a constructor with args, the default constructor is omitted. Hence
MyClass n = new MyClass();
will fail to compile.
Note that a class can have multiple constructors, and you can declare the default no-arg constructor explicitly if you have other constructors. e.g.
class MyClass{
public MyClass(int a){ }
public MyClass(String a){ }
public MyClass(){ } // no-arg declaration now required
}

That's because once you declared a constructor with parameters, the default constructor without parameters is no longer available.

In your class default constructor is missing , it contains only parameterised constructor. But you are initializing using default constructor. So you will get error at line 4.
Add default constructor too in your code as blow
as your creating object with default constructor MyClass n = new MyClass(); your code should have default constructor.
public MyClass(){ }
now it will work with out any error.
If you want to go with paramertised constructor, then create object as below.
MyClass n = new MyClass(pass parameter here);

if you have no constructors defined in the class then only compiler will automatically insert default constructor (no-args)
Read the last paragraph at http://docs.oracle.com/javase/tutorial/java/javaOO/constructors.html

When you create parameterized cunstructor then default constructor is removed unless you create you own default constructor.
Hence you have to create constructor as below.
public MyClass(){}

Related

What does the default constructor really do? [duplicate]

This question already has answers here:
What is the actual use of the default constructor in java?
(7 answers)
Closed 4 years ago.
There is something that I don't understand about the real role of the default constructor in java. In the official tutorial about object creation :
Creating Objects
All classes have at least one constructor. If a class does not explicitly declare any, the Java compiler automatically provides a no-argument constructor, called the default constructor. This default constructor calls the class parent's no-argument constructor, or the Object constructor if the class has no other parent. If the parent has no constructor (Object does have one), the compiler will reject the program.
And in the docs about the Default Constructor (§8.8.9)
8.8.9. Default Constructor
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.
So even the default constructor of the class Object has an empty body. And I know that the default constructor does NOT initialize fields to their default values, because it's the compiler who does that :
Default Values
It's not always necessary to assign a value when a field is declared. Fields that are declared but not initialized will be set to a reasonable default by the compiler.
What I don't understand is, if we didn't declare a constructor, what does the default constructor really do ?
what does the default constructor really do?
It calls super(). As per all your quotations. And does nothing else. JLS #8.8.9:
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.
i.e. it does nothing else. For those who believe it initializes instance variables please see JLS #12.5 where the contrary is asserted.
In Java, if you don´t declare any constructor the compiler create a default constructor and this constructor call to super() method, that is parents constructor. And in this process, inits instance variables like no-default constructors.
What I don't understand is, if we didn't declare a constructor, what
does the default constructor really do ?
By default, if no constructor is declared, a class has a default constructor with no args. I think that's why, by default all constructor calls super(). It follows probably the convention over configuration principle.
Whatever you declare a public constructor or you don't declare at all constructor, first instruction of the constructor is super().
That's why if you define in a class MyClass a constructor with args MyClass(String s) without keeping a constructor with no argument, constructor of MyClass subclasses cannot compile while it doesn't precise in their first instruction, the call to an existing parent constructor, in the exemple, it would be super(String ...).
Here an example :
public class MyClassWithNoArg{
public MyClassWithNoArg(){
}
}
MyClassWithNoArg constructor calls super() in this first instruction even if it not specified in the source code.
It is as if it is written in this way :
public class MyClassWithNoArg{
public MyClassWithNoArg(){
super();
}
}
Imagine now another class MyClassWithArg:
public class MyClassWithArg{
public MyClassWithNoArg(String s){
}
}
And MySubclass a subclass of MyClassWithArg
public class MySubclass extends MyClassWithArg{
public MySubclass (String s){
}
public MySubclass (){
}
}
In both cases, it will not compile since as explained previously all constructors call by default the default constructor (super()) of their parent but here the parent,MyClassWithArg, has no constructor with no arg. So, it doesn't compile.
So to solve the problem, you have to call the super constructor which exists.
public class MySubclass extends MyClassWithArg{
public MySubclass (String s){
super(s);
}
public MySubclass (){
super("");
}
}
Now, compilation is OK.
Without constructor no one can create a object of a class. Now if programmer does not add any constructor with a class then java compiler added a constructor with that class before compilation,which is known as default constructor in java.
But if programmer adds any kind of constructor(with argument or without argument) then that becomes user defined constructor and no constructor 'll be added via java compiler.
Now question is what does constructor do.
allocates memory for new object
if user defines any other operation like initialising variable that is done.

Relating Constructor of Super Class in java

If I create an object of a sub-class with no constructors, then I know that the compiler will implicitly provide a default constructor. What if I create a constructor in the sub-class and try to access the super class constructor using the super keyword, and, now, the super class has no constructor in it. Will the compiler provide a default constructor for the super class as well?
Yes, if there is no specified constructor, there is always default empty constructor
Does the compiler provides a default constructor for the super class also???
The default constructor will be there whether or not there is a subclass that needs it. The default is supplied when the parent is compiled, not later.
...What if I created sub class Constructor and trying to access the super class constructor using the super keyword,and the super class has no constructor in it.
But it does: The default one.
It goes like this.
Lets speak about Object which is the supermost class in java, If you open an editor and just make a class, then it is presumed that It is extending Object. Every class in Java extends from Object. If you do not write your own constructor then Compiler will provide one.
But if you write your own constructor let's say a constructor with one argument, compiler will not provide you with any constructor.
Now lets say taht you extend the above class, then compiler will complain you saying that the superclass does not have a default constructor rather a custom constructor so you need to make one constructor for this child class since first constructor which is called starts from the supermost class that is OBJECT and then proceeds down the line.
Hope this answers comprehensively,
Thanks.
Yes the super always occurs even if you didnt explicit declare
public class FatherTest {
}
public class SonTest extends FatherTest{
public SonTest(String sonName){
super(); // this will always occurs
}
}
If you don't write a constructor for a class, the compiler will implicitly add an empty one for you.
That means this:
public class X {
}
is identical to this:
public class X {
public X() {
// there's also an implicit super(); added here, but that's not directly relevant
}
}
If the super class doesn't have explicit constructor, then an implicit default constructor will be added to it. So your super() will invoke that.
If the super class only have some constructors with parameters. Then super() in the sub-class won't compile. You have to explicitly use one of the defined super-class constructor super(param1, param2, ...), since super() will be called if you don't call it.

Default constructor in Java?

What is the purpose of the default constructor in java
class Bike1 {
Bike1() {
System.out.println("Bike is created");
}
public static void main(String args[]){
Bike1 b=new Bike1();
}
}
The default constructor provides the default values to the objects. The java compiler creates a default constructor only if there is no constructor in the class.
Your example provides a constructor,
Bike1(){System.out.println("Bike is created");}
which means you do not get a default constructor. A default constructor is inserted if you do not provide any constructor. Finally, Bike1 is a no-args constructor with package level (or default) access permission and appears to display a message when an instance of Bike1 is created.
Default constructor means that when you don't create any constructor for your class, the compiler automatically creates a default constructor (with no parameters) to your class at the time of compilation.
In your example you created a constructor. The constructor does not create any objects, it initialize the object.
Default constructors allow you to create objects with known, default settings and behavior. If you call a constructor with arguments, you are creating a custom object. But calling the default constructor will create objects with identical properties every time it is used.
Typically, a default constructor with "no code" doesn't need any code; it already has all the information it needs to create the object.
Remember that default constructor and a constructor with no-args are different.
Since you are defining a constructor Bike1(){} here, the default constructor will loose it's scope and will not be generated automatically.
The default constructor is the no-argument constructor automatically generated unless you define another constructor. It initialises any uninitialised fields to their default values...
follow this link.. Java default constructor
Default constructor have no arguments(parameters) and constructor name is same as class name.It will invoke at the time of object creation.
Example:
class Display{
Display(){
System.out.println("Default Constructor");
}
}
class constructor{
public static void main(String args[]){
Display dis=new Display();
}
}
Output:
Default Constructor
Because when the time of object creation default constructor will invoke automatically.
First thing we need to know that default constructor and no argument constructor are both different things. The no argument constructor is one which we declare inside the class where we actually may or may not write the functionality. The default constructor is one which will be called after object creation. The main purpose of this is to initialize the attributes of the object with their default values.
Java compiler provides a default constructor by default if there is no constructor available in the class

What does this function do in Java?

public class TransparentProxy {
private static ProxyServer _proxyserver = null;
private static TransparentProxy _instance = null;
public TransparentProxy() {
}
public static void main(String args[]) throws Exception {
TransparentProxy.getInstance();
}
I understand everything except the public TransparentProxy() {}. Why is it empty? What is its purpose? Why is it exempt from having a return type?
I have looked it up but can't get an exact answer. Thanks
From the tutorial of the initial part of - Learning the Java Language
A class contains constructors that are invoked to create objects from the class blueprint.
Constructor declarations look like method declarations—except that they use the name of the class
and have no return type.
You don't have to provide any constructors for your class, but you must be careful when doing this.
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.
It looks like you've not read through the basics of Java language yet, you should go through them.
This is an empty constructor. It has no return types and named as the class name.
An empty constructor is needed to create a new instance via reflection by your persistence framework. If you don't provide any additional constructors with arguments for the class, you don't need to provide an empty constructor because you get one per default.
public TransparentProxy() {} ---is a Constructor
Java constructors are the methods with the same name as the Class with no return type/value. They are called or invoked when an object of class is created and can't be called explicitly. An object of a class is created using the new keyword. Ex: TransparentProxy proxy = new TransparentProxy();
Three types of Constructors are present.
1. Default Constructor
JVM internally declares a constructor when no constructor in specified. This is to allow a class to create an instance of it. Also, an Interface in Java does not have a constructor and hence no instances/object can be created.
2. Zero argument Constructor
A constructor defined with no arguments is called a Zero argument Constructor. You may use it to initialize variables to some value to begin with. All objects/instances of the class will have the same initial values.
3. Constructor with arguments
Its a constructor defined with arguments which initialize the variables of the class at the time of object creation. Every object/instance created of that class will have different initial values depending on the values passed to the constructor.
A constructor can be overloaded with different type of arguments or the number of arguments.
It cannot be overrided in a sub class.
Read here -- Why do constructors not return values?

Java inheritance - constructors

While studying for my finals, I came across the following statement in the book from which I am currently studying. Considering the following code :
class A {
public A(int x) { }
}
class B extends A {
public B(int x ) { }
}
is it mandatory to call the constructor of class A in the constructor of class B(super(x)). The book states that it's not mandatory, because they have the exact number and type of parameters. But when I try this in a java compiler, the following error gets thrown :
constructor A in class A cannot be
applied to given types; required:
int found: no arguments reason:
actual and formal argument lists
differ in length
The compiler automatically inserts super() in the beginning.
However, even constructors arguments, super() (without arguments) is added which invokes the default constructor of the superclass. And you don't have one, hence the error.
You have to specify super(x) (to invoke A(x)), or define a no-argument constructor.
By the way, Eclipse compiler gives a way better error message:
Implicit super constructor A() is undefined. Must explicitly invoke another constructor
It looks like the compiler tries to create a call to the superclasses default constructor with super(), which isn't avaliable:
required: int
found: no arguments
But back to your book: I've never heard of a rule that you can skip the super statement in a constructor if the actual constructor has the exact same parameter list as a constructor in the direct superclass. Only a call to the superclass's default constructor is added implicitly (super()) but that requires that the superclass has a default constructor.
In contrast to what's written in your book (or in contrast to your understanding of the written text), here's a sentence from the language spec:
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 is implicitly assumed by the compiler to begin with a super
class constructor invocation “super();”, an invocation of the constructor of its
direct superclass that takes no arguments.
If you have a the base class having a default constructor (no-arg constructor), when you extend B, you don't need to explicitly call super() because it is called any way.
But when you have a constructor with arguments, when making the contructor with parameters in B, you need to pass in super() a parameter for A
example :
class A {
public A(int x) { }
}
class B extends A {
public B(int x )
{
super(x); // need to specify the parameter for class A
//...
}
}
This happens when you dont have a default constructor and you are creating an instance with default one. Because If you have any Parameterized constructor then compiler will not insert the default one for you, instead you have to define.
It is neccessary to call constructor of super class in case of Java. Therefore, whenever you generate constructor of sub class, super class' constructor is self created by IDE.
It is because whenever base class constructor demands arguments, compiler thinks they are to be filled by base class constructor. In case of default constructor, it is OK. No need to call super() in sub class.

Categories

Resources