CS2312 Lecture 7

Generic Classes and Case Study

ArrayList is an implementation of a growable array in Java - java.util.ArrayList

ArrayList uses to store objects

ArrayList contactList = new ArrayList();

Person p = new Person("Mike","1234",30);
Business b = new Business("Debonaires","2323");

contactList.add(p);
contactList.add(b);

((Person)contactList.get(0)).print();

Casting

contactList.get(0) returns a reference of type Object to a Person (“Mike”);  

(Person) casts that Object reference to  a reference of type Person.

((Person)contactList.get(0)) evaluates to a reference to a Person. 

.print() calls print on the Person. 

contactList.get(0) returns an Object reference which does not have the print() method

 

Can use inheritance, ((Contact)contactList.get(0)).print(); 

Contact defines print(), so can use Inheritance and cast to the superclass.  – Person and Business override print()  

Java will call print in Person using dynamic dispatch. 

for (int j = 0; j < contactList.size(); j++) { 
    ((Contact)contactList.get(j)).print();
}

Note:

contactList.add(new String(""));  // String extends Object, so this is legal

//But
((Contact)contactList.get(0)).print();   //the cast will fail, A Contact reference cannot be String!

Generics in Java - Better Solution

ArrayList<Contact> = new ArrayList<Contact>();

// This is read “Arraylist of Contacts”
// Do not have to cast!
// Have error checking!

GenericClass<Type> gc = new GenericClass<Type>();    

The type specified can either be an interface or a class.      

Reference declaration (left side) has to match object created (right side) 

ArrayList<Contact> contactList = new ArrayList<Contact>();

Person p = new Person(“Mike”, “123456”, 30);
Business b = new Business(“Debonaires”,“2323323234”);

contactList.add(p); 
contactList.add(b);

contactList.get(0).print();

for (int j = 0; j < contactList.size();j++){
    contactList.get(j).print();
}
// No Casting
// Less typing

// But
contactList.add(new String(“”));  //This statement will not compile! Because String is not a Contact!

 

 

Case Study(Review)

Encapsulation

  • Data Abstraction
  • Information hiding
  • The notion of class and object

Inheritance

  • Code reusability
  • Is-a vs. has-a relationships

Polymorphism

  • Dynamic method binding 

 

 

 

posted @ 2018-04-14 18:38  Charonnnnn  阅读(123)  评论(0编辑  收藏  举报