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
}
}
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){
}
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);
}
}
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);
}
}