JAVA공부하기 110

instanceof

 

//InstanceofTest1.java

class Element {int atomicNumber;}

class Point extends Element {int x, y;}

class InstanceofTest1 {

public static void main(String[] args) {

Element e = new Element();

Point p = new Point();

if (e instanceof Point) {

Stystem.out.println("First Test : I get your point !");

p = (point)e;

}

e = p;

if (e instanceof Point) {

System.out.println("Second Test : I get your point!");
p = (Point)e;

}

if (e instanceof Element) {

System.out.println("Third Test : I get your Element!");

p = (point)e;

}

}

}

 

 

 

 

JAVA공부하기 109.

instanceof

- Instanceof 키워드는 좌우의 객체, 클래스가 서로 같은 계층에 있지 않을 경우 컴파일 에러를 발생시킨다.

 

- 좌측의 객체가 우측의 클래스로 캐스팅 될 수 있으면 true리턴

 

 

//InstanceofTest.java

class Element {int atomicNumber;}

class Point {int x, y;}

class InstanceofTest {

public static void main(String[] args) {

point p = new Point();

Element e = new Element();

if (e instanceof Point) { // compile-time error

System.out.println("I get your point!");

p=(point)e;    // compile-time error

}

}

 

 

 

+ Recent posts