Public constructor can be invoked by any other class.
Syntax of Public Constructor
class clsName
{
// Variable declaration
public clsName()
{
}
// Methods
}
clsName is a valid identifier in java. It is a class name.
Example of Public Constructor
Example 1 : Program that illustrates public constructor use in java
class Person
{
String name;
int age;
public Person(String name, int age)
{
this.name = name;
this.age = age;
}
}
class PublicConstructorDemo
{
public static void main(String args[])
{
Person pObj = new Person("Michel",24);
System.out.println(pObj.name);
System.out.println(pObj.age);
}
}
Output
Michel
24