70 likes | 236 Views
Class and Object. Class vs Object. Let us consider the following scenario… Class defines a set of attributes/fields and a set of methods/services. Object is an instance of a class. Object allows you to call the methods defined in the Class. Class Computer.
E N D
Class vs Object • Let us consider the following scenario… • Class defines a set of attributes/fields and a set of methods/services. • Object is an instance of a class. Object allows you to call the methods defined in the Class
Class Computer • In Class Computer, you can declare all relevant attributes. • In Class Computer, you can define/implement all services/methods (non static) Computer class Computer { private string mfr; private int year; … public void set_mfr(…) {…} public string get_mfr() {…} public void editAfile(){… ;save(..);} } • - String: mfr • Int: year • Double: price + set_mfr(…){..} + get_mfr(){..} + editAfile() {…} Every attribute MUST be private AND you must provide Two methods related to each attribute to allow set a value And get the value !!!
Object Computer • You cannot use any services provided by a computer until you have a computer. Computer myPC = new Computer(“IBM”, 2012,1000); myPC.editAfile(); Computer mylaptop= new Computer(“Dell”, 2010,900); mylaptop.editAfile();
USB Flash Drive • Assume USB Flash correctly implements the save data service via method save() • Where should you put method save() • Copy save() method to Class Computer • Create a separate class for USB Flash Drive where save() is provided.
Class USBFlashDrive • We better introduce a new class USBFlashDriveand save() is defined as a method in that class Computer class Computer { private string mfr; private int year; … public void set_mfr(…) {…} public string get_mfr() {…} public void editAfile(){… ; ;} } • - String: mfr • Int: year • Double: price private USBFlashDriveusb; + set_mfr(…){..} + get_mfr(){..} + editAfile() {…} public void set_usb(USBFlashDrive u){…} public USBFlashDriveget_usb(){…} usb.save() USBFlashDrive - String: loc + save() {…}
Now You can use the save() service • You need to buy a computer and a usb flash drive Computer mylaptop = new Computer(“Dell”, 2010,900); USBFlashDrivemyusb = new USBFlashDrive(…); mylaptop.editAfile(); mylaptop.setusb(myusb); Don’t forget to connect myusb to mylaptop!!!