Presentation is loading. Please wait.

Presentation is loading. Please wait.

Object- Oriented Programming (CS243) Dr Walid M. Aly lec4 1 Dr Walid M. Aly 1 Lecture 4 Object- Oriented Programming (CS243) Group home page:

Similar presentations


Presentation on theme: "Object- Oriented Programming (CS243) Dr Walid M. Aly lec4 1 Dr Walid M. Aly 1 Lecture 4 Object- Oriented Programming (CS243) Group home page:"— Presentation transcript:

1 Object- Oriented Programming (CS243) Dr Walid M. Aly lec4 1 Dr Walid M. Aly 1 Lecture 4 Object- Oriented Programming (CS243) Group home page: http://groups.yahoo.com/group/JAVA-CS243/ Defining your own classes

2 Object- Oriented Programming (CS243) Dr Walid M. Aly lec4 2 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.

3 Object- Oriented Programming (CS243) Dr Walid M. Aly lec4 3 3 Banking System Class Employee Class Manager Class BankAccount Class CreditCard Student Registration System Class Student Class Lecturer Class Course Class ClassRoom Voting System Class Voting Class Citizen Class vote Class Candidate Library System Class Book Class LibraryMember Class Employee Example : classes in different systems

4 Object- Oriented Programming (CS243) Dr Walid M. Aly lec4 4 4 class className { } class className { } Variables describing state Methods describing behavior class Student { String name; double GPA; Int regidterationNumber; ………………….. void registerUnit() { ………………… } void payFees(){……} } class Student { String name; double GPA; Int regidterationNumber; ………………….. void registerUnit() { ………………… } void payFees(){……} } Student object 1 name =Ahmed Aly registration number=245245 GPA=3.2 register a unit Student object 2 name =Mohamed Fathi registration number=34345 GPA=2.2 payFees

5 Object- Oriented Programming (CS243) Dr Walid M. Aly lec4 5 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. 5 Objects & classes Radio might have states (on, off, current volume, current station) and behavior (turn on, turn off, increase volume, decrease volume, seek, scan, and tune). Radio

6 Object- Oriented Programming (CS243) Dr Walid M. Aly lec4 6 6 Example :Class Radio public class Radio{ int volume; String station; boolean powerStatus; public void increaseVolume(){ volume++; } public void decreaseVolume(){ volume--; } public void changeStation(String newStation){ station=newStation; } public void turnOn(){ volume=3; powerStatus=true; } public void turnOff(){ volume=0; powerStatus=false; } } volume =4 station=“Negoom FM” Powerstatus=true Radio object1 volume =7 station=“Quran” Powerstatus=true Radio object2 volume =0 station=“FM” Powerstatus=false Radio object3 volume =3 station=“FM” Powerstatus=true Turn On

7 Object- Oriented Programming (CS243) Dr Walid M. Aly lec4 7 class { } Template for Class Definition Import Statements Class Comment Class Name Data Members Methods (incl. Constructor) Methods (incl. Constructor) A class will have variables, constructors and methods. All these are known as class members

8 Object- Oriented Programming (CS243) Dr Walid M. Aly lec4 8 The Definition of the Bicycle Class class Bicycle { // Data Member private String ownerName; //Constructor: Initialzes the data member public Bicycle( ) { ownerName = "Unknown"; } //Returns the name of this bicycle's owner public String getOwnerName( ) { return ownerName; } //Assigns the name of this bicycle's owner public void setOwnerName(String name) { ownerName = name; }

9 Object- Oriented Programming (CS243) Dr Walid M. Aly lec4 9 Chapter 4 - 9 Data Member Declaration ; private String ownerName ; Modifiers Data Type 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”

10 Object- Oriented Programming (CS243) Dr Walid M. Aly lec4 10 Chapter 4 - 10 Method Declaration ( ){ } public void setOwnerName ( String name ) { ownerName = name; } Statements Modifier Return Type Method Name Parameter  Class members can be declared with access modifier as public or protected or private.  the default access modifier is “ package”

11 Object- Oriented Programming (CS243) Dr Walid M. Aly lec4 11 Constructor A constructor is a special method that is executed when a new instance of the class is created. public ( ){ } public Bicycle ( ) { ownerName = "Unassigned"; } Statements Modifier Class Name Parameter

12 Object- Oriented Programming (CS243) Dr Walid M. Aly lec4 12 Constructors….. 12  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 findArea() { // } class Circle { double radius=0 ; public Circle() { } public Circle (double r) { radius=r; } public double findArea() { // } multiple constructors with the same name but different signatures can exist.(overloading)

13 Object- Oriented Programming (CS243) Dr Walid M. Aly lec4 13 class Circle { double radius=0 ; public Circle() { } public Circle (double r) { radius=r; } public double findArea() { return radius * radius * 3.14; } class Circle { double radius=0 ; public Circle() { } public Circle (double r) { radius=r; } public double findArea() { return radius * radius * 3.14; } } class Test{ public static void main (String [] arg) { Circle c1; c1=new Circle(); Circle c2= new Circle(); Circle c3= new Circle(5.1); } class Test{ public static void main (String [] arg) { Circle c1; c1=new Circle(); Circle c2= new Circle(); Circle c3= new Circle(5.1); } 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 ClassName(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. radius=0 radius=5.1 c1 c2c3 c1,c2,c3 are reference data types

14 Object- Oriented Programming (CS243) Dr Walid M. Aly lec4 14 Revisiting the Bicycle Class class Bicycle { // Data Member private String ownerName; //Constructor: Initialzes the data member public Bicycle( ) { ownerName = "Unknown"; } //Returns the name of this bicycle's owner public String getOwnerName( ) { return ownerName; } //Assigns the name of this bicycle's owner public void setOwnerName(String name) { ownerName = name; }

15 Object- Oriented Programming (CS243) Dr Walid M. Aly lec4 15 Using the Bicycle Class class BicycleRegistration { public static void main(String[] args) { Bicycle bike1, bike2; String owner1, owner2; bike1 = new Bicycle( ); //Create and assign values to bike1 bike1.setOwnerName("Adam Smith"); bike2 = new Bicycle( ); //Create and assign values to bike2 bike2.setOwnerName("Ben Jones"); owner1 = bike1.getOwnerName( ); //Output the information owner2 = bike2.getOwnerName( ); System.out.println(owner1 + " owns a bicycle."); System.out.println(owner2 + " also owns a bicycle."); }

16 Object- Oriented Programming (CS243) Dr Walid M. Aly lec4 16 Chapter 4 - 16 Multiple Instances Once the Bicycle class is defined, we can create multiple instances. Bicycle bike1, bike2; bike1bike2 : Bicycle ownerName : Bicycle ownerName “Adam Smith” “Ben Jones” bike1 = new Bicycle( ); bike1.setOwnerName("Adam Smith"); bike2 = new Bicycle( ); bike2.setOwnerName("Ben Jones"); Sample Code

17 Object- Oriented Programming (CS243) Dr Walid M. Aly lec4 17 Example :Adding constructors to class Radio 17 public class Radio{ int volume; String station; boolean powerStatus; public Radio() { volume=3; } public Radio(int startVolume) { volume= startVolume; } public void increaseVolume(){ volume++; } public void decreaseVolume(){ volume--; } public void changeStation(String newStation){ station=newStation;} public void turnOn(){ powerStatus=true; } public void turnOff(){ volume=0; powerStatus=false; } class Test { public static void main (String [] args) { Radio radio1=new Radio(); radio1.turnOn(); radio1.increaseVolume(); Radio radio2=new Radio(5); }

18 Object- Oriented Programming (CS243) Dr Walid M. Aly lec4 18 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; } public class Test { public static void main(String args[]) { Box mybox1 = new Box( ); } 1-compile error 2-Runtime error 3-Compile and run without error What will be the output ? 1-compile error Default constructor should be written

19 Object- Oriented Programming (CS243) Dr Walid M. Aly lec4 19 Example :The Account Class class Account { private String ownerName; private double balance; public Account( ) { ownerName = "Unassigned"; balance = 0.0; } public void add(double amt) { balance = balance + amt; } public void deduct(double amt) { balance = balance - amt; } public double getCurrentBalance( ) { return balance; } public String getOwnerName( ) { return ownerName; } public void setInitialBalance (double bal) { balance = bal; } public void setOwnerName (String name) { ownerName = name; } Page 1Page 2

20 Object- Oriented Programming (CS243) Dr Walid M. Aly lec4 20 Arguments and Parameters An argument is a value we pass to a method class Account {... public void add(double amt) { balance = balance + amt; }... } class Sample { public static void main(String[] arg) { Account acct = new Account();... acct.add(400);... }... } argument parameter A parameter is a placeholder in the called method to hold the value of the passed argument.

21 Object- Oriented Programming (CS243) Dr Walid M. Aly lec4 21 ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 4 - 21 Matching Arguments and Parameters The number or arguments and the parameters must be the same class Demo { public void compute(int i, int j, double x) {... } Demo demo = new Demo( ); int i = 5; int k = 14; demo.compute(i, k, 20); 3 arguments 3 parameters The matched pair must be assignment- compatible (e.g. you cannot pass a double argument to a int parameter) Arguments and parameters are paired left to right Passing Side Receiving Side

22 Object- Oriented Programming (CS243) Dr Walid M. Aly lec4 22 Calling a constructor from another constructor 22 tthis is used to call a constructor from another constructor. ccall to this must be first statement in constructor otherwise compile error 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); } }

23 Object- Oriented Programming (CS243) Dr Walid M. Aly lec4 23 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.

24 Object- Oriented Programming (CS243) Dr Walid M. Aly lec4 24 Chapter 4 - 24 Accessibility Example class Service { public int memberOne; private int memberTwo; public void doOne() { … } private void doTwo() { … } … Service obj = new Service(); obj.memberOne = 10; obj.memberTwo = 20; obj.doOne(); obj.doTwo(); … ClientService

25 Object- Oriented Programming (CS243) Dr Walid M. Aly lec4 25 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.


Download ppt "Object- Oriented Programming (CS243) Dr Walid M. Aly lec4 1 Dr Walid M. Aly 1 Lecture 4 Object- Oriented Programming (CS243) Group home page:"

Similar presentations


Ads by Google