» » Constructors in java





  • Constructors will be executed when the object is created.
  • Constructors should have same name of class name.
  • Executed once per object.
  • Basically used to assign instance variables
  • We can overload constructors.
  • We can call super class constructor form sub class constructor.






  1. package instanceofjava;
  2. class A{
  3. A(){
  4. }
  5. }
  6. }

  • while creating object constructor will be executed so we can assign instance variables to some default values.

  1. package instanceofjava;
  2. class A{
  3. int a,b
  4. A(int x, int y){
  5. a=x;
  6. b=y;
  7. }
  8.  
  9. public static void main(String[] args){
  10.  A a=new A(10,20);

  11. }
  12. }

Types of constructors:

  • There are two types of constructors 
  • Default constructors
  • Parameterized constructor.

Default constructor:

  •  Default constructor will not have any arguments.
  • If we not defined any constructor in our class. JVM automatically defines a default constructor to our class.
  1. package instanceofjava;
  2. class Sample{
  3. int a,b
  4. Sample(){
  5. a=37;
  6. b=46;
  7. }
  8.  
  9. public static void main(String[] args){
  10.  
  11.  Sample obj=new Sample();
  12.   System.out.println(obj.a);
  13.   System.out.println(obj.b);
  14.  
  15. }
  16. }

Output:

  1. 37
  2. 46

Parameterized constructor


  1. package instanceofjava;
  2. class Sample{
  3. int a,b
  4. Sample(int x, int y){
  5. a=x;
  6. b=y;
  7. }
  8.  
  9. public static void main(String[] args){
  10.  
  11.  Sample obj=new Sample(37,46);
  12.   System.out.println(obj.a);
  13.   System.out.println(obj.b);
  14.  
  15. }
  16. }

Output:

  1. 37
  2. 46

Constructor overloading:

  1. package instanceofjava;
  2. class Sample{
  3. int a,b 
  4. Sample(){
  5. this(1,2);
  6.  System.out.println("Default constructor");
  7.  
  8. }
  9. Sample(int x , int y){
  10.  
  11. this(1,2,3); 
  12. a=x;
  13. b=y;
  14.  System.out.println("Two argument constructor");
  15.  
  16. }
  17.  
  18. Sample(int a , int b,int c){
  19.  System.out.println("Three argument constructor")
  20. }
  21. public static void main(String[] args){
  22.  
  23.  Sample obj=new Sample();
  24.   System.out.println(obj.a);
  25.   System.out.println(obj.b);
  26.  
  27. }
  28. }


Output:

  1. Three argument constructor
  2. Two argument constructor
  3. Default argument constructor
  4. 1
  5. 2





Instance Of Java

We will help you in learning.Please leave your comments and suggestions in comment section. if you any doubts please use search box provided right side. Search there for answers thank you.
«
Next
Newer Post
»
Previous
Older Post

No comments

Leave a Reply

Select Menu