Class Constructors and Objects
🧩 Syntax:
class Player {
int id;
String name;
String email;
static int topPlayerId;
static String topPlayerName;
Player(int id){ // constructor1
this.id = id;
}
Player(int id, String email){ //contructor2
this.id = id;
this.email = email;
}
Player(int id, String name, String email){ //contructor3
this.id = id;
this.name = name;
this.email = email;
}
void setTopPlayerName(String name){
topPlayerName = name;
}
// Que - is it nececessary to access a static variable with static method only ?
// static void setTopPlayerName(String name){
// topPlayerName = name; // this name will have value of its closed scope variable
// }
void getTopPlayerName(){
System.out.println("Top Player Name : " + topPlayerName);
}
}
public class Question{
public static void main(String args[]){
// creating obj of 'Player', with initialization
Player p1 = new Player(1,"Yashasvi","yashasvi@some.com");
p1.setTopPlayerName("King");
p1.getTopPlayerName();
System.out.println("id : " + p1.id);
System.out.println("name : " + p1.name);
System.out.println("email : " + p1.email);
}
}
/*
Output :
Top Player Name : King
id : 1
name : Yashasvi
email : yashasvi@some.com
*/