Java Programming Can you explain or add comments on what\'s happening in this co
ID: 3771540 • Letter: J
Question
Java Programming
Can you explain or add comments on what's happening in this code below step-by-step?
public class Test{
private int value = 0;
public Test(){
value = 5;
}
public Test(int newValue){
value = newValue;
}
public void setValue(int newValue){
value = newValue;
public int get Value( ){
return value;
}
public static int calculateSquare(int number){
return number * number;
}
}
public class TestTest{
public static void main (String [] args){
Test try1 = new Test();
Test try2 = new Test(42);
Test try3 = new Test(1);
try2.setvalue(Test.calculateSquare(2));
try3 = try2;
System.out.println("try1: " + try1.getValue());
System.out.println("try2: " + try2.getValue());
System.out.println("try3: " + try3.getValue());
}
}
Explanation / Answer
/*
*Below, we have created a Java class named "Test" . Having two Constructor..
*one constructor having no parameter and other one having 1 parameter
*Constructor are used two to initialize the instance's of the class.
*/
class Test{
private int value = 0;
public Test(){
this.value = 5;
}
public Test(int newValue){
this.value = newValue;
}
/*
*setValue is a function which is created to update the value of data element "value " of a Class instance.
*/
public void setValue(int newValue){
this.value = newValue;
}
/*
*getValue() fucntion returns the data element of the class instance..
*/
public int getValue(){
return this.value;
}
/*
*calculateSquare() takes a number as input the and returns the square of the number as output..
*/
public static int calculateSquare(int number){
return number * number;
}
}
public class TestTest{
public static void main (String [] args){
/*
*Below ,we are creating 3 objects or instances of the Class test
*first instance is initialized with empty constructor ,second instance is intialized with 1 parameter *constructor. and third with one 1 parameter.
*/
Test try1 = new Test();
Test try2 = new Test(42);
Test try3 = new Test(1);
try2.setValue(Test.calculateSquare(2)); //updating the value of instance 2 value using setter method
try3 = try2; // now try3 is now pointing to try2 instance..
System.out.println("try1: " + try1.getValue());
System.out.println("try2: " + try2.getValue());
System.out.println("try3: " + try3.getValue());
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.