Java Tutorial/Data Type/Cast
Casting Objects
class Animal {
public String toString() {
return "This is an animal ";
}
}
class Dog extends Animal {
public void sound() {
System.out.println("Woof Woof");
}
}
class Cat extends Animal {
public Cat(String aName) {
name = aName;
}
public String toString() {
return super.toString() + "\nIt"s " + name + " the " + breed;
}
public void sound() {
System.out.println("Miiaooww");
}
private String name;
private String breed;
}
public class MainClass {
public static void main(String[] a) {
Cat aPet = new Cat("Fang");
Animal theAnimal = (Animal) aPet;
}
}
Convert an integer into binary, hexadecimal, and octal.
class StringConversions {
public static void main(String args[]) {
int num = 19648;
System.out.println(num + " in binary: " + Integer.toBinaryString(num));
System.out.println(num + " in octal: " + Integer.toOctalString(num));
System.out.println(num + " in hexadecimal: " + Integer.toHexString(num));
}
}