In Java Let’s say we’re designing a Student class that has two
data fields. One data field, called id, is for storing each
student’s ID number. Another data field, called numStudents, keeps
track of how many Student objects have been created. For each of
the blanks, indicate the appropriate choice.
id should be public/private and
static/not static .
numStudents should be public/private
and static/not static .
The next three questions use the following class:
class Counter {
private int count;
public Counter() {
this(0);
}
public Counter(int startingCount) {
count =
startingCount;
}
public void increment() {
count++;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count =
count;
}
}
Here is one program using the above class:
public class Main {
public static void main(String[] args) {
Counter c1 = new Counter();
Counter c2 = new Counter(5);
swap(c1.getCount(),
c2.getCount());
System.out.print(c1.getCount() + "
" +
c2.getCount());
}
public static void swap(int c1, int c2) {
int temp = c1;
c1 = c2;
c2 = temp;
}
}
If you run the program, you’ll see that the output is:
0 5
Explain using words and/or pictures why that is the output.
Here is a second program using the above class:
public class Main {
public static void main(String[] args) {
Counter c1 = new Counter();
Counter c2 = new Counter(5);
swap(c1, c2);
System.out.print(c1.getCount() + "
" +
c2.getCount());
}
public static void swap(Counter c1, Counter c2)
{
Counter temp = c1;
c1 = c2;
c2 = temp;
}
}
If you run the program, you’ll see that the output is:
0 5
Explain using words and/or pictures why that is the output.
Here is a third program using the above class:
public class Main {
public static void main(String[] args) {
Counter c1 = new Counter();
Counter c2 = new Counter(5);
swap(c1, c2);
System.out.print(c1.getCount() + "
" +
c2.getCount());
}
public static void swap(Counter c1, Counter c2)
{
int temp =
c1.getCount();
c1.setCount(c2.getCount());
c2.setCount(temp);
}
}
If you run the program, you’ll see that the output is:
5 0
Explain using words and/or pictures why that is the output.
Answer 1:
id should be private and non static:
numStudents should be public and static
Answer 2:
because c1 and c2 has 0 and 5 we are calling swap function
but here the we are passing parameters using call by value
so that swap occured in that function will not have impact at
main
Answer 3:
because c1 and c2 has 0 and 5 we are calling swap function
but here the we are passing parameters using call by value
so that swap occured in that function will not have impact at
main
Answer 4:here we are changing the values of c1 and c2 in swap
function so the chages will
have effect at main
Get Answers For Free
Most questions answered within 1 hours.