Java runtime type information (RTTI) exercise (I), javartti

Source: Internet
Author: User

Java runtime type information (RTTI) exercise (I), javartti

Example 1: implement the class and its structure as shown in. Pet is the base class. Cat, Dog, and Rodent inherit Pet directly, and the remaining classes inherit from their own superclasses. The base class Pet automatically generates a non-repeated encoding for each instance (including subclass instances) and stores it in the private domain long id. The base class Pet reloads the toString () function and returns the type name + number.

Implement the PetCreator class. 1) implement the public method to return a reference pointing to a random Pet subclass object; 2) implement the public method to return an array filling the random Pet subclass object; 3) the public method is used to return a List of randomly populated Pet subclass objects.

Solution 1:

1) create a Pet and its subclass, and write a. java file for each class.

//:pets\\Pet.javapackage pets;public class Pet{    private static long counter;    private long id = counter++;        public String toString(){        return getClass().getSimpleName()+"_"+id;}//:pets\\Cat.javapackage pets;public class Cat extends Pet{}//:pets\\EgyptianMau.javapackage pets;public class EgyptianMau extends Cat{}//:pets\\Manx.javapackage pets;public class Manx extends Cat{}//:pets\\Cymric.javapackage pets;public class Cymric extends Manx{}//:pets\\Dog.javapackage pets;public class Dog extends Pet{}//:pets\\Mutt.javapackage pets;public class Mutt extends Dog{}//:pets\\Pug.javapackage pets;public class Pug extends Dog{}//:pets\\Rodent.javapackage pets;public class Rodent extends Pet{}//:pets\\Rat.javapackage pets;public class Rat extends Rodent{}//:pets\\Mouse.javapackage pets;public class Mouse extends Rodent{}//:pets\\Hamster.javapackage pets;public class Hamster extends Rodent{}

2) Implement the PetCreator class and place it in the PetCreator. java file.

//:pets\\PetCreator.javapackage pets;import java.util.*;public class PetCreator{    public Pet getRandomPet() throws Exception {        return types.get(rand.nextInt(types.size())).newInstance();    }    public Pet[] getRandomPetArray(int size) throws Exception{        Pet[] pets = new Pet[size];        for(int i = 0; i < size; i++){            pets[i] = getRandomPet();        }        return pets;    }    public List<Pet> getRandomPetList(int size) throws Exception{        List<Pet> pets = new LinkedList<Pet>();        for(int i = 0; i < size; i++){            pets.add(getRandomPet());        }        return pets;    }    private Random rand = new Random(47);    private static final String typeNames[] = {        "pets.Pug",  "pets.Mutt",        "pets.EgyptianMau", "pets.Manx", "pets.Cymric",        "pets.Rat", "pets.Mouse", "pets.Hamster"    };    private static List<Class<? extends Pet>> types = new ArrayList<Class<? extends Pet>>();    static{        loader();    }    @SuppressWarnings("unchecked")    private static void loader(){        for(String name : typeNames){            try{                types.add((Class<? extends Pet>) Class.forName(name));            }catch(ClassNotFoundException e){                e.printStackTrace();                throw new RuntimeException();            }        }    }    public static void main(String[] args) throws Exception {        PetCreator pc = new PetCreator();        for(int i = 0; i < 5; i++){            System.out.println(pc.getRandomPet());        }        System.out.println(Arrays.toString(pc.getRandomPetArray(5)));        System.out.println(pc.getRandomPetList(5));    }}/* outputRat_0Manx_1Cymric_2Pug_3Mutt_4[Cymric_5, Mutt_6, Manx_7, Cymric_8, Rat_9][EgyptianMau_10, Hamster_11, EgyptianMau_12, Pug_13, Pug_14]*/

Analysis:

  • The getName () method called in the toString () method of the base class Pet will be dynamically bound to the corresponding method of the subclass during compilation.
  • The Application of generic rules to Class objects is different from the general generic rules. For example, if you apply a generic type to the List interface, the List object referenced by List <Pet> can be stored as a reference of any Pet subclass, however, the reference of Class <Pet> cannot point to the Class Object of the Pet subclass. This is because although the Pet subclass inherits from Pet, the Class Object of the Pet subclass is not a subclass of the Class Object of the Pet Class. Therefore, wildcard (wildcard) is required for Class Object generic applications ). For example, the Class object that can point to any Pet subclass is referenced as a Class <? Extends Pet>.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.