xxxxxxxxxx
public class Hello {
String name;
//Constructor
Hello(){
this.name = "BeginnersBook.com";
}
public static void main(String[] args) {
Hello obj = new Hello();
System.out.println(obj.name);
}
}
xxxxxxxxxx
class Other{
public Other(String message){
System.out.println(message);
}
}
class scratch{
public static void main(String[] args) {
Other method = new Other("Hey");
//prints Hey to the console
}
}
xxxxxxxxxx
A constructor is a special method used to initialize objects in java.
we use constructors to initialize all variables in the class
when an object is created. As and when an object
is created it is initialized automatically with the help of
constructor in java.
We have two types of constructors:
Default Constructor
Parameterized Constructor
public classname(){
}
public classname(parameters list){
}
xxxxxxxxxx
public class Car {
private String make;
private String model;
// Constructor
public Car(String make, String model) {
this.make = make;
this.model = model;
}
// Other methods and variables
public void startEngine() {
// Code to start the car's engine
}
public void drive() {
// Code to make the car drive
}
// Getters and setters for make and model
}
xxxxxxxxxx
class Main {
private String website;
// constructor
Main() {
website = "'softhunt.net'";
}
public static void main(String[] args) {
// constructor is invoked while
// creating an object of the Main class
Main obj = new Main();
System.out.println("Welcome to " + obj.website);
}
}