Advertisement
class A
{
A() //no argument constructor.
{
System.out.println("Constructor called");
}
public void message()
{
System.out.println("A");
}
}
class B
{
public static void main(String... ar)
{
A ob= new A(); // calling no argument constructor, with no arguments.
ob.message();
}
}
Constructor called
A
class A
{
private A()
{
System.out.println("Constructor of A is called");
}
}
class B
{
public static void main(String... ar)
{
A ob= new A(); //private constructor of A class is called outside its class, hence compile error.
}
}
A.java:13: error: A() has private access in A
A ob= new A();
^
1 error
Advertisement
//Class A has no constructor, hence, compiler adds an invisible default no-arg constructor to it.
class A
{
public void message()
{
System.out.println("A");
}
}
class B
{
public static void main(String... ar)
{
A ob= new A(); //comment1
ob.message();
}
}
A
In the code above, class A wasn't provided with any constructor, hence it is given an invisible default no-argument constructor by the compiler.
At comment1, this no-argument constructor is called to create an object of class A.
class Names
{
String firstName;
String secondName;
Names(String firstN, String secondN)
{
firstName=firstN;
secondName=secondN;
}
public void printName()
{
System.out.println(firstName + " " + secondName);
}
}
class D
{
public static void main(String... ar)
{
Names ob= new Names("Charlie","Chaplin"); //Calling a constructor with two String values to create an object.
ob.printName();
}
}
Charlie Chaplin
class MathOP
{
MathOP(int a, int b) //Constructor to add two integers
{
System.out.println(a+b);
}
MathOP(String a, String b) //Constructor to add two integers
{
System.out.println(a+b);
}
MathOP(float a, float b) //Constructor to add two integers
{
System.out.println(a+b);
}
MathOP(char a, char b) //Constructor to add two integers
{
System.out.println(a+b);
}
}
class Cons
{
public static void main(String... ar)
{
MathOP ob1= new MathOP(1,2);
MathOP ob2= new MathOP("John","Denver");
MathOP ob3= new MathOP(2.5f, 2.5f);
MathOP ob4= new MathOP('a', 'b');
}
}
3
JohnDenver
5.0
195
Advertisement
Advertisement
Please check our latest addition
C#, PYTHON and DJANGO
Advertisement