Create a class called Methods that has a single instance variable private int x
ID: 3602024 • Letter: C
Question
Create a class called Methods that has a single instance variable private int x, then write the following six methods in the class:
A static method that takes no parameters, returns no value, and prints “Hello, world!”
An instance (non-static) method called print() that takes no parameters, returns no value, and prints the current value of the x instance variable like this: “x is: x”
A setter method for the x instance variable, whose parameter name is also x; remember the naming convention for setter methods and their return type!
The setter method must guarantee that x is never set to a value less than 0
If the setter argument is negative, it can either set x to 0 or leave x unchanged
A Methods constructor that takes one int parameter called x and calls the setter method to set the value of the x instance variable
A getter method for the x instance variable; remember the parameter and return types for getter methods!
A static void method called print(), whose single parameter is a Methods object, that prints the value of its parameter’s x instance variable – this is method overloading
This method can use either the object’s print() or its getter method to do this
Explanation / Answer
Methods.java
class Methods{
private int x;
public static void printHello(){
System.out.println("Hello,World");
}
Methods(int x){
setX(x);
}
public void print(){
System.out.println("x is:"+x);
}
public void setX(int x){
if(x<0)
x=0;
else
this.x=x;
}
public int getX(){
return x;
}
public static void print(Methods obj){
obj.print();
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.