CSC 1214: Object-Oriented Programming

Similar documents
JAVA. Lab-9 : Inheritance

Unit 3 INFORMATION HIDING & REUSABILITY. -Inheritance basics -Using super -Method Overriding -Constructor call -Dynamic method

IS-A is a way of saying: This object is a type of that object. Let us see how the extends keyword is used to achieve inheritance.

Hierarchical abstractions & Concept of Inheritance:

Inherit a class, you simply incorporate the definition of one class into another by using the extends keyword.

Java Object Oriented Design. CSC207 Fall 2014

CSC 1214: Object-Oriented Programming

INHERITANCE Inheritance Basics extends extends

PROGRAMMING LANGUAGE 2

Darshan Institute of Engineering & Technology for Diploma Studies Unit 3

ITI Introduction to Computing II

CS-202 Introduction to Object Oriented Programming

ITI Introduction to Computing II

Inheritance. The Java Platform Class Hierarchy

Data Structures (list, dictionary, tuples, sets, strings)

Principles of Object Oriented Programming. Lecture 4

CREATED BY: Muhammad Bilal Arslan Ahmad Shaad. JAVA Chapter No 5. Instructor: Muhammad Naveed

What is Inheritance?

Object-Oriented Concepts

Programming II (CS300)

Overview of OOP. Dr. Zhang COSC 1436 Summer, /18/2017

8.1 Inheritance. 8.1 Class Diagram for Words. 8.1 Words.java. 8.1 Book.java 1/24/14

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub

CPS 506 Comparative Programming Languages. Programming Language

INHERITANCE & POLYMORPHISM. INTRODUCTION IB DP Computer science Standard Level ICS3U. INTRODUCTION IB DP Computer science Standard Level ICS3U

OBJECT ORIENTED PROGRAMMING. Course 4 Loredana STANCIU Room B616

IT101. Inheritance, Encapsulation, Polymorphism and Constructors

(SE Tutorials: Learning the Java Language Trail : Interfaces & Inheritance Lesson )

Java Fundamentals (II)

ECE 122. Engineering Problem Solving with Java

Inheritance, and Polymorphism.

Inheritance, Polymorphism, and Interfaces

G Programming Languages - Fall 2012

Programming II (CS300)

Chapter 5 Object-Oriented Programming

Argument Passing All primitive data types (int etc.) are passed by value and all reference types (arrays, strings, objects) are used through refs.

CS 251 Intermediate Programming Inheritance

Chapter 5. Inheritance

Lecture 3. COMP1006/1406 (the Java course) Summer M. Jason Hinek Carleton University

Day 3. COMP 1006/1406A Summer M. Jason Hinek Carleton University

Programming II (CS300)

CmSc 150 Fundamentals of Computing I. Lesson 28: Introduction to Classes and Objects in Java. 1. Classes and Objects

Subclasses, Superclasses, and Inheritance

Object Oriented Features. Inheritance. Inheritance. CS257 Computer Science I Kevin Sahr, PhD. Lecture 10: Inheritance

Computer Science 210: Data Structures

Inheritance. Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L

Object Oriented Programming. Java-Lecture 11 Polymorphism

Inheritance and Polymorphism

Programming II (CS300)

HAS-A Relationship. Association is a relationship where all objects have their own lifecycle and there is no owner.

What s Conformance? Conformance. Conformance and Class Invariants Question: Conformance and Overriding

Day 4. COMP1006/1406 Summer M. Jason Hinek Carleton University

CLASSES AND OBJECTS IN JAVA

Chapter 2: Java OOP I

CMSC 132: Object-Oriented Programming II. Inheritance

Object Oriented Programming is a programming method that combines: Advantage of Object Oriented Programming

Programming Language Concepts Object-Oriented Programming. Janyl Jumadinova 28 February, 2017

Exercise: Singleton 1

8. Polymorphism and Inheritance

Object Oriented Programming: Based on slides from Skrien Chapter 2

Distributed Systems Recitation 1. Tamim Jabban

Inheritance (continued) Inheritance

Inheritance -- Introduction

Computer Science II (20073) Week 1: Review and Inheritance

CMSC 132: Object-Oriented Programming II

Programming in Java, 2e Sachin Malhotra Saurabh Choudhary

CS1004: Intro to CS in Java, Spring 2005

HAS-A Relationship. Association is a relationship where all objects have their own lifecycle and there is no owner.

CS1150 Principles of Computer Science Objects and Classes

CS5000: Foundations of Programming. Mingon Kang, PhD Computer Science, Kennesaw State University

Abstract Classes and Polymorphism CSC 123 Fall 2018 Howard Rosenthal

Contents. I. Classes, Superclasses, and Subclasses. Topic 04 - Inheritance

Week 5-1: ADT Design

CSE 452: Programming Languages. Previous Lecture. From ADTs to OOP. Data Abstraction and Object-Orientation

Lecture 36: Cloning. Last time: Today: 1. Object 2. Polymorphism and abstract methods 3. Upcasting / downcasting

Arrays Classes & Methods, Inheritance

Inheritance. For example, to zoom in on the deer family (cervid), we could make a tree like the following.

Chapter 11. Categories of languages that support OOP: 1. OOP support is added to an existing language

Object Oriented Programming (OOP) is a style of programming that incorporates these 3 features: Encapsulation Polymorphism Class Interaction

CS260 Intro to Java & Android 03.Java Language Basics

ENCAPSULATION AND POLYMORPHISM

Implements vs. Extends When Defining a Class

Inheritance. Transitivity

Overview of Eclipse Lectures. Module Road Map

INHERITANCE. Spring 2019

Java for Non Majors Spring 2018

Object-Oriented Programming Concepts

Chapter 5: Classes and Objects in Depth. Information Hiding

CSC207H: Software Design. Java + OOP. CSC207 Winter 2018

More About Classes CS 1025 Computer Science Fundamentals I Stephen M. Watt University of Western Ontario

Inheritance Chapter 8. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

Object-Oriented Languages and Object-Oriented Design. Ghezzi&Jazayeri: OO Languages 1

CH. 2 OBJECT-ORIENTED PROGRAMMING

Superclasses / subclasses Inheritance in Java Overriding methods Abstract classes and methods Final classes and methods

Software Practice 1 - Inheritance and Interface Inheritance Overriding Polymorphism Abstraction Encapsulation Interfaces

Darrell Bethea June 6, 2011

UCLA PIC 20A Java Programming

Distributed Systems Recitation 1. Tamim Jabban

COMP Information Hiding and Encapsulation. Yi Hong June 03, 2015

a) Answer all questions. b) Write your answers in the space provided. c) Show all calculations where applicable.

Transcription:

CSC 1214: Object-Oriented Programming J. Kizito Makerere University e-mail: jkizito@cis.mak.ac.ug www: http://serval.ug/~jona materials: http://serval.ug/~jona/materials/csc1214 e-learning environment: http://muele.mak.ac.ug office: block A, level 3, department of computer science alt. office: institute of open, distance, and elearning, room 2 Encapsulation, Inheritance, and Polymorphism Kizito (Makerere University) CSC 1214 February, 2018 1 / 24

Overview 1 Encapsulation 2 Inheritance Introduction Variable Referencing Using super Method overriding Using final Abstract Methods and Classes 3 Polymorphism 4 Homework Kizito (Makerere University) CSC 1214 February, 2018 2 / 24

Encapsulation Encapsulation Encapsulation (aka Information hiding) is the mechanism that binds together code and the data it manipulates, and keeps both safe from outside interference and misuse This is achieved by making the fields in a class private and providing access to the fields via public methods Access to the code and data is controlled through a well-defined interface In java the basis of encapsulation is the class The main benefit of encapsulation is the ability to modify our implemented code without breaking the code of others who use our code Encapsulation gives maintainability, flexibility and extensibility to our code Kizito (Makerere University) CSC 1214 February, 2018 3 / 24

Encapsulation Encapsulation Example 1 (without encapsulation) class Car { String numberplate; // e.g. UBC 080A double speed = 0.0; // in kilometers per hour double maxspeed; // in kilometers per hour int year; double oldcarspeedlimit = 180.0; class CarDriver { public static void main(string args[]){ Car mycar = new Car(); mycar.speed = 380.0; // No encapsulation Kizito (Makerere University) CSC 1214 February, 2018 4 / 24

Encapsulation Encapsulation Example 2 (with encapsulation): Accessors and Mutators aka Getters and Setters public class EncapTest{ private String name, idnum; private int age; public int getage(){ return age; public String getname(){ // Accessor return name; public String getidnum(){ // Accessor return idnum; public void setage(int newage){ age = newage; public void setname(string newname){ name = newname; public void setidnum(string newid){ idnum = newid; public class RunEncap{ public static void main(string args[]){ EncapTest encap = new EncapTest(); // encap.name = "James"; Errro! encap.setname("james"); encap.setage(20); encap.setidnum("12343ms"); System.out.print( "Name : " + encap.getname()+ ", Age : " + encap.getage()); Kizito (Makerere University) CSC 1214 February, 2018 5 / 24 Output Name : James, Age : 20

Encapsulation Encapsulation Example 2 (with encapsulation): Accessors and Mutators aka Getters and Setters public class EncapTest{ private String name, idnum; private int age; public int getage(){ return age; public String getname(){ // Accessor return name; public String getidnum(){ // Accessor return idnum; public void setage(int newage){ age = newage; public void setname(string newname){ name = newname; public void setidnum(string newid){ idnum = newid; public class RunEncap{ public static void main(string args[]){ EncapTest encap = new EncapTest(); // encap.name = "James"; Errro! encap.setname("james"); encap.setage(20); encap.setidnum("12343ms"); System.out.print( "Name : " + encap.getname()+ ", Age : " + encap.getage()); Kizito (Makerere University) CSC 1214 February, 2018 5 / 24 Output Name : James, Age : 20

Encapsulation Encapsulation Example 2 (with encapsulation): Accessors and Mutators aka Getters and Setters public class EncapTest{ private String name, idnum; private int age; public int getage(){ return age; public String getname(){ // Accessor return name; public String getidnum(){ // Accessor return idnum; public void setage(int newage){ age = newage; public void setname(string newname){ name = newname; public void setidnum(string newid){ idnum = newid; public class RunEncap{ public static void main(string args[]){ EncapTest encap = new EncapTest(); // encap.name = "James"; Errro! encap.setname("james"); encap.setage(20); encap.setidnum("12343ms"); System.out.print( "Name : " + encap.getname()+ ", Age : " + encap.getage()); Kizito (Makerere University) CSC 1214 February, 2018 5 / 24 Output Name : James, Age : 20

Encapsulation Encapsulation Access control Visibility Modifiers Recall... In Java, we accomplish encapsulation through the appropriate use of visibility modifiers A modifier is a Java reserved word that specifies particular characteristics of a method or data Java has three visibility modifiers: public, protected, and private Access Specifiers/ Visibility Modifiers Variables Methods public Violate encapsulation Provide services to client objects private Enforce encapsulation Support other methods in the class Kizito (Makerere University) CSC 1214 February, 2018 6 / 24

Introduction Inheritance Inheritance is the process by which one object acquires the properties of another Supports the concept of hierarchical classification An inherited subclass (or child class) inherits all of the attributes from each of its ancestors in the class hierarchy The class from which the subclass is derived is called a superclass (also a base class or a parent class) Inheritance interacts with encapsulation as well To inherit a class, you incorporate the definition of one class into another by using the extends keyword All classes in the Java platform are descendants of Object Kizito (Makerere University) CSC 1214 February, 2018 7 / 24

Introduction Inheritance Example (3) class MountainBike extends Bicycle { /* * new fields and methods defining * a mountain bike would go here */ Java does not support multiple inheritance. OO languages that support multiple inheritance include C++, Python, Common Lisp In Java, we use the reserved keyword extends to establish an inheritance relationship between classes Kizito (Makerere University) CSC 1214 February, 2018 8 / 24

Introduction Inheritance Example (4) Box.java 1. // This program uses inheritance to extend Box 2. // Also illustrates method/constructor overloading 3. class Box { 4. double width, height, depth; 5. // construct clone of an object 6. Box(Box ob) { // pass object to constructor 7. width = ob.width; 8. height = ob.height; 9. depth = ob.depth; 10. 11. // constructor used when all dimensions specified 12. Box(double w, double h, double d) { 13. width = w; 14. height = h; 15. depth = d; 16. 17. Box() { // constructor used when no dimensions specified 18. // use -1 to indicate an uninitialized box 19. width = height = depth = -1; 20. 21. // constructor used when cube is created 22. Box(double len) { 23. width = height = depth = len; 24. 25. // compute and return volume 26. double volume() { 27. return width * height * depth; 28. 29. Kizito (Makerere University) CSC 1214 February, 2018 9 / 24

Introduction Inheritance Example (4) DemoBoxWeight.java 1. // Here, Box is extended to include weight 2. class BoxWeight extends Box { 3. double weight; // weight of the box 4. 5. // constructor for BoxWeight 6. BoxWeight(double w, double h, double d, double m) { 7. width = w; 8. height = h; 9. depth = d; 10. weight = m; 11. 12. 13. 14. class DemoBoxWeight { 15. public static void main(string args[]) { 16. BoxWeight mybox1= new BoxWeight(10, 20, 15, 34.3); 17. BoxWeight mybox2= new BoxWeight(2, 3, 4, 0.076); 18. Double vol; 19. 20. vol = mybox1.volume(); 21. System.out.println("Volume of mybox1 is " + vol); 22. System.out.println("Weight of mybox1 is " + mybox1.weight); 23. System.out.println(); 24. 25. vol = mybox2.volume(); 26. System.out.println("Volume of mybox2 is " + vol); 27. System.out.println("Weight of mybox2 is " + mybox2.weight); 28. 29. Output: Volume of mybox1 is 3000.0 Weight of mybox1 is 34.3 Volume of mybox2 is 24.0 Weight of mybox2 is 0.076 Kizito (Makerere University) CSC 1214 February, 2018 10 / 24

Variable Referencing Inheritance Superclass variable can reference subclass object BoxWeight wbox = new BoxWeight(3, 5, 7, 8.37); Box box = new Box(); double vol; // assign BoxWeight ref to Box ref box = wbox; vol = box.volume(); // OK // the following is invalid System.out.print("box s weight is "+ box.weight); Kizito (Makerere University) CSC 1214 February, 2018 11 / 24

Using super Inheritance Using super Avoids duplication of code, which is inefficient Subclasses do not necessarily have access to superclass members Two general forms: 1 Call a constructor method of a superclass super(parameter-list); 2 Access members of a superclass super.member Kizito (Makerere University) CSC 1214 February, 2018 12 / 24

Using super Inheritance Example (5) Using super // implementation of BoxWeight using super class Box { double width, height, depth; // construct clone of an object Box(Box ob) { // pass object to constructor width = ob.width; height = ob.height; depth = ob.depth; // constructor used when all dimensions specified Box(double w, double h, double d) { width = w; height = h; depth = d; // constructor used when no dimensions specified Box() { // use -1 to indicate an uninitialized box width = height = depth = -1; // constructor used when cube is created Box(double len) { width = height = depth = len; // compute and return volume double volume() { return width * height * depth; 30. // Add weight 31. class BoxWeight extends Box { 32. double weight; // weight of the box 33. 34. // construct clone of passed object 35. BoxWeight(BoxWeight ob) { 36. super(ob); 37. weight = ob.weight; 38. 39. // constructor when all parameters are specified 40. BoxWeight(double w, double h, double d, double m) 41. { 42. super(w, h, d); 43. weight = m; 44. 45. // default constructor 46. BoxWeight() { 47. super(); 48. weight = -1; 49. 50. // constructor used when cube is created 51. BoxWeight(double len, double m) { 52. super(len); 53. weight = m; 54. 55. Kizito (Makerere University) CSC 1214 February, 2018 13 / 24

Method overriding Inheritance Method overriding In a class hierarchy, when a method in a subclass has the same signature as a method in its superclass The super class method is said to be hidden By same signature we mean the subclass method has the same name, number and type of parameters, and return type as the one it overrides/hides An overriding method can also return a subtype of the type returned by the overridden method. This is called a covariant return type Another use of super unhides the hidden method Kizito (Makerere University) CSC 1214 February, 2018 14 / 24

Method overriding Method overriding Example (6) class A { int i, j; A(int a, int b) {i = a; j = b; void show() { System.out.print("i and j: "+ i +" "+ j); class B extends A { int k; //... void show() { super.show(); // call superclass version System.out.print(" k: "+ k); Kizito (Makerere University) CSC 1214 February, 2018 15 / 24

Using final Inheritance Using final to prevent Overriding Methods declared as final cannot be overridden class A { final void meth() { System.out.println("A final method"); class B extends A { void meth() { // ERROR! Can t override System.out.println("Illegal"); Kizito (Makerere University) CSC 1214 February, 2018 16 / 24

Using final Inheritance Using final to prevent Inheritance Classes declared as final cannot be inherited A final class has all of its methods as final, too final class A { //... // The following class is illegal class B extends A { // ERROR Can t subclass A //... Kizito (Makerere University) CSC 1214 February, 2018 17 / 24

Using final Inheritance Method Overloading Overloading Vs Overriding Don t confuse the concepts of overloading and overriding Overloading deals with multiple methods with the same name in the same class, but with different signatures Overriding deals with two methods, one in a parent class and one in a child class, that have the same signature Kizito (Makerere University) CSC 1214 February, 2018 18 / 24

Abstract Methods and Classes Inheritance Abstract Methods and Classes You can require that certain methods be overridden by subclasses An abstract method is a method that is declared without an implementation abstract void moveto(double deltax, double deltay); An abstract class is a class that is declared abstract it may or may not include abstract methods A class that includes abstract methods must be declared abstract When an abstract class is subclassed, the subclass usually provides implementations for all of the abstract methods in its parent class. However, if it does not, the subclass must also be declared abstract An abstract class can not be instantiated Unlike interfaces, abstract classes can contain fields that are not static and final, and they can contain implemented methods If an abstract class contains only abstract method declarations, it should be declared as an interface instead Kizito (Makerere University) CSC 1214 February, 2018 19 / 24

Abstract Methods and Classes Abstract Methods and Classes Example (7) abstract class GraphicObject { int x, y; //... void moveto(int newx, int newy) { /*... */ abstract void draw(); abstract void resize(); class Circle extends GraphicObject { void draw() { /*... */ void resize() { /*... */ class Rectangle extends GraphicObject { void draw() { /*... */ void resize() { /*... */ Kizito (Makerere University) CSC 1214 February, 2018 20 / 24

Polymorphism Polymorphism Polymorphism (from the Greek, meaning many forms ) is a feature that allows one interface to be used for a general class of actions In OOP, a reference can be polymorphic, which can be defined as having many forms One interface, multiple methods Consider a program that requires three types of stacks (integer, floating-point, and character values) Stack algorithm is the same Data being stored defers though Polymorphism, Encapsulation, and Inheritance work together We have already seen cases where Inheritance allows subclasses of a class to define their own unique behaviors and yet share some of the same functionality of the parent class this is Polymorphism Kizito (Makerere University) CSC 1214 February, 2018 21 / 24

Polymorphism Polymorphism Example (8) Recall our Bicycle example. We could have a method printdescription() overriden as below: public class MountainBike extends Bicycle { //... public void printdescription() { super.printdescription(); System.out.println("The MountainBike has a" + getsuspension() +" suspension."); public class RoadBike extends Bicycle { //... public void printdescription() { super.printdescription(); System.out.println("The RoadBike has "+gettirewidth()+"mm tires."); Kizito (Makerere University) CSC 1214 February, 2018 22 / 24

Homework Assignment Ia Classes and Objects Class Libraries, Packages, and GUI Applications Read about Class libraries, Packages, and GUI Applications (AWT and Swing) See ClassLibrariesPackagesGUIApps.pdf Kizito (Makerere University) CSC 1214 February, 2018 23 / 24

Homework Assignment Ib Classes and Objects Approximating Mathematical Constant π = 3.14159 26535 89793 23846 26433 83279... Using Objects in the Java Language class simplecalc { // Your task is to define this class simplecalcdemo { public static void main (String [] argv) { // This I have written for you Group size and what to hand in Due date In case of groups, maximum size is 6 (six)? Hand in hard copies of your source code Monday 26 th February 2018 Some π approximations: 355 113 gives more exact digits? 3 1, 22 7, 333 106, 355 113, 103993 33102, 104348 33215, 208341 66317, 312689 99532, 833719 265381, 1146408 364913, 4272943 1360120, 5419351 1725033 Test your program correct to at least 14 decimal places Kizito (Makerere University) CSC 1214 February, 2018 24 / 24

Homework Assignment Ib Classes and Objects Approximating Mathematical Constant π = 3.14159 26535 89793 23846 26433 83279... Using Objects in the Java Language class simplecalc { // Your task is to define this class simplecalcdemo { public static void main (String [] argv) { // This I have written for you Group size and what to hand in Due date In case of groups, maximum size is 6 (six)? Hand in hard copies of your source code Monday 26 th February 2018 Some π approximations: 355 113 gives more exact digits? 3 1, 22 7, 333 106, 355 113, 103993 33102, 104348 33215, 208341 66317, 312689 99532, 833719 265381, 1146408 364913, 4272943 1360120, 5419351 1725033 Test your program correct to at least 14 decimal places Kizito (Makerere University) CSC 1214 February, 2018 24 / 24