데이터 과학

this와 toString() 메소드 본문

AP/AP Computer Science A

this와 toString() 메소드

티에스윤 2024. 5. 29. 11:54

우선 JAVA언어에서 this의 사용법은 여러 가지가 있습니다. 

 

간단하게 변수이름을 구분지을때 사용하는 것이 일반적인데 이외에도 여러 가지 사용법이 있습니다. 

 

public class Person {     

   private String name;     

       public void setName(String name) {         

           this.name = name; // this 키워드를 사용하여 멤버 변수를 참조     

    }

 }

 

https://tsyoon.tistory.com/162

 

this 키워드

자바에서 this 키워드는 현재 객체를 가리키는 참조입니다. 이 키워드를 사용하여 클래스 내부에서 현재 객체의 멤버 변수와 메서드에 접근할 수 있습니다. this 키워드는 다음과 같은 상황에서

tsyoon.tistory.com

 

아래 예제는 this와 함께 toString을 복합적으로 사용한 예제입니다. 

this를 출력물로 사용할 때의 역할은 toSting 메소드를 호출하는 것입니다. 

 

public class Person {
   private String name;
   private int age;
 

  public Person(String aName, int anAge) {
     name = aName;
     age = anAge;
}


/** @return the String form of this person */
  public String toString()
   { return name + " " + age; }
  public void printPerson()
   { System.out.println(this); }
   //Other variables and methods are not shown.

public static void main(String[] args) {
   
    Person p = new Person("Dan", 10);
     p.printPerson();
//System.out.println(p);
 }
}

 

 

결과: Dan 10

 

 

프로그램을 수정하여서 아래와 같이 코딩을 해 보면 결과가 같습니다. 

 

public class Person {private String name;private int age;
 public Person(String aName, int anAge) {name = aName; age = anAge;}
 
/** @return the String form of this person */
public String toString()
{ return name + " " + age; }
public void printPerson()
{ System.out.println(this); }
//Other variables and methods are not shown.

public static void main(String[] args) {
    Person p = new Person("Dan", 10);
    //p.printPerson();
    System.out.println(p);
    }}

 

 

결과: Dan 10

 

 

https://www.onlinegdb.com/online_java_compiler#

 

'AP > AP Computer Science A' 카테고리의 다른 글

상속에서 생성자와 super 연산  (0) 2024.06.04
상속 예제  (0) 2024.05.31
static 변수  (0) 2024.05.29
ArrayList 예제  (0) 2024.01.12
생성자 선언 관련 문제  (1) 2024.01.11