Constructor in Java
May 2, 2017
Categorised in: Java Core
Let’s Jump to Code
Vehicle.java file in folder path: K:\Constructor
import model.Bike;
import java.util.List;
import java.util.ArrayList;
public class Vehicle {
public static void main( String[] args ){
List<Bike> bikes = new ArrayList<>();
// Bike bike1 = new Bike("Honda", 0x2E0456, 1);
// bikes.add(bike1);
// Bike bike2 = new Bike("Yamaha", 0x2E0854, 1);
// bikes.add(bike2);
// Bike bike3 = new Bike("Suzuki", 0x000000, 1);
// bikes.add(bike3);
//Below is fine tuned code but same as above:
bikes.add(new Bike("Honda", 0x2E0456, 1));
bikes.add(new Bike("Yamaha", 0x2E0854, 1));
bikes.add(new Bike("Suzuki", 0x2E0555, 1));
//BELOW CODE GIVES ERROR AS DATA IS PRIVATE
// for(Bike b: bikes) {
// System.out.println(b.name +" " + b.color + " " + b.gearOrNot);
// }
for(Bike b: bikes) {
System.out.println(b.getName() +" " + b.getColor() + " " + b.getGearOrNot());
}
}
}
Bike.java file in folder path: K:\Constructor\model
package model;
public class Bike {
private String name = "Honda";
private long color = 0x2E0456;
private int gearOrNot = 1;
public Bike() {} //does nothing but must be defined and public
public Bike(String name, long color, int gearOrNot) {
this.name = name;
this.color = color;
this.gearOrNot = gearOrNot;
}
public String getName() { return name; }
public long getColor() { return color; }
public int getGearOrNot() { return gearOrNot; }
}
Output
- Honda 3015766 1
- Yamaha 3016788 1
- Suzuki 3016021 1
Notes
- If you want to define your own constructor with arguments then you must explicitly declare the empty constructor.
- Getters are used to get the value of private data.
- Constructor must be public by default.
- this keyword helps differentiate from the passed argument and instance variable.
Pratik Kataria is currently learning Springboot and Hibernate.
Technologies known and worked on: C/C++, Java, Python, JavaScript, HTML, CSS, WordPress, Angular, Ionic, MongoDB, SQL and Android.
Softwares known and worked on: Adobe Photoshop, Adobe Illustrator and Adobe After Effects.