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 

 

 

 

转载于:https://www.cnblogs.com/charon922/p/8833976.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值