To gain more experience with Java, I decided to try to create my own program, using OOP, and this program as a template:
public class HelloObject {
private String hello; // instance attribute or variable
public HelloObject() { // constructor
hello = "Hello, World!";
}
public String getHello() { // getter, returns value from inside the object
return this.hello; // return String from object
}
public static void main(String[] args) {
HelloObject ho = new HelloObject(); // Instance of Class (ho) is an Object via "new HelloObject()"
System.out.println(ho.getHello()); // Object allows reference to public methods and data
}
}
// IJava activation
HelloObject.main(null);
I decided to make a program to sum all the numbers from 1 to 100 The original code is below:
int sum = 0;
for (int i=1; i<101; i++) {
sum = sum+i;
}
System.out.println(sum)
And revised code is below:
public class SumObject {
private int sum;
public SumObject() {
sum = 0;
}
public int getSum() {
return sum;
}
public void setSum(int s) {
sum = s;
}
public static void main(String[] args) {
SumObject summer = new SumObject();
for (int i=1; i<101; i++) {
int s = summer.getSum();
summer.setSum(i+s);
}
System.out.println(summer.getSum());
}
}
SumObject.main(null);