instanceof
์ด๋ค ํด๋์ค๋ฅผ ์์๋ฐ์๋์ง ํ์ธ
class Person{
String name;
Person(String name){
this.name = name;
}
void printInfo() {
System.out.println(name);
}
}
class Student extends Person{
int snum;
Student(String name, int snum){
super(name);
this.snum = snum;
}
void printStudent() {
System.out.println("snum: "+snum);
}
}
class Researcher extends Person{
int rnum;
Researcher(String name, int rnum){
super(name);
this.rnum = rnum;
}
void printResearcher() {
System.out.println("rnum: "+rnum);
}
}
class Professor extends Researcher{
String depart;
Professor(String name, int rnum, String depart){
super(name, rnum);
this.depart = depart;
}
void printProfessor() {
System.out.println("depart: "+depart);
}
}
public class InstanceofEx {
static void print(Person p) {
if(p instanceof Person) {
p.printInfo();
}
if(p instanceof Student) {
Student s = (Student)p;
s.printStudent();
}
if(p instanceof Researcher) {
Researcher r = (Researcher)p;
r.printResearcher();
}
if(p instanceof Professor) {
Professor pro = (Professor)p;
pro.printProfessor();
}
}
public static void main(String[] args) {
print(new Person("Person"));
print(new Student("Student", 100));
print(new Researcher("Resarcher", 1001));
print(new Professor("Professor", 1002, "computer"));
}
}
์ค๋ฒ๋ผ์ด๋ฉ
class Person{
String name;
Person(String name){
this.name = name;
}
void printInfo() {
System.out.println(name);
}
}
class Student extends Person{
int snum;
Student(String name, int snum){
super(name);
this.snum = snum;
}
@Override
void printInfo() {
super.printInfo();
System.out.println("snum: "+snum);
}
}
class Researcher extends Person{
int rnum;
Researcher(String name, int rnum){
super(name);
this.rnum = rnum;
}
@Override
void printInfo() {
super.printInfo();
System.out.println("rnum: "+rnum);
}
}
class Professor extends Researcher{
String depart;
Professor(String name, int rnum, String depart){
super(name, rnum);
this.depart = depart;
}
@Override
void printInfo() {
super.printInfo();
System.out.println("depart: "+depart);
}
}
public class InstanceofEx {
static void print(Person p) {
p.printInfo();
}
public static void main(String[] args) {
print(new Person("Person"));
print(new Student("Student", 100));
print(new Researcher("Resarcher", 1001));
print(new Professor("Professor", 1002, "computer"));
}
}
728x90
๋ฐ์ํ
0