#멋쟁이사자처럼 #부트캠프 #백엔드 #JAVA
Pen and BallPenpublic class Main {
public static void method1(Pen pen) {
// ...
}
public static void method2(BallPen ballPen) {
// ...
}
public static void method3(Object obj) {
if (obj instanceof Pen) {
((Pen) obj).write();
} else {
System.out.println("Only pen has write method!");
}
}
public static void main(String[] args) {
Pen pen = new Pen();
BallPen ballPen = new BallPen();
String str = "hello";
Object obj = new Object();
method1(ballPen);
method2(ballPen);
method2(pen);
method3(ballPen);
method3(str);
method3(obj);
}
}
equalsimport java.util.Objects;
class MyClass {
private String name;
private int age;
public MyClass(String name, int age) {
this.name = name;
this.age = age;
}
// @Override
// public boolean equals(Object o) {
// if (!(o instanceof MyClass myClass)) return false;
// return age == myClass.age && Objects.equals(name, myClass.name);
// }
@Override
public boolean equals(Object o) {
if (o == null || getClass() != o.getClass()) return false;
MyClass myClass = (MyClass) o;
return age == myClass.age && Objects.equals(name, myClass.name);
}
}
public class Main {
public static void main(String[] args) {
MyClass instance1 = new MyClass("Steve", 1);
MyClass instance2 = new MyClass("Steve", 1);
System.out.println(instance1.equals(instance2));
}
}
instanceof and getClass()instanceof |
getClass() |
|
|---|---|---|
| Allows instances of subclasses to equal instances of the superclass | yes | no |
| Allows instances of different subclasses to equal each other | yes | no |
Overriding the generated equals() method does not break its contract |
no | yes |
| Avoids extra null check | yes | no |
| Obeys the Liskov substitution principle | yes | no |
String str1 = "hello";
String str2 = "hello";
System.out.println(str1 == str2); // true
System.out.println(str1.equals(str2)); // true
The == operator compares references (memory locations) when used with objects. However, with string literals in Java, there's an optimization called String Interning. When you create string literals (e.g., "hello"), they are stored in a special memory area called the String Pool. If a string with the same content already exists in the pool, Java reuses the existing reference rather than creating a new one.
Stringstr, str2, and str3 all point to the same location.
But when you change the value of str1 it shouldn't affect other variables.