Programing

게터와 세터는 어떻게 작동합니까?

crosscheck 2020. 8. 12. 07:41
반응형

게터와 세터는 어떻게 작동합니까?


저는 PHP 세계에서 왔습니다. 게터와 세터가 무엇인지 설명하고 몇 가지 예를 들어 줄 수 있습니까?


이를 위해 튜토리얼은 실제로 필요하지 않습니다. 캡슐화 에 대한 읽기

private String myField; //"private" means access to this is restricted

public String getMyField()
{
     //include validation, logic, logging or whatever you like here
    return this.myField;
}
public void setMyField(String value)
{
     //include more logic
     this.myField = value;
}

Java에서 getter 및 setter는 완전히 일반적인 기능입니다. 그들을 getter 또는 setter로 만드는 유일한 것은 관습입니다. foo에 대한 getter는 getFoo라고하고 setter는 setFoo라고합니다. 부울의 경우 getter를 isFoo라고합니다. 또한 'name'에 대한 getter 및 setter의이 예제에 표시된대로 특정 선언이 있어야합니다.

class Dummy
{
    private String name;

    public Dummy() {}

    public Dummy(String name) {
        this.name = name;
    }

    public String getName() {
        return this.name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

멤버를 공개하는 대신 getter 및 setter를 사용하는 이유는 인터페이스를 변경하지 않고도 구현을 변경할 수 있기 때문입니다. 또한 리플렉션을 사용하여 개체를 검사하는 많은 도구 및 도구 키트는 getter 및 setter가있는 개체 만 허용합니다. 예를 들어 JavaBeans 에는 getter 및 setter 및 기타 요구 사항이 있어야합니다.


class Clock {  
        String time;  

        void setTime (String t) {  
           time = t;  
        }  

        String getTime() {  
           return time;  
        }  
}  


class ClockTestDrive {  
   public static void main (String [] args) {  
   Clock c = new Clock;  

   c.setTime("12345")  
   String tod = c.getTime();  
   System.out.println(time: " + tod);  
 }
}  

프로그램을 실행하면 프로그램이 전원에서 시작됩니다.

  1. 객체 c가 생성됩니다.
  2. 함수 setTime()는 객체 c에 의해 호출됩니다.
  3. 변수 time는 전달 된 값으로 설정됩니다.
  4. 함수 getTime()는 객체 c에 의해 호출됩니다.
  5. 시간이 돌아왔다
  6. 그것은에 패스포트됩니다 todtod인쇄 얻을

" Why getter and setter methods are evil " 을 읽을 수도 있습니다 .

Though getter/setter methods are commonplace in Java, they are not particularly object oriented (OO). In fact, they can damage your code's maintainability. Moreover, the presence of numerous getter and setter methods is a red flag that the program isn't necessarily well designed from an OO perspective.

This article explains why you shouldn't use getters and setters (and when you can use them) and suggests a design methodology that will help you break out of the getter/setter mentality.


1. The best getters / setters are smart.

Here's a javascript example from mozilla:

var o = { a:0 } // `o` is now a basic object

Object.defineProperty(o, "b", { 
    get: function () { 
        return this.a + 1; 
    } 
});

console.log(o.b) // Runs the getter, which yields a + 1 (which is 1)

I've used these A LOT because they are awesome. I would use it when getting fancy with my coding + animation. For example, make a setter that deals with an Number which displays that number on your webpage. When the setter is used it animates the old number to the new number using a tweener. If the initial number is 0 and you set it to 10 then you would see the numbers flip quickly from 0 to 10 over, let's say, half a second. Users love this stuff and it's fun to create.

2. Getters / setters in php

Example from sof

<?php
class MyClass {
  private $firstField;
  private $secondField;

  public function __get($property) {
    if (property_exists($this, $property)) {
      return $this->$property;
    }
  }

  public function __set($property, $value) {
    if (property_exists($this, $property)) {
      $this->$property = $value;
    }

    return $this;
  }
}
?>

citings:


Here is an example to explain the most simple way of using getter and setter in java. One can do this in a more straightforward way but getter and setter have something special that is when using private member of parent class in child class in inheritance. You can make it possible through using getter and setter.

package stackoverflow;

    public class StackoverFlow 

    {

        private int x;

        public int getX()
        {
            return x;
        }

        public int setX(int x)
        {
          return  this.x = x;
        }
         public void showX()
         {
             System.out.println("value of x  "+x);
         }


        public static void main(String[] args) {

            StackoverFlow sto = new StackoverFlow();
            sto.setX(10);
            sto.getX();
            sto.showX();
        }

    }

참고URL : https://stackoverflow.com/questions/2036970/how-do-getters-and-setters-work

반응형