9 Java Constructor
9 Java Constructor
package javaprogram;
//Constructor
class Games
{
// In constructor We can use access modifiers
of public,private and protected
// same as method if we didn't use
public,private and protected it consider as default
// We can't use default keyword for default
constructor
public Games()
{
String gamename="cricket";
System.out.println("default constructor"+"
"+gamename);
}
// parameterized constructor with single
parameter
public Games(String gamename)
{
System.out.println("non-parameterized
constructor"+" "+gamename);
}
// parameterized constructor with double
parameter
public Games(String gamename,int
startingYearofgame)
{
System.out.println("non-parameterized
constructor"+" "+gamename+" "+startingYearofgame);
}
}
public class TopicConstructor{
public static void main(String[] args) {
// we don't have call specific constructor
// creating an object It calls constructor
based on parameters(arguments)
Games cricketgame=new Games(); // calling
default constructor
Games cricketgameobj=new
Games("vollyball");// calling parameterized
constructor with single parameter
Games cricketgameobj2=new
Games("football",1888);// calling parameterized
constructor with double parameter
}
}
A copy constructor is a constructor that creates a new
object by copying values from another object of the same
class.
package javaprogram;
//Constructor
class additions
{
int a; // instance variable a
int b; // instance variable b