instanceof java
Posts: 576
Nickname: instanceof
Registered: Jan, 2015
instanceof java is a java related one.
Constructors in java
Posted: Mar 8, 2015 8:19 AM
This post originated from an RSS feed registered with Java Buzz
by instanceof java.
Original Post: Constructors in java
Feed Title: Instance Of Java
Feed URL: http://feeds.feedburner.com/blogspot/TXghwE
Feed Description: Instance of Java. A place where you can learn java in simple way each and every topic covered with many points and sample programs.
Latest Java Buzz Posts
Latest Java Buzz Posts by instanceof java
Latest Posts From Instance Of Java
Advertisement
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 package instanceofjava; class A{ A(){ } } } while creating object constructor will be executed so we can assign instance variables to some default values. package instanceofjava; class A{ int a,b A(int x, int y){ a=x; b=y; } public static void main(String[] args){ A a=new A(10,20); } } 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. package instanceofjava; class Sample{ int a,b Sample(){ a=37; b=46; } public static void main(String[] args){ Sample obj=new Sample(); System.out.println(obj.a); System.out.println(obj.b); } } Output: Parameterized constructor package instanceofjava; class Sample{ int a,b Sample(int x, int y){ a=x; b=y; } public static void main(String[] args){ Sample obj=new Sample(37,46); System.out.println(obj.a); System.out.println(obj.b); } } Output: Constructor overloading: package instanceofjava; class Sample{ int a,b Sample(){ this(1,2); System.out.println("Default constructor"); } Sample(int x , int y){ this(1,2,3); a=x; b=y; System.out.println("Two argument constructor"); } Sample(int a , int b,int c){ System.out.println("Three argument constructor") } public static void main(String[] args){ Sample obj=new Sample(); System.out.println(obj.a); System.out.println(obj.b); } } Output: Three argument constructor Two argument constructor Default argument constructor 1 2
Read: Constructors in java