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