Constructor java tutorial: Java constructors are the methods which are used to initialize objects. Constructor method has the same name as that of class, they are called or invoked when an object of class is created and can't be called explicitly. Attributes of an object may be available when creating objects if no attribute is available then default constructor is called, also some of the attributes may be known initially. It is optional to write constructor method in a class but due to their utility they are used.
Java constructor example
Output of program:
This code is the simplest example of constructor, we create class Programming and create an object, constructor is called when object is created. As you can see in output "Constructor method called." is printed.
This code is the simplest example of constructor, we create class Programming and create an object, constructor is called when object is created. As you can see in output "Constructor method called." is printed.
Java constructor overloading
Like other methods in java constructor can be overloaded i.e. we can create as many constructors in our class as desired. Number of constructors depends on the information about attributes of an object we have while creating objects. See constructor overloading example:
Output of program:
When cpp object is created default constructor is called and when java object is created constructor with argument is called, setName method is used to set 'name' attribute of language, getName method prints language name.
Java constructor chaining
Constructor chaining occurs when a class inherits another class i.e. in inheritance, as in inheritance sub class inherits the properties of super class. Both the super and sub class may have constructor methods, when an object of sub class is created it's constructor is invoked it initializes sub class attributes, now super class constructor needs to be invoked, to achieve this java provides a
super
keyword through which we can pass arguments to super class constructor. For more understanding see constructor chaining example:Output of program:
Constructor method doesn't specify a return type, they return instance of class itself.
No comments:
Post a Comment