In: Computer Science
Please explain clearly which line means what and how can I get the answer. (correct answer 2 2) public class Checker { public static int count = 0; public int number = 0; public Checker(){ count++; number = count; } public int getCount() { return count; } public int getNumber() { return number; } }
What is output from the code fragment below?
Checker one = new Checker(); Checker two = new Checker(); System.out.println(one.getCount() + " " + two.getCount());
code:
class Checker
{
public static int count = 0; //static variable (common to all
instatnces(or objects) of class)
public int number = 0;
public Checker(){ //constructor (executed every time object is
ceated)
count++; //count increament (here value of count will increase by 1
everytime the object is craeted)
number = count; //sets number variable equal to count
}
public int getCount() { return count; } //returns the value of
static variable count
public int getNumber() { return number; } //returns value of
variable number
}
public class Main{
public static void main(String a[])
{
Checker one = new Checker(); //constructor executed(setting count=1
and number=count i.e. number=1)
Checker two = new Checker(); //again constructor executed (setting
count=2 now and likewise number=count=2)
System.out.println(one.getCount() + " " + two.getCount());
//getCount here will now return value 2 since count variable is
static (i.e. it is common to both objects created here)
//if getNumber used, one.getNumber=1 and two.getNumber=2 because
separate copy if each variable is maintained for number
variable
}
}