I know that we can retrieve a variable's value by simply writing get methods and return var;. However, is there another way to write a get method to return information on the fields instead? If so, how does one access it. For example, if I have a planeNumber and I want to check it against another object's planeNumber, is there a way to use a boolean to check instead of writing public int getPlaneNumber()?
- Does this answer your question? Compare two objects, javaPranav Kasetti– Pranav Kasetti2021-09-13 16:57:22 +00:00Commented Sep 13, 2021 at 16:57
Add a comment |
2 Answers
Seems like you are wanting to implement the Comparable interface? https://docs.oracle.com/javase/8/docs/api/java/lang/Comparable.html
That is it looks like you have an attribute, planeNumber, that you want to use to compare the classes?
Maybe you want something like this
import java.util.Comparator; import java.util.Objects; public class Airplane implements Comparable<Airplane> { private final int planeNumber; public Airplane(final int planeNumber) { this.planeNumber = planeNumber; } public final int getPlaneNumber() { return planeNumber; } @Override public int compareTo(final Airplane o) { return Objects.compare(this, o, Comparator.comparing(Airplane::getPlaneNumber)); } public static void main(final String... args) { System.out.println(new Airplane(1).compareTo(new Airplane(2))); System.out.println(new Airplane(100).compareTo(new Airplane(100))); System.out.println(new Airplane(1000).compareTo(new Airplane(100))); } } -1 0 1 Comments
You could add a method comparing the field values to your class like this (omitting null check in the methods):
class Scratch { public static void main(String[] args) { ObjectWithPlaneNumber o1 = new ObjectWithPlaneNumber(42); ObjectWithPlaneNumber o2 = new ObjectWithPlaneNumber(42); ObjectWithPlaneNumber o3 = new ObjectWithPlaneNumber(11); System.out.println(o1.hasSamePlaneNumber(o2)); System.out.println(o1.hasSamePlaneNumber(o3)); } static class ObjectWithPlaneNumber { private final int planeNumber; public ObjectWithPlaneNumber(int planeNumber) { this.planeNumber = planeNumber; } public boolean hasSamePlaneNumber(ObjectWithPlaneNumber other) { return this.planeNumber == other.planeNumber; } } }