Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Java Instanceof keyword, will you use it?


May 30, 2021 Article blog



a instanceof A: The purpose of the keyword is to determine whether the instantiated object of class A can be assigned to object a, returning data of a boolean type. Recommended lessons: Java micro-class, Java advanced: Web development practice

Example:

class A{

public void eat() {

System.out.println ("Father A Eating");

}

}

class B extends A{

public void eat() {

System.out.println ("Child B Take");

}

}

class C extends A{

public void eat() {

System.out.println ("Subclass C Meals");

}

}

public class Shiyan {

public static void main(String[] args) {

// TODO Auto-generated method stub

A a a = new b (); / / up transformation, the instance of class B is assigned to class A object

a.eat (); // to call through class A, class B EAT method

// a The role of the instanceOf A keyword is to determine the instantiated object of class A that can be assigned to object a.

C c = (c) a; // uses forced conversion to enforce the object of Class B into C's instantiated objects.The compiler can be compiled, but the error will be reported when running.

a.eat();

}

Run without the Instanceof keyword as follows:

The compiler reported a type conversion exception

Subclass B eats
Exception in thread "main" java.lang.ClassCastException: class polymorphism. B cannot be cast to class polymorphism. C (polymorphism. B and polymorphism. C are in unnamed module of loader 'app')
at polymorphism. Shiyan.main(Shiyan.java:28)

Improved use of the keyword Instanceof code:

At this point, use keyword instanceof, determine if it can be converted successfully

class A{

public void eat() {

System.out.println ("Father A Eating");

}

}

class B extends A{

public void eat() {

System.out.println ("Child B Take");

}

}

class C extends A{

public void eat() {

System.out.println ("Subclass C Meals");

}

}

public class Shiyan {

public static void main(String[] args) {

// TODO Auto-generated method stub

A a a = new b (); / / up transformation, the instance of class B is assigned to class A object

a.eat (); // to call through class A, class B EAT method

// a The role of the instanceOf A keyword is to determine the instantiated object of class A that can be assigned to object a.

boolean isturue=a instanceof C;

System.out.println(isturue);

}

Improved results:
Subclass B eats
false