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
}
}
public class MyClass {//this is an example of a class with a non default constructor
private int number = 0;
public MyClass() {
}
public MyClass(int theNumber) {//this is the constructor
//acces modifiers+constructor name(it needs to be the same as the class name)+parameters
this.number = theNumber;
}
}
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);
}
}
class Main {
private String name;
// constructor
Main() {
System.out.println("Constructor Called:");
name = "Programiz";
}
public static void main(String[] args) {
// constructor is invoked while
// creating an object of the Main class
Main obj = new Main();
System.out.println("The name is " + obj.name);
}
}
// Java Program to Illustrate Working of
// Parameterized Constructor
// Importing required inputoutput class
import java.io.*;
// Class 1
class Geek {
// data members of the class.
String name;
int id;
// Constructor would initialize data members
// With the values of passed arguments while
// Object of that class created
Geek(String name, int id)
{
this.name = name;
this.id = id;
}
}
// Class 2
class GFG {
// main driver method
public static void main(String[] args)
{
// This would invoke the parameterized constructor.
Geek geek1 = new Geek("adam", 1);
System.out.println("GeekName :" + geek1.name
+ " and GeekId :" + geek1.id);
}
}