logo

Java의 같음 메서드 재정의

객체를 받아들이고 현재 객체와 비교하는 객체 클래스의 equals() 메서드는 두 객체를 비교하는 데 사용됩니다. 이 두 개체에 대한 참조가 동일하면 메서드는 true를 반환합니다. 그렇지 않으면 그렇지 않습니다.

다음 예제 전체의 Employee 클래스에는 이름과 나이라는 두 개의 변수와 매개변수화된 함수 Object() { [네이티브 코드] }가 있습니다.

equals() 메소드를 사용하여 동일한 데이터를 제공하고 결과를 비교하여 기본 메소드에서 두 개의 객체를 만듭니다.

VLC 유튜브 비디오 다운로드

Object 클래스의 equals() 메서드는 객체에 대한 참조가 동일한 경우에만 true를 반환하기 때문에 이 소프트웨어는 false를 반환합니다.

equals 메소드를 재정의하는 예제 코드:

EqualsExpl.java

 import java.util.Scanner; class Student { private String n; private int a; Student(String n, int a){ this.n = n; this.a = a; } } public class EqualsExpl { public static void main(String[] args) { Student s1 = new Student('Sonoo', 19); Student s2 = new Student('Jaiswal', 19); // Comparing the two instances boolean bool = s1.equals(s2); System.out.println(bool); } } 

산출:

Java의 같음 메서드 재정의

equals() 메서드 재정의

객체는 실제로 Java의 모든 클래스에 대한 슈퍼클래스이므로 자신만의 equals 메소드 버전을 개발할 수 있습니다.

스택 자바

예제 코드:

EqualsExpl1.java

 class Student { private String n; private int a; Student(String n, int a){ this.n = n; this.a = a; } public boolean equals(Object o) { if (o == this) { return true; } if (!(o instanceof Student)) { return false; } Student s = (Student) o; return n.equals(s.n)&& Integer.compare(a, s.a) == 0; } } public class EqualsExpl1 { public static void main(String[] args) { Student s1 = new Student('Sonoo', 19); Student s2 = new Student('Jaiswal', 19); //Comparing the two instances boolean bool = s1.equals(s2); System.out.println(bool); } } 

산출:

Java의 같음 메서드 재정의