📄 badcast.java
字号:
package examples.rtti;
/** Classes to demonstrate a run-time cast error
*/
public class BadCast {
/** Test method for the class
* @param args not used
*/
public static void main( String[] args ) {
Mammal horse = new Mammal( "horse" );
Reptile snake = new Reptile( "snake" );
Mammal mouse = new Mammal( "mouse" );
horse.categorize();
snake.categorize();
mouse.categorize();
}
}
/** A generic animal class
*/
class Animal {
protected String name;
public Animal( String name ) {
this.name = name;
}
public void categorize() {
try {
if ( ((Mammal) this).isRodent() ) {
System.out.println( "A " + name
+ " is a rodent." );
} else {
System.out.println( "A " + name
+ " is not a rodent." );
}
}
catch ( ClassCastException ccx ) {
ccx.printStackTrace();
}
try {
int legs = ((Reptile) this).numLegs();
System.out.println( "A " + name + " has "
+ legs + " legs." );
} catch ( ClassCastException ccx ) {
ccx.printStackTrace();
}
}
}
/** The class representing all mammals
*/
class Mammal extends Animal {
private static String[] rodents
= { "rat", "rabbit", "mouse", "beaver" };
public Mammal( String name ) {
super( name );
}
public boolean isRodent() {
for ( int i=0; i < rodents.length; i++ ) {
if ( name.equals( rodents[i] ) ) {
return true;
}
}
return false;
}
}
/** The class representing all reptiles
*/
class Reptile extends Animal {
public Reptile( String name ) {
super( name );
}
public int numLegs() {
if ( name.equals( "snake" ) ) {
return 0;
} else {
return 4;
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -