#멋쟁이사자처럼 #부트캠프 #백엔드 #JAVA
public class TV {
private boolean power = false;
private int channel;
private int volume;
public TV(boolean power, int channel, int volume) {
this.power = power;
this.channel = channel;
this.volume = volume;
}
public TV(boolean power, int channel) {
this(power, channel, 0);
}
public TV(boolean power) {
this(power, 0, 0);
}
}
/*
Console:
public Person(String name, int age, String phoneNumber) {}
public Person(String name, int age) {}
public Person(String name) {}
*/
public class Person {
private String name;
private int age;
private String phoneNumber;
public Person(String name, int age, String phoneNumber) {
System.out.println("public Person(String name, int age, String phoneNumber) {}");
this.name = name;
this.age = age;
this.phoneNumber = phoneNumber;
}
public Person(String name, int age) {
this(name, age, "");
System.out.println("public Person(String name, int age) {}");
}
public Person(String name) {
this(name, 0);
System.out.println("public Person(String name) {}");
}
public static void main(String[] args) {
Person park = new Person("Park");
}
}
Parent and Childclass Parent {
int i = 5;
public int getI() {
return i;
}
}
class Child extends Parent {
int i = 10;
}
public class Main {
public static void main(String[] args) {
Child child = new Child();
System.out.println(child.getI()); // 5
}
}
class Parent {
int i = 5;
public int getI() {
return i;
}
}
class Child extends Parent {
int i = 10;
public void cry() {
System.out.println("I want this!");
}
}
public class Main {
public static void main(String[] args) {
Child child = new Child();
child.heyHey();
}
}
// ...
public class Main {
public static void main(String[] args) {
Parent child = new Child();
// ❌ Cannot resolve method 'heyHey' in 'Child'
child.heyHey();
}
}
Casting 'p' to 'Child' will produce ClassCastException for any non-null value.
It doesn't cause a compile time error because p can also contain a Child type instance.
class Parent {
int i = 5;
public int getI() {
return i;
}
}
class Child extends Parent {
int i = 10;
public void cry() {
System.out.println("I want this!");
}
}
public class Main {
public static void main(String[] args) {
Parent p = null;
Child c = null;
c = (Child) p;
}
}
// ...
public class Main {
public static void main(String[] args) {
Parent p = null;
Child c = null;
// ❌ Exception in thread "main" java.lang.ClassCastException:
// class org.example.Parent cannot be cast to class org.example
// Child (org.example.Parent and org.example.Child are in
// unnamed module of loader 'app')
p = new Parent();
c = (Child) p;
}
}
Meanwhile... the following example works fine: