Object Oriented Programming CS 243 Defining your own
Object- Oriented Programming (CS 243) Defining your own classes 1
OO Programming Concepts Object-oriented programming (OOP) involves programming using objects. An object represents an entity in the real world that can be distinctly identified. For example, a student, a desk, a circle, a button, and even a loan can all be viewed as objects. An object has a unique identity, state, and behaviors. The state of an object consists of a set of data fields (also known as properties) with their current values. The behavior of an object is defined by a set of methods.
Why Programmer-Defined Classes? • Using just standard API classes will not meet all of our needs. We need to be able to define our own classes customized for our applications. • Learning how to define our own classes is the first step toward mastering the skills necessary in building large programs. • Classes we define ourselves are called programmer-defined classes.
Example : classes in different systems Banking System Student Registration System Class Employee Class Manager Class Student Class Lecturer Class Bank. Account Class Course Class Credit. Card Class. Room Voting System Library System Class Voting Class Citizen Class Book Class Library. Member Class vote Class Employee Class Candidate 4
class Student { String name; double GPA; Int regidteration. Number; …………………. . void register. Unit() { ………………… } void pay. Fees(){……} class. Name { Variables describing state Methods describing behavior } } Student object 1 Student object 2 name =Ahmed Aly registration number=245245 GPA=3. 2 name =Mohamed Fathi registration number=34345 GPA=2. 2 register a unit pay. Fees 5
Objects & classes • Real-world objects share two characteristics: they all have state and behavior. • in your program, you will have software objects which are objects that you want to manipulate. • The state of an object is represented by variables with their current values. • The behavior of an object is defined by a set of methods • The terms object and instance are interchangeable. • Objects of the same type are defined using a common class. • The class defines the type of variables the object can have and the type of method the object can execute. Radio might have states (on, off, current volume, current station) and behavior (turn on, turn off, increase volume, decrease volume, seek, scan, and tune). 6
Example : Class Radio public class Radio{ int volume; String station; boolean power. Status; public void increase. Volume(){ volume++; } public void decrease. Volume(){ volume--; } public void change. Station(String new. Station){ station=new. Station; } public void turn. On(){ volume=3; power. Status=true; } public void turn. Off(){ volume=0; power. Status=false; } } Radio object 1 volume =4 station=“Negoom FM” Powerstatus=true Radio object 2 volume =7 station=“Quran” Powerstatus=true Radio object 3 volume =0 station=“FM” Powerstatus=false Turn On volume =3 station=“FM” Powerstatus=true 7
Template for Class Definition Import Statements Class Comment class { Class Name Data Members Methods (incl. Constructor) } A class will have variables , constructors and methods. All these are known as class members
The Definition of the Bicycle Class class Bicycle { // Data Member private String owner. Name; //Constructor: Initialzes the data member public Bicycle( ) { owner. Name = "Unknown"; } //Returns the name of this bicycle's owner public String get. Owner. Name( ) { } return owner. Name; //Assigns the name of this bicycle's owner public void set. Owner. Name(String name) { } } owner. Name = name;
Data Member Declaration <modifiers> <data type> <name> ; Modifiers Data Type private String Name owner. Name ; Note: There’s only one modifier in this example. ØClass members can be declared with access modifier as public or protected or private. Ø the default access modifier is “ package”Chapter 4 - 10
Method Declaration <modifier> <return type> <method name> ( <parameters> <statements> } Modifier Return Type public void Method Name set. Owner. Name owner. Name = name; ( Parameter String name ) { Statements } ØClass members can be declared with access modifier as public or protected or private. Ø the default access modifier is “ package”Chapter 4 - 11 ){
Example : Class Gas. Tank • Write a class named Gas. Tank containing: – An instance variable named amount of type double, initialized to 0. – A method named add. Gas that accepts a parameter of type double. The value of the amount instance variable is increased by the value of the parameter. – A method named use. Gas that accepts a parameter of type double. The value of the amount instance variable is decreased by the value of the parameter. – A method named get. Gas. Level that accepts no parameters. get. Gas. Level returns the value of the amount instance variable. 12
Constructor • A constructor is a special method that is executed when a new instance of the class is created. public <class name> ( <parameters> ){ <statements> } Modifier public Class Name Bicycle Parameter ( ) { owner. Name = "Unassigned"; } Statements
Encapsulation • The data (state) of an object is private – it cannot be accessed directly. • The state can only be changed through its behaviour, otherwise known as its public interface or contract • This is called encapsulation
Constructors are a special Circle() { kind of methods that are } invoked to perform initializing actions. Circle(double new. Radius) { radius = new. Radius; }
Constructors, cont. A constructor with no parameters is referred to as a no-arg constructor. · Constructors must have the same name as the class itself. · Constructors do not have a return type—not even void. · Constructors are invoked using the new operator when an object is created. Constructors play the role of initializing objects.
Constructors…. . ØConstructor must have the same name as the class name. ØConstructors do not have a return type—not even void, can not be static. Ødefault blank constructor, is provided automatically only if no constructors are explicitly declared in the class. ØA constructor is generally used to do initial setup for an object class Circle { double radius=0 ; public Circle() { } public Circle (double r) { radius=r; } public double find. Area() { // } } multiple constructors with the same name but different signatures can exist. (overloading) 17
class Emp { private String name; private String id; private int salary; Emp() // default constructor. No argument list { name = “Ahmet"; id = "1234"; salary = 100; } public Emp(String n, String i, int s) // non-default constructor { name = n; id = i; salary = s; } void display() { System. out. println("n. Employe Info "); System. out. println("Name "+ name); System. out. println("ID "+ id); System. out. println("Salary "+ salary); } }
class Ex. Emp { public static void main(String [] args) { Emp e 1 = new Emp(); e 1. display(); Emp e 4 = new Emp("Ali", "98745", 400); e 4. display(); } }
Declaring/Creating Objects in a Single Step Class. Name object. Ref. Var = new Class. Name(); Example: Circle my. Circle = new Circle();
How to create an object from class? ØTo construct an object from a class, invoke a constructor of the class using the new operator, as follows: new Class. Name(arguments); Øconstructor can contain any type of code that a normal method could contain. When constructor is invoked an object is created and also code in constructor is executed. class Circle { double radius=0 ; public Circle() { } public Circle (double r) { radius=r; } public double find. Area() { return radius * 3. 14; } } c 1 class Test{ public static void main (String [] arg) { Circle c 1; c 1=new Circle(); Circle c 2= new Circle(); Circle c 3= new Circle(5. 1); } } c 1, c 2, c 3 are reference data types radius=0 c 2 radius=0 c 3 radius=5. 1 21
Example 3 : Class Car • Design and implement a class called Car that contains instance data that represents the make, model, and year of the car (as a String, String and int values respectively). Define the Car constructor to initialize these values (in that order). • Include getter and setter methods for all instance data 22
Revisiting the Bicycle Class class Bicycle { // Data Member private String owner. Name; //Constructor: Initialzes the data member public Bicycle( ) { owner. Name = "Unknown"; } //Returns the name of this bicycle's owner public String get. Owner. Name( ) { } return owner. Name; //Assigns the name of this bicycle's owner public void set. Owner. Name(String name) { } } owner. Name = name;
Using the Bicycle Class class Bicycle. Registration { public static void main(String[] args) { Bicycle bike 1, bike 2; String owner 1, owner 2; bike 1 = new Bicycle( ); //Create and assign values to bike 1. set. Owner. Name("Adam Smith"); bike 2 = new Bicycle( ); //Create and assign values to bike 2. set. Owner. Name("Ben Jones"); owner 1 = bike 1. get. Owner. Name( ); //Output the information owner 2 = bike 2. get. Owner. Name( ); System. out. println(owner 1 + " owns a bicycle. "); System. out. println(owner 2 + " also owns a bicycle. "); } }
Multiple Instances • Once the Bicycle class is defined, we can create multiple instances. bike 1 bike 2 Bicycle bike 1, bike 2; : Bicycle bike 1 = new Bicycle( ); bike 1. set. Owner. Name("Adam Smith"); owner. Name “Adam Smith” bike 2 = new Bicycle( ); bike 2. set. Owner. Name("Ben Jones"); Sample Code Chapter 4 - 25 : Bicycle owner. Name “Ben Jones”
Example : Adding constructors to class Radio public class Radio{ int volume; String station; boolean power. Status; public Radio() { volume=3; } public Radio(int start. Volume) { volume= start. Volume; } public void increase. Volume(){ volume++; } public void decrease. Volume(){ volume--; } public void change. Station(String new. Station){ station=new. Station; } public void turn. On(){ power. Status=true; } public void turn. Off(){ volume=0; power. Status=false; } } class Test { public static void main (String [] args) { Radio radio 1=new Radio(); radio 1. turn. On(); radio 1. increase. Volume(); Radio radio 2=new Radio(5); } } 26
What will be the output ? public class Box { double width; double height; double depth; double volume; public Box(double w, double h, double d) { width=w; height=h; depth=d; } } 1 -compile error 2 -Runtime error 3 -Compile and run without error 1 -compile error Default constructor should be written public class Test { public static void main(String args[]) { Box mybox 1 = new Box( ); } 27
Example : The Account Class class Account { private String owner. Name; public void set. Initial. Balance (double bal) { private double balance; public Account( ) { owner. Name = "Unassigned"; balance = 0. 0; } } balance = bal; public void set. Owner. Name (String name) { public void add(double amt) { balance = balance + amt; } } } owner. Name = name; public void deduct(double amt) { balance = balance - amt; } public double get. Current. Balance( ) { return balance; } public String get. Owner. Name( ) { } return owner. Name; Page 1 Page 2
Arguments and Parameters class Sample { class Account { public static void main(String[] arg) { } . . . Account acct = new Account(); . . . public void add(double amt) { acct. add(400); . . . } . . . } parameter argument balance = balance + amt; . . . } • An argument is a value we pass to a method • A parameter is a placeholder in the called method to hold the value of the passed argument.
Matching Arguments and Parameters • The number or arguments and the parameters must be the same • Arguments and parameters are paired left to right • The matched pair must be assignmentcompatible (e. g. you cannot pass a double argument to a int parameter) Demo demo = new Demo( ); int i = 5; int k = 14; demo. compute(i, k, 20); 3 arguments Passing Side class Demo { public void compute(int i, int j, double x) {. . . } } 3 parameters Receiving Side ©The Mc. Graw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 4 - 30
Calling a constructor from another constructor class Box{ double width; double height; double depth; Box(double w, double h, double d){ width = w; height = h; depth = d; } Box() { width = 1; height = 1; depth = 1; } Box(double y) { this(y, y, y); } } §this is used to call a constructor from another constructor. §call to this must be first statement in constructor otherwise compile error 31
Information Hiding and Visibility Modifiers • The modifiers public and private designate the accessibility of data members and methods. • If a class component (data member or method) is declared private, client classes cannot access it. • If a class component is declared public, client classes can access it. • Internal details of a class are declared private and hidden from the clients. This is information hiding.
Accessibility Example class Service { public int member. One; private int member. Two; … Service obj = new Service(); public void do. One() { obj. member. One = 10; … obj. member. Two = 20; } private void do. Two() { obj. do. One(); … } obj. do. Two(); } … Client Service Chapter 4 - 33
Data Members Should Be private • Data members are the implementation details of the class, so they should be invisible to the clients. Declare them private. • Exception: Constants can (should) be declared public if they are meant to be used directly by the outside methods.
Variables Member Variables storing the state of the object Defined outside methods Instance Variables (Non-static Fields) Local Variables in a method Class Variables (static Fields) Instance Variables Local Variables Parameters(arguments) Variables in method declaration class Bicycle Class variable { int speed; static int number. Of. Bicycles; void speed. Up(int increment) { speed += increment; argument } void caluclate. Distance(String S) { int x; …………… } static void m(){…. } } 35
Variables Initialization Member variables that are declared but not initialized will be set to a default by the compiler Data Type Default Value byte 0 short 0 int 0 long 0 L float 0. 0 f double 0. 0 d char 'u 0000' String (or any object refrence) null boolean false 36
Accessing an Object's instance variables and Methods class Test { public static void main (String [] arg) { A a 1=new A(); a 1. x=7; a 1. m 1(); A a 2=new A(); a 2. x=10; class A { public int x; public int y; public void m 1(){ y=9; m 2(); } public void m 2(){ } } a 1, a 2 are of reference data type Rules : x=7 y=9 a 1 x=10 y=0 a 2 ØInstance variable of object are accessed from another class by : object. Name. variable. Name Øinstance methods are accessed from another class by : object. Name. method. Name(argument) ØInside same class , members can be called with their names only 37
Example : Accessing members of class Circle{ public int radius; public double area; public void set. Area() { this. area=3. 14*(this. radius); //area=3. 14*radius; } Circle() { } Circle(int r){ this. radius=r; //radius=r; } } c 1 class Test { public static void main (String [] arg) { Circle c 1=new Circle(); c 1. radius=5; c 1. set. Area(); System. out. println(c 1. area); Circle c 2=new Circle(8); c 2. set. Area(); System. out. println(c 2. area); } } radius=5 radius=8 area=3. 14*5*5 area=3. 14*8*8 c 2 Rule : ØInstance variables in instance methods are always related to the calling object, JAVA add this. before each of them 38
Example : Accessing members of class Bank. Account Class Bank. Account public class Bank. Account { int account. Num=0; float account. Balance=0; public Bank. Account( ) {} public Bank. Account(int account. Number, float balance) { this. account. Num=account. Number; this. account. Balance=balance; } void set. Account. Number(int num) { this. account. Num = num; } void withdraw(float amount) { this. account. Balance = this. account. Balance -amount; } void deposit (float amount) { this. account. Balance = this. account. Balance + amount; } } Class Bank public class Bank { public static void main (String [] arg) { Bank. Account account 1=new Bank. Account(); account 1. set. Account. Number(456); account 1. deposit(1000); Bank. Account account 2=new Bank. Account(590, 200); } } 39
Calling Methods of the Same Class • So far, we have been calling a method of another class (object). • It is possible to call method of a class from another method of the same class. – in this case, we simply refer to a method without dot notation Chapter 4 - 40
Instance Variable Hiding when a local variable has the same name as an instance variable, the local variable hides the instance variable. class A{ int i=20; int j=10; void m() { int i=5; System. out. println("i="+i); //prints 5 } } class Test { public static void main(String [] arg) { A a=new A(); a. m(); } class A { int i=20; int j=10; void m() { int i=5; System. out. println("i="+this. i); //prints 20 } } 41
The this Keyword • this is always a reference to current object, you must use this to overcome local variable hiding A redundant use of this. class Box{ double width ; double height ; double depth ; Box(double w, double h, double d) { this. width = w; this. height = h; this. depth = d; } void increment. Width() { this. width++; } } A mandatory use of this. class Box{ double width ; double height ; double depth ; int i; Box(double width , double height, double depth) { this. width = width; this. height = height; this. depth = depth; } //overcome instance variable hiding void m 1(){ int i=7; this. i=10; } } void m(double width){ this. width=width; }} 42
Array of Objects Arrays can hold a certain type of objects class Bank. Account int account. Num; int account. Balance; String customer. Name; Bank. Account(int num, int balance, String name) { account. Num=num; account. Balance=balance; customer. Name=name; } Bank. Account() { }} class Test{ Public static void main (String [] arg){ Bank. Account [] accounts=new Bank. Account[3]; accounts[0]=new Bank. Account(); //initialization accounts[1]=new Bank. Account(223, 1000, ”Ahmed”); }} null accounts accont. Num=223 account. Balance=1000 customer. Name=“Ahmed” accont. Num=0 account. Balance=0 customer. Name=null accounts[2] accounts[1] accounts[ 0] 43
Example : Class Employee • Design a class Employee that encapsulate the concept of Employee. • Each employee has a first name and a last name and a boolean variable (hired) representing whether the employee is hired or not. • 2 variables exist to store the total number of employees (total. Count)and total number of hired employees(hired. Count). • Each employee is constructed using his first name and last name. §Class employee has the following methods: §accessor methods for its member variables. § method get. AJob () : make an unhired employee hired and increment hired count. § method loose. AJob() : make a hired employee not hired and decrement hired count. In UML static member are denoted by being underlined. 44
public class Employee { private String first. Name; private String last. Name; private static int total. Count ; private static int hired. Count ; private boolean hired; public Employee( String first, String last ) { first. Name = first; last. Name = last; total. Count++; } public void get. AJob() { if(hired) return; hired=true; hired. Count++; } public void loose. AJob() { if(!hired) return; hired=false; hired. Count--; } public String get. First. Name() { return first. Name; } public String get. Last. Name() { return last. Name; } public boolean is. Hired() { return hired; } public static int get. Total. Count() { return total. Count; } } public static int get. Hired. Count() { return hired. Count; } 45
public class Test. Employee { public static void main (String [] arg) { System. out. println("Total number of Employees : "+Employee. get. Total. Count()); System. out. println("Total number of hired Employees : " +Employee. get. Hired. Count()); Employee emp 1=new Employee("Ahmed", "Aly"); Employee emp 2=new Employee("Mohamed", "Mansour"); Employee emp 3=new Employee("Fathi", "Ahmed"); System. out. println("Total number of Employees "+Employee. get. Total. Count()); System. out. println("Total number of hired Employees : " +Employee. get. Hired. Count()); emp 1. get. AJob(); emp 2. get. AJob(); System. out. println("Total number of hired Employees : " +Employee. get. Hired. Count()); emp 2. loose. AJob(); System. out. println("Total number of hired Employees : " +Employee. get. Hired. Count()); } 46
The Calculator
JAVA Naming Conventions Identifier Type Rules for Naming Examples Class names should be nouns, in mixed case with the first letter of each internal word capitalized. class Bank. Accounts Methods should be verbs, in mixed case with the first letter lowercase, with the first letter of each internal word capitalized. run() run. Fast() Variables ØNouns in mixed case with a lowercase first letter. Internal words start with capital letters. ØVariable names should be short yet meaningful. ØOne-character variable names should be avoided except for temporary “throwaway” variables. ØCommon names for temporary variables are i, j, k, m, and n for integers; c, d, and e for characters. int i; float my. Width; Constants Nouns all uppercase with words separated by underscore. (”_“) int MIN_WIDTH = 4 Package Noun, lowercase package util; 48
Example • Create rectangle class that consists of the length and width with methods to initialize the members, calculate the perimeter of the rectangle, and calculate the area of the rectangle. 49
Example • Write a 12 -hour clock program that declares a clock class to store hours, minutes, seconds, A. M. and P. M. provide methods to perform the following tasks: – Set hours, minutes, seconds to 00: 00 by default – Initialize hours, minutes, seconds, A. M. and P. M. from user entries – Allow the clock to tick by advancing the seconds by one and at the same time correcting the hours and minutes for a 12 -hour clock value of AM or PM – Display the time in hours: minutes: seconds AM / PM format 50
• Construct C# console application to solve the following problem. A football team plays n games per year in its league. Given n and the scores of all of the games the team played this year (both the team’s score and its opponent’s score for each game), compute the team’s margin of victory in the games that it played (win = 3, tied = 1 and ignore lost). 51
• Create a class Employee that should contain an instance variables Birthday, Startday, first. Name and Last. Name. Members’ startday and birthday are references to Date object which contains instance variables month, day and year. Employee class provides two constructors: one that takes no arguments and another that takes necessary parameters, and it provides member methods: setting date (in class Date) and display data which use message box to show the Employee information (in class Employee). 52
- Slides: 52