Lecture 02 - Classes and Objects.pdf

Full Transcript

Object Oriented Programming IT2030 - Object Oriented Programming Lecture 02 Java Classes and Objects 1 SLIIT - Faculty of Computing Object Oriented Progr...

Object Oriented Programming IT2030 - Object Oriented Programming Lecture 02 Java Classes and Objects 1 SLIIT - Faculty of Computing Object Oriented Programming Learning Outcomes At the end of the Lecture students should be able to get a revision on OOC you learnt in Year 1 Object Oriented Programming Classes and Objects Abstraction Encapsulation Inheritance Polymorphism Interfaces We will also look at key differences between writing Simple Object Oriented Programs in C++ and Java. 2 SLIIT - Faculty of Computing Object Oriented Programming Object Oriented Programming Object Oriented programming is a method of implementation in which programs are organized as cooperative collections of objects, each of which represents an instance of some class, and whose classes are all members of a hierarchy of classes united via inheritance relationships. ( Reference : Grady Booch, eta (2008), Object Oriented Analysis and Design with Applications 3rd Edition, pg 41) 3 SLIIT - Faculty of Computing Object Oriented Programming Object Oriented Programming Object Oriented Programming is a method of implementation in which programs are organized as a collection of objects which cooperate to solve a problem. Allows to solve more complex problems easily 4 SLIIT - Faculty of Computing Object Oriented Programming Object Oriented Programming A complex system is developed using smaller sub systems Sub systems are independent units containing their own data and functions Can reuse these independent units to solve many different problems 5 SLIIT - Faculty of Computing Object Oriented Programming A Computer System 6 SLIIT - Faculty of Computing Object Oriented Programming Classes A class is the abstract definition of the data type. It includes the data elements that are part of the data type, and the operations which are defined on the data type. It is an Entity which could be a thing, person or something that is imaginary. 7 SLIIT - Faculty of Computing Object Oriented Programming Classes An entity can be described by the data ( Properties ) and its behavior ( methods ) Class Name e.g.: Attributes/Properties Methods 8 SLIIT - Faculty of Computing Object Oriented Programming Classes and Objects An Object is a specific instance of the data type (class) A class is a blue print of an object. House2 House1 Objects Class House House3 9 SLIIT - Faculty of Computing Object Oriented Programming Objects Objects are instances of classes, which we can use to store data and perform actions We need to define a class including the properties and methods and then create as many objects which has the same structure of the class ( House example ) 10 SLIIT - Faculty of Computing Object Oriented Programming Class in C++ Student class Student{ private : StudentNo int studentNo; Name char name; CA_marks Private int CA_mark; Final_mark int Final_mark; Total public: void assignMarks(int pCA, int pFin); assignMarks () int calculateTotal(); calculateTotal() Public void printDetails(); printDetails() }; 11 SLIIT - Faculty of Computing Object Oriented Programming Exercise 1 Identify the classes, attributes and what sort of objects that will have for hospital management system Write the classes and possible methods in simple English language 12 SLIIT - Faculty of Computing Object Oriented Programming Class in Java class Student { class Student{ private int studentNo; private : private String name; int studentNo; private int CA_mark; char name; private int Final_mark; int CA_mark; int Final_mark; public void assignMarks(int pCA, public: int pFin) { void assignMarks(int pCA, int pFin) { } } public int calculateTotal() { int calculateTotal() { } } public void printDetails() { void printDetails() { } } } }; C++ Java 13 SLIIT - Faculty of Computing Object Oriented Programming Java vs C++ All methods are implemented in the class definition in Java. Each property, method needs a specific access modifier e.g. private, public, protected In Java there is no semi colon at the end of the class In Java you only have dynamic objects. Since Java has an automatic garbage collector, you do not need to use a command line delete to remove objects from memory. We use the dot operator instead of the -> operator to access methods in Java. 14 SLIIT - Faculty of Computing Object Oriented Programming Private & Public The private part of the definition specifies the data members of a class These are hidden from outside the class and can only be accessed though the operations defined for the class The public part of the definition specifies the operations as function prototypes These operations, or methods as they are called, can be accesses by the main program. 15 SLIIT - Faculty of Computing Object Oriented Programming Private & Public student1 Private Public studentID assignMarks () name Client calculateTotal() CA_marks printDetails() Final_mark Total 16 SLIIT - Faculty of Computing Object Oriented Programming Creating Objects Student student1 = new Student(); Student student2 = new Student(); // We do not use * for pointers in Java student1 student2 studentNo – 1011 studentNo – I131 Name – Ajith Silva Name – Surani Fernando CA_mark - 56 CA_mark - 70 Final_mark -60 Final_mark -65 17 SLIIT - Faculty of Computing Object Oriented Programming Exercise 2 Select one class that selected from the hospital management system. Ex:- receptionist Write the relevant class using the java language 18 SLIIT - Faculty of Computing Object Oriented Programming Methods and Properties In C++ properties are called data members, other popular names for properties are attributes, variables. In C++ methods are called member functions, other popular names are operations, behaviors. These are really functions. 19 SLIIT - Faculty of Computing Object Oriented Programming Abstraction An abstraction denotes the essential characteristics of an object that distinguish it from all other kinds of objects and thus provide crisply defined conceptual boundaries, relative to perspective of the viewer. ( Reference : Grady Booch, eta (2008), Object Oriented Analysis and Design with Applications 3rd Edition, pg 44) 20 SLIIT - Faculty of Computing Object Oriented Programming Abstraction Abstraction is the process of removing characteristics from ‘something’ in order to reduce it to a set of essential characteristics that is needed for the particular system. 21 SLIIT - Faculty of Computing Object Oriented Programming Abstraction 22 SLIIT - Faculty of Computing Object Oriented Programming Exercise 3 Think of the class you selected in Hospital Management System. 1. What are the attributes needed ? 2. What are the attributes that can be omitted? 23 SLIIT - Faculty of Computing Object Oriented Programming Encapsulation Encapsulation is the process of compartmentalizing the elements of an abstraction that constitute its structure and behavior; encapsulation serves to separate the contractual interface of an abstraction and its implementation. ( Reference : Grady Booch, eta (2008), Object Oriented Analysis and Design with Applications 3rd Edition, pg 52) 24 SLIIT - Faculty of Computing Object Oriented Programming Encapsulation 25 SLIIT - Faculty of Computing Object Oriented Programming Encapsulation It is the process of grouping related attributes and methods together, giving a name to the unit and providing an interface for outsiders to communicate with the unit. 26 SLIIT - Faculty of Computing Object Oriented Programming Exercise 4 Explain what is encapsulation with related to your class in the Hospital Management System. 27 SLIIT - Faculty of Computing Object Oriented Programming Information Hiding Hide certain information or implementation decision that are internal to the encapsulation structure ( class ) The only way to access an object is through its public interface Public – anyone can access / see it Private – no one except the class can see/ use it 28 SLIIT - Faculty of Computing Object Oriented Programming Exercise 5 Modify your java classes so that it support for information hiding 29 SLIIT - Faculty of Computing Object Oriented Programming Interface 30 SLIIT - Faculty of Computing Object Oriented Programming Interface Employee Client setOtDetails() EmployeeNo Name setAllowance() Basic Salary OT Hours calcSal() OT Amount Allowance Salary printPaySlip() 31 SLIIT - Faculty of Computing Object Oriented Programming Terminology Employee Class name empNo Attributes name Properties basicSalary Data Members otHrs otRate allowance salary Employee(empNo, name, basicSalary) Methods setOtDetails() Behaviors setAllowance() member functions calcSalary() printPaySlip() 32 SLIIT - Faculty of Computing Object Oriented Programming Exercise 6 Implement a class called MyMain with a main method and Create Objects of the class to demonstrate the methods. 33 SLIIT - Faculty of Computing Object Oriented Programming Constructor The constructor is used to initialize the object when it is declared. The constructer does not return a value, and has no return type ( not even void ) The constructors has the same name as the class. There can be default constructers or constructors with parameters When an object is declared the appropriate constructor is executed. 34 SLIIT - Faculty of Computing Object Oriented Programming Constructor // default Constructor public static void main(String args[]) { public Rectangle () { // default constructor called width = 0; Rectangle r1 = new Rectangle(); // Second constructor called length = 0; Rectangle r2 = new Rectangle(10,20); } } // Constructor with parameters public Rectangle (int w, int l) { width = w; length = l; } 35 SLIIT - Faculty of Computing Object Oriented Programming Constructors Default Constructors Can be used to initialized attributes to default values public Rectangle () { width = 0; length = 0; } Overloaded Constructors ( Constructors with Parameters ) Can be used to assign values sent by the main program as arguments public Rectangle (int w, int l) { width = w; length = l; } 36 SLIIT - Faculty of Computing Object Oriented Programming Exercise 7 Take one class from your topic 1. Add the default constructor 2. And a parameterized constructor to initiate all attributes 37 SLIIT - Faculty of Computing Object Oriented Programming Getters and Setters In general properties are declared as private preventing them from being accessed from outside the class. Typically an attribute will have a getter (accessor) (A get method to return its value) and a setter (mutator) (A set method to set a value). e.g. a property called length will have a getter defined as int getLength() and a setter defined as void setLength(). Both these methods will be declared as public methods. 38 SLIIT - Faculty of Computing Object Oriented Programming Getters and Setters 39 SLIIT - Faculty of Computing Object Oriented Programming this keyword The this keyword can be used to refer to any member of the current object from within an instance Method or a constructor. We need to use this.name to refer to the property name to distinguish it from the parameter name. 40 SLIIT - Faculty of Computing Object Oriented Programming Exercise 8 Modify your class with getters and setters 41 SLIIT - Faculty of Computing Object Oriented Programming Generalization/Inheritance Child class is a type of the parent class Used to showcase reusable elements in the class diagram Child classes “inherit” the attributes and methods defined in the parent class Shape Rectangle Circle 42 SLIIT - Faculty of Computing Object Oriented Programming C++ vs Java - Inheritance C++ Java class Circle : public Shape { class Circle extends Shape { Java has a simpler inheritance mechanism where base class is extended as public. C++ has multiple inheritance compared to Java’s Single Inheritance. 43 SLIIT - Faculty of Computing Object Oriented Programming C++ vs Java - Inheritance C++ Java Circle (string tname, int r) : Shape ( tname) { public Circle (String tname, int r) { radius = r; super(tname); } radius = r; } When you want to call a base class constructor C++ Requires to explicitly name the base class. In Java we use the super keyword to access the direct descendent class. However this implies that in Java you can’t directly call a class higher in the hierarchy e.g. the Grandfather class which is not in C++ 44 SLIIT - Faculty of Computing Object Oriented Programming C++ vs Java - Inheritance C++ Java virtual void speak() {} public void speak() {} All methods in Java are virtual by default. In C++ we need to explicitly define polymorphic methods. 45 SLIIT - Faculty of Computing Object Oriented Programming Exercise 9 Think of a way of implementing generalization in you selected class 46 SLIIT - Faculty of Computing Object Oriented Programming Object Class A class hierarchy is similar to the taxonomy of animals that shows their ancestry. There are many breeds of dogs. A well known fact is that the common origin of a dog is the Gray Wolf. All Java classes are derived from a class called Object. This includes all the existing Java built in classes and the classes that you write. The methods and properties of the Object class is accessible to any Java class that you create. 47 SLIIT - Faculty of Computing Object Oriented Programming Inheritance Shapes Example C++ Shape_example.cpp 48 SLIIT - Faculty of Computing Object Oriented Programming Inheritance Shapes Example Java Shape_example.java 49 SLIIT - Faculty of Computing Object Oriented Programming Exercise 10 Write the java code in order to implement the inheritance 50 SLIIT - Faculty of Computing Object Oriented Programming Polymorphism Greek meaning “having multiple forms“ Ability to assign a different meaning or usage to something in different contexts Specifically, to allow an entity such as a variable, a function, or an object to have more than one form 51 SLIIT - Faculty of Computing Object Oriented Programming An example Consider the request (analogues to a method) “please cut this in half“ taking many forms 52 SLIIT - Faculty of Computing Object Oriented Programming “please cut this in half” Imagine this task is automated… Without polymorphism Need to tell the computer how to proceed for each situation With polymorphism Just tell please cut this in half The computer will handle the rest! 53 SLIIT - Faculty of Computing Object Oriented Programming Animal Example Animal_example.cpp Animal_example.java 54 SLIIT - Faculty of Computing Object Oriented Programming Exercise 11 Think of a way to implement Polymorphism in your solution 55 SLIIT - Faculty of Computing Object Oriented Programming Exercise 12 Implement the necessary classes, along with their required attributes and methods, based on the following description. You have been assigned the task of developing a simple system to manage the employees of a company. The system should consist of two classes, Employee and Manager. The Employee class should have three data members, EmpId, name, and address, which are all of string data type. It should also have a default constructor and a parameterize constructor to initialize these attributes. Create a getter and a setter to the attribute EmpId. Add two methods, Read () and Print(). The Read () should accept inputs for the above mentioned attributes through the keyboard and Print() should display their values. 56 SLIIT - Faculty of Computing Object Oriented Programming The Manager class should extend from the Employee class and should have two data members Department number (int), Department name (String). It should have a parameterized constructor to initialize all these attributes. Furthermore, you need to create a class called EmployeeApp with a main method where you can create 2 objects each from Employee and Manager classes. 57 SLIIT - Faculty of Computing Object Oriented Programming Thank you! 58 SLIIT - Faculty of Computing

Use Quizgecko on...
Browser
Browser