Constructor's in java
A constructor is similar to a method (but not actually a method ) that is invoked automatically when an object is instantiated.
class Test { Test(){
//constructor body
}
}
for Ex.
No-Arg(argument) Constructors
public class MyConstructor {MyConstructor() {System.out.println("Object is now created");}public static void main(String args[]) {MyConstructor obj = new MyConstructor();}}
Object is now created
if a java constructor does not accept any parameters, it is a no-arg constructor.
class Test{
int a;
Test(){
a=5; //initialize here
}
}
public class Vehicle {int wheels;Vehicle() {wheels = 4;}public static void main(String args[]) {Vehicle car = new Vehicle();System.out.println(car.wheels + " wheels");}}
4 wheels
If a Java constructor accepts some parameters, it is a parameterized constructor.
Ex.
class Test {
int a;
Test ( int b ) {
a = b; // initialize here
}
}
public class Vehicle {int wheels;Vehicle(int noOfWheels) {wheels = noOfWheels;}public static void main(String args[]) {Vehicle car = new Vehicle(6);Vehicle scuty = new Vehicle(2);System.out.println(car.wheels + " wheels");System.out.println(scuty.wheels + " wheels");}}
PS G:\oops> java Vehicle 6 wheels 2 wheels
Similar like method overloading, you can also overload constructors if two or more constructors are different in parameters.
class Test {
int a;
Test () {
a = 5; //initialize here
}
Test ( int b) {
a = b; //initialize here
}
}
public class Vehicle {int wheels;String color;Vehicle(int noOfWheels) {wheels = noOfWheels;}Vehicle(int wheels, String color) {this.wheels = wheels;this.color = color;}public static void main(String args[]) {// Vehicle car = new Vehicle(6);// Vehicle scuty = new Vehicle(2);Vehicle truck = new Vehicle(12, "red");// System.out.println(car.wheels + " wheels");// System.out.println(scuty.wheels + " wheels");System.out.println(truck.wheels + " wheels and color = " + truck.color);}}
12 wheels and color = red
Post a Comment