simpleclassdemo10.java
来自「JAVA程序设计课程中各章节的程序实例。」· Java 代码 · 共 65 行
JAVA
65 行
/**
*A demonstration program of the instanceof operator
*In object-oriented programming language upcasting is always legal
* it implies that a child class object can be referenced through a parent reference variable
* If the objects are passed around say in a function using reference to their parents
* the instanceof operator provides a way to differentiate between them as is shown in the
* program below
*It's a classic example!
*/
class Student
{
public void print()
{
System.out.println("I'm a student");
}
}
class Freshman extends Student
{
public void print()
{
System.out.println("I'm a first year student");
}
}
class Sophomore extends Student
{
public void print()
{
System.out.println("I'm a second year student");
}
}
public class simpleClassDemo10
{
public void identify(Student s)
{
if(s instanceof Freshman)
{
s.print();
System.out.println("Instance of the Freshman");
}
if(s instanceof Sophomore)
{
s.print();
System.out.println("Instance of the Sophomore");
}
}
public static void main(String args[])
{
Freshman obj1 = new Freshman();
Sophomore obj2 = new Sophomore();
simpleClassDemo10 obj = new simpleClassDemo10();
obj.identify(obj1);
obj.identify(obj2);
}
}
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?