class Fruit {
int apple;
int straw;
int grapes;
int sum;
Fruit(int apple, int straw, int grapes){
this.apple = apple;
this.straw = straw;
this.grapes = grapes;
}
public int Count(){
sum = apple + straw + grapes;
return sum;
}
}
public class MethodDemo1 {
public static void main(String args[]){
int total;
Fruit f1 = new Fruit(30, 30, 40);
total = f1.Count();
System.out.println("객체 f1의 총 갯수 = " + total);
System.out.println("객체 f1의 apple 개수 = "+ f1.apple);
System.out.println("객체 f1의 straw 개수 = "+ f1.straw);
System.out.println("객체 f1의 graphs 개수 = "+ f1.grapes);
}
}
여기까지 예제는 따로 클래스화 시키지 않은 내용들인데
사실 객체지향을 위해서라면 아래 코딩된 예시가 더욱 올바른 것이라고 한다.
class Fruit{
private int a;
private int b;
private int c;
private int sum;
Fruit (int apple, int straw, int grapes){
a = apple;
b = straw;
c = grapes;
this.count();
}
private void count(){
sum = a + b + c;
}
public int gettotal(){
return sum;
}
public int getapple(){
return a;
}
public int getstraw(){
return b;
}
public int getgrapes(){
return c;
}
}
public class MethodDemo2 {
public static void main(String args[]){
int total;
Fruit f1 = new Fruit(30,30,40);
total = f1.gettotal();
System.out.println("객체 f1의 총 개수 =" + total);
System.out.println("객체 f1의 apple 개수 = "+ f1.getapple());
System.out.println("객체 f1의 straw 개수 = "+ f1.getstraw());
System.out.println("객체 f1의 graphs 개수 = "+ f1.getgrapes());
}
}
각각의 값을 return 해 주는 클래스 메소드가 따로 있다.