
public class Point {
public int x ;
public int y ;
//constructor
public Point(int x, int y) {
x = x;
y = y;
}
void display(){
System.out.println(x+" :: "+y);
}
public static void main(String args[]){
Point s1 = new Point (111,222);
Point s2 = new Point (333,444);
s1.display();
s2.display();
}
}
public class Point {
public int x = 0;
public int y = 0;
//constructor
public Point(int x, int y) {
this.x = x;
this.y = y;
}
void display(){
System.out.println(x+" :: "+y);
}
public static void main(String args[]){
Point s1 = new Point (111,222);
Point s2 = new Point (333,444);
s1.display();
s2.display();
}
}
public class Rectangle {
private int x, y;
private int width, height;
public Rectangle() {
this(0, 0, 0, 0);
}
public Rectangle(int width, int height) {
this(0, 0, width, height);
}
public Rectangle(int x, int y, int width, int height) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}
...
}
This class contains a set of constructors. Each constructor initializes some or all of the rectangle's member variables. The constructors provide a default value for any member variable whose initial value is not provided by an argument. For example, the no-argument constructor calls the four-argument constructor with four 0 values and the two-argument constructor calls the four-argument constructor with two 0 values. As before, the compiler determines which constructor to call, based on the number and the type of arguments.class Employee{
int id;
String name;
String city;
Employee(int id,String name){
this.id = id;
this.name = name;
}
Employee(int id,String name,String city){
this(id,name);//now no need to initialize id and name
this.city=city;
}
void display(){
System.out.println(id+" "+name+" "+city);
}
public static void main(String args[]){
Employee e1 = new Employee(222,"Dinesh");
Employee e2 = new Employee(555,"Anamika","Noida");
e1.display();
e2.display();
}
}
class Employee{
int id;
String name;
Employee(){
System.out.println("default constructor is invoked");
}
Employee(int id,String name){
id = id;
name = name;
this ();//must be the first statement
}
void display(){
System.out.println(id+" "+name);
}
public static void main(String args[]){
Employee e1 = new Employee(222,"Dinesh");
Employee e2 = new Employee(555,"Anamika");
e1.display();
e2.display();
}
}
Labels: Core JAVA