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 Classes, Using Objects, and Cleanup Kizito (Makerere University) CSC 1214 February, 2018 1 / 23
Overview 1 Classes 2 Objects 3 Initialization 4 Cleanup 5 Access control Kizito (Makerere University) CSC 1214 February, 2018 2 / 23
Classes Classes Introduction A class is a template for an object An object is an instance of a class A class defines a new type which can be used to create objects of that type Declared by use of the class keyword Definition specifies the data it contains and the code that operates on that data Think of a class as a plan for a house. Before you build a house, you should have a plan. Once you have a plan, however, you can build any number of houses that follow that plan. An object has behaviours i.e., what it can do (what can be done to it) Kizito (Makerere University) CSC 1214 February, 2018 3 / 23
Classes Classes General Form class classname { type instance-variable1; type instance-variable2; //... type instance variablen; type methodname1(parameter-list) { // body of method type methodname2(parameter-list) { // body of method //... type methodnamen(parameter-list) { // body of method Kizito (Makerere University) CSC 1214 February, 2018 4 / 23
Classes Classes Members of the Class Data, or variables, defined within a class are called instance variables Methods are groups of related statements in a class that perform a specific task i.e., The code that operates on the data is contained within methods A simple class class Box { double width; double height; double depth; The methods and the code are called members of the class The new data type here is called Box Box mybox = new Box(); // create a Box object Members of an object can be accessed using the dot (.) operator mybox.width = 100; Kizito (Makerere University) CSC 1214 February, 2018 5 / 23
Classes Classes Members of the Class Data, or variables, defined within a class are called instance variables Methods are groups of related statements in a class that perform a specific task i.e., The code that operates on the data is contained within methods A simple class class Box { double width; double height; double depth; The methods and the code are called members of the class The new data type here is called Box Box mybox = new Box(); // create a Box object Members of an object can be accessed using the dot (.) operator mybox.width = 100; Kizito (Makerere University) CSC 1214 February, 2018 5 / 23
Objects Objects Declaring objects class Box { double width; double height; double depth; Two steps involved 1 Box mybox; // declare reference to object 2 mybox = new Box(); // allocates an object Can be combined into one statement Box mybox = new Box(); Kizito (Makerere University) CSC 1214 February, 2018 6 / 23
Objects Methods class Box { double width; double height; double depth; void volume() { System.out.print("Volume is "); System.out.println(width*height*depth); Kizito (Makerere University) CSC 1214 February, 2018 7 / 23
Objects Objects Methods (returning a value) class Box { double width; double height; double depth; double volume() { double vol = width * height * depth; return vol; Kizito (Makerere University) CSC 1214 February, 2018 8 / 23
Objects Methods (returning a value) Smarter class Box { double width; double height; double depth; double volume() { return width * height * depth; Kizito (Makerere University) CSC 1214 February, 2018 9 / 23
Objects Objects Methods can take parameters int square(int i) { return i * i; square() will return the square of whatever value it is called with Example int x, y, z; x = square(5); // x equals 25 y = square(9); // y equals 81 z = square(y); // z equals 4 Note that the syntax of calling it varies from that of C since the method will now be contained in some class Kizito (Makerere University) CSC 1214 February, 2018 10 / 23
Initialization Initialization Java initializes all class member variables to zero whenever we create an object Java allows us to write constructors, special methods, one of which will be called on object creation Using constructors, we can initialize class members to values of our choice Kizito (Makerere University) CSC 1214 February, 2018 11 / 23
Initialization Initialization Constructors A constructor initializes an object upon creation Has the same name as the class in which it resides Syntactically similar to a method but has no return type, not even void Automatically called immediately after the object is created, before the new operator completes Like methods, constructors can be parameterized Kizito (Makerere University) CSC 1214 February, 2018 12 / 23
Initialization Constructors Example (1) class Box { double width; double height; double depth; Box(double w, double h, double d) { width = w; height = h; this.depth = d; // redundant use of this double volume() { return width * height * depth; Kizito (Makerere University) CSC 1214 February, 2018 13 / 23
Initialization Constructors Example (2) Proper use of this class Box { double width; double height; double depth; Box(double width, double height, double depth) { this.width = width; this.height = height; this.depth = depth; double volume() { return width * height * depth; Kizito (Makerere University) CSC 1214 February, 2018 14 / 23
Initialization Constructors The default constructor How come even when I don t write constructors, my program runs? The compiler will write one for you! But only if you haven t written any constructors at all (for this class) A default constructor has no arguments (but still has the same name as the class) Kizito (Makerere University) CSC 1214 February, 2018 15 / 23
Initialization Creating Objects Example (3) DemoBox.java 1. class DemoBox { 2. public static void main(string args[]) { 3. Box mybox1 = new Box(10, 20, 15); 4. Box mybox2 = new Box(2, 3, 4); 5. Double vol; 6. 7. vol = mybox1.volume(); 8. System.out.println("Volume of mybox1 is " + vol); 9. 10. vol = mybox2.volume(); 11. System.out.println("Volume of mybox2 is " + vol); 12. 13. Output: Volume of mybox1 is 3000.0 Volume of mybox2 is 24.0 Kizito (Makerere University) CSC 1214 February, 2018 16 / 23
Initialization Example (4) The Stack Class Stack.java 1. // this class defines an integer stack that can hold 10 values 2. class Stack { 3. int tos, stck[] = new int[10]; 4. 5. Stack() { tos = -1; // initialize top-of-stack 6. 7. void push(int item) { // push an item onto the stack 8. if (tos==9) 9. System.out.println("Stack is full."); 10. else 11. stck[++tos] = item; 12. 13. 14. int pop() { // pop an item from the stack 15. if (tos < 0) { 16. System.out.println("Stack underflow."); 17. return 0; 18. else 19. return stck[tos--]; 20. 21. Kizito (Makerere University) CSC 1214 February, 2018 17 / 23
Initialization Example (4) The Stack Class Tester Test.java 1. class Test { 2. public static void main(string args[]) { 3. Stack mystack1 = new Stack(); 4. Stack mystack2 = new Stack(); 5. 6. // push some numbers onto the stack 7. for (int i = 0; i < 10; i++) mystack1.push(i); 8. for (int i = 10; i < 20; i++) mystack2.push(i); 9. 10. // pop those numbers from the stack 11. System.out.println("Stack in mystack1:"); 12. for (int i = 0; i < 10; i++) 13. System.out.println(mystack1.pop()); 14. 15. System.out.println("Stack in mystack2:"); 16. for (int i = 0; i < 10; i++) 17. System.out.println(mystack2.pop()); 18. 19. Kizito (Makerere University) CSC 1214 February, 2018 18 / 23
Initialization The test program generates the following output: The Stack Class Example Output Stack in mystack1: 9 8 7 6 5 4 3 2 1 0 Stack in mystack2: 19 18 17 16 15 14 13 12 11 10 Kizito (Makerere University) CSC 1214 February, 2018 19 / 23
Initialization Initialization Static Methods class A { void meth1() { /* implementation */ static void meth2() { /* implementation */ class Test { public static void main(string args[]){ A obj = new A(); obj.meth1(); // Ok obj.meth2(); // Illegal, meth2() is a class method A.meth2(); // Ok A.meth1(); // Illegal, meth1 is not a class method Kizito (Makerere University) CSC 1214 February, 2018 20 / 23
Cleanup Example Cleanup (Garbage collection) In some languages like C and C++, dynamically allocated objects must be manually released Java handles de-allocation automatically When no reference exists, the memory is reclaimed Garbage collection occurs during the execution of the program Java run-time implementations take varying approaches to garbage collection String name1 = new String("John Mary"); String name2 = new String("Michael Smith"); name2 = name1; // no more reference to Michael Smith object Kizito (Makerere University) CSC 1214 February, 2018 21 / 23
Cleanup Example Cleanup (Garbage collection) In some languages like C and C++, dynamically allocated objects must be manually released Java handles de-allocation automatically When no reference exists, the memory is reclaimed Garbage collection occurs during the execution of the program Java run-time implementations take varying approaches to garbage collection String name1 = new String("John Mary"); String name2 = new String("Michael Smith"); name2 = name1; // no more reference to Michael Smith object Kizito (Makerere University) CSC 1214 February, 2018 21 / 23
Cleanup Cleanup The finalize() method Necessary for objects that need to perform some actions when it is destroyed Although Java supports constructors, it does not have destructors. Instead, it has a finalize() function protected void finalize() { // finalization code goes here... The keyword protected (discussed on next slide) is a specifier that prevents access to finalize() by code defined outside its class Kizito (Makerere University) CSC 1214 February, 2018 22 / 23
Access control Access control private, public, and protected Three access specifiers: private, public, and protected private: can only be accessed by other members of its class public: can be accessed by any other code in the program protected: like private but only applies when inheritance is involved Variables and methods declared with public visibility are inherited; those with private visibility are not The protected modifier allows a member of a superclass to be inherited into a subclass We shall discuss inheritance in the next Lecture Default: public in the same package Kizito (Makerere University) CSC 1214 February, 2018 23 / 23