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 해 주는 클래스 메소드가 따로 있다.


'Programing > JAVA' 카테고리의 다른 글

This Keyword  (0) 2015.02.10
접근 한정자 (member access)  (0) 2015.02.10
인스턴스 복사  (0) 2015.02.10
배열과 객체생성 잊지 말아야 할 점!  (0) 2015.02.10
Setter와 Getter  (0) 2015.02.10
Posted by kimmayer

블로그 이미지
IT 기술들 정리, 독후감을 주로 남깁니다!
kimmayer

공지사항

Yesterday
Today
Total

달력

 « |  » 2024.4
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30

최근에 올라온 글

최근에 달린 댓글

최근에 받은 트랙백

글 보관함