ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 7일 차 JAVA getter만드는 법
    삼성SDS_멀티캠퍼스/Java 2015. 9. 15. 15:31
    반응형

    getter/setter를 사용하면


    1.객체지향원리에 충실

    2.세분화된 접근제어가 가능

    3.입력값에 대한 검증(올바른 값만 들어갈 수 있게)

      

    3.1  -예를들어 speed에는 -값이 존재하지 않는다

    그렇기에 if(speed > 0) this.speed = speed; 로 하면

    양수일때만 스피드가 들어가게 할 수 있다.



    가급적이면 getter/setter를 쓰자.





    --------------------------------------------------------------------------------------------






    class Car5 {


    private int speed;

    private int mileage;

    private String color;


    public void speedUp() {

    speed += 10;

    }


    public void speedDown() {

    speed -= 10;

    }


    public String toString() {

    return "속도 : " + speed + ", 주행거리 : " + mileage + ", 색상 : " + color;

    }


    public void setSpeed(int speed) {

    this.speed = speed; // 자기 자신 객체의 주소

    System.out.println("정수버전 스피드 :" + speed);

    }


    public void setSpeed(double speed) {

    this.speed = (int) speed; // 자기 자신 객체의 주소

    System.out.println("실수버전 스피드 :" + speed);

    }

    public void setMileage(int mileage) {

    this.mileage = (int) mileage; // 자기 자신 객체의 주소

    System.out.println("정수버전 마일리지 :" + mileage);

    }

    public void setMileage(double mileage) {

    this.mileage = (int) mileage; // 자기 자신 객체의 주소

    System.out.println("실수버전 마일리지 :" + mileage);

    }

    public void setColor(String color){

    this.color = color;

    System.out.println(color);

    }

    public int getSpeed()

    {

    return speed;

    }

    public int getMileage()

    {

    return mileage;

    }

    public String getColor()

    {

    return color;

    }

    }


    public class Test13 {


    public static void main(String[] args) {


    Car5 myCar = new Car5();

    Car5 yourCar = new Car5();


    myCar.setSpeed(60);

    myCar.setMileage(10);

    myCar.setColor("blue");


    yourCar.setSpeed(150.6);

    yourCar.setMileage(30.3);

    yourCar.setColor("white");


    myCar.speedUp();

    yourCar.speedDown();


    System.out.print("\n\n");

    System.out.println(myCar.getSpeed());

    System.out.println(myCar.getMileage());

    System.out.println(myCar.getColor());

    System.out.println();

    System.out.println(yourCar.getSpeed());

    System.out.println(yourCar.getMileage());

    System.out.println(yourCar.getColor());

    System.out.println(myCar);

    System.out.println(yourCar);

    }


    }







    출처: 삼성SDS멀티캠퍼스 

    강사: 홍승길

    Email : iccack70@gmail.com



    반응형
Designed by Tistory.