DCS 2133 Object Oriented Programming Defining Your Own Classes Part 2.

Slides:



Advertisements
Similar presentations
Introduction to OOP with Java 4th Ed, C. Thomas Wu
Advertisements

©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Four Defining Your Own Classes.
Core Java Lecture 4-5. What We Will Cover Today What Are Methods Scope and Life Time of Variables Command Line Arguments Use of static keyword in Java.
Programmer-defined classes Part 2. Topics Returning objects from methods The this keyword Overloading methods Class methods Packaging classes Javadoc.
Abstract Data Type Fraction Example
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 4 Defining Your Own Classes.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 7 More on Defining Classes Overloading.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 4 Defining Your Own Classes.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 4 Defining Your Own Classes Part 1.
COMP 110 Introduction to Programming Mr. Joshua Stough October 8, 2007.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 4 Defining Your Own Classes Part 1 Animated.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 7 More on Defining Classes Overloading.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 7 Defining Your Own Classes Part 2.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 4 Defining Your Own Classes.
Chapter 7- 1 Chapter 7 Defining Your Own Classes Part 2.
بسم الله الرحمن الرحيم CPCS203: Programming II. ©The McGraw-Hill Companies, Inc. Permission required for reproduction or display., Modifications by Dr.
Chapter Chapter 4 Defining Your Own Classes Part 1.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 4 Defining Your Own Classes.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 7 User-Defined Methods.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 7 Defining Your Own Classes Part 2.
Programmer-defined classes Part 3. A class for representing Fractions public class Fraction { private int numerator; private int denominator; public Fraction(int.
Develop Instantiable classes (continue). Exam 1 – section 02 Avg = 131 (87%). Max: 148.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Why Programmer-Defined Classes Using just the String,
Defining Your Own Classes Part 3. class { } Template for Class Definition Import Statements Class Comment Class Name Data Members Methods (incl. Constructor)
SE-1010 Dr. Mark L. Hornick 1 Defining Your Own Classes Part 3.
CSM-Java Programming-I Spring,2005 Introduction to Objects and Classes Lesson - 1.
 2003 Prentice Hall, Inc. All rights reserved. 1 Introduction to Classes and Objects Outline Introduction Classes, Objects, Member Functions and Data.
Modular Programming Chapter Value and Reference Parameters t Function declaration: void computesumave(float num1, float num2, float& sum, float&
Writing Classes (Chapter 4)
Data Objects (revisited) Recall that values are stored in data objects, and that each data object holds one value of a particular type. Data objects may.
CSE 1301 Lecture 11 Object Oriented Programming Figures from Lewis, “C# Software Solutions”, Addison Wesley Richard Gesick.
Local Variables A local variable is a variable that is declared within a method declaration. Local variables are accessible only from the method in which.
Modular Programming Chapter Value and Reference Parameters computeSumAve (x, y, sum, mean) ACTUALFORMAL xnum1(input) ynum2(input) sumsum(output)
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
CSE 1302 Lecture 7 Object Oriented Programming Review Richard Gesick.
Java Classes Appendix C © 2015 Pearson Education, Inc., Hoboken, NJ. All rights reserved.
Copyright © 2002, Systems and Computer Engineering, Carleton University a-JavaReview.ppt * Object-Oriented Software Development Unit.
1 Overloading Overloading allows a function or operator to have a different meaning depending on the type of objects it is used on. Examples: operator+
Dr. Salah Hammami KSU-CCIS-CS Ahmad Al-Rjoub CSC 113 King Saud University College of Computer and Information Sciences Department of Computer Science Ahmad.
ECE122 Feb. 22, Any question on Vehicle sample code?
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Chapter 7 Defining Your Own Classes Part 2 Animated Version.
Java™ How to Program, 10/e © Copyright by Pearson Education, Inc. All Rights Reserved.
Methods: A Deeper Look. Template for Class Definition public class { } A.Import Statement B.Class Comments C.Class Name D.Data members E.Methods (inc.
COP INTERMEDIATE JAVA Designing Classes. Class Template or blueprint for creating objects. Their definition includes the list of properties (fields)
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 7 Defining Your Own Classes Part 2 (adapted.
Object- Oriented Programming (CS243) Dr Walid M. Aly lec4 1 Dr Walid M. Aly 1 Lecture 4 Object- Oriented Programming (CS243) Group home page:
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Chapter 7 Defining Your Own Classes Part 2.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Chapter 4 Defining Your Own Classes Part 1 Animated Version.
Java & C++ Comparisons How important are classes and objects?? What mechanisms exist for input and output?? Are references and pointers the same thing??
 Static  Example for Static Field  Example for Static Method  Math class methods  Casting  Scope of Declaration  Method Overloading  Constructor.
Classes - Intermediate
 2005 Pearson Education, Inc. All rights reserved. 1 Classes and Objects: A Deeper Look.
Chapter 3: Classes and Objects Java Programming FROM THE BEGINNING Copyright © 2000 W. W. Norton & Company. All rights reserved. 1 Chapter 3 Classes and.
© 2004 Pearson Addison-Wesley. All rights reserved April 10, 2006 Inheritance (part 2) ComS 207: Programming I (in Java) Iowa State University, SPRING.
Building Programs from Existing Information Solutions for programs often can be developed from previously solved problems. Data requirements and solution.
© 2004 Pearson Addison-Wesley. All rights reserved November 14, 2007 Inheritance (part 2) ComS 207: Programming I (in Java) Iowa State University, FALL.
Chapter 7- Defining Your Own Classes Part 2 : Objectives After you have read and studied this chapter, you should be able to –Describe how objects are.
Object-Oriented Design Chapter 7 1. Objectives You will be able to Use the this reference in a Java program. Use the static modifier for member variables.
Functions + Overloading + Scope
More About Objects and Methods
User-Written Functions
Java Primer 1: Types, Classes and Operators
Object Oriented Programming
Inheritance April 7, 2006 ComS 207: Programming I (in Java)
Defining Your Own Classes
Introduction to Object-Oriented Programming with Java--Wu
Class rational part2.
Corresponds with Chapter 5
SPL – PS3 C++ Classes.
Chapter 7 Defining Your Own Classes Part 2
Presentation transcript:

DCS 2133 Object Oriented Programming Defining Your Own Classes Part 2

DCS 2133 Object Oriented Programming Objectives Describe how objects are returned from methods Describe how the reserved word this is used Define overloaded methods and constructors Define class methods and variables Describe how the arguments are passed to the parameters using the pass-by-value scheme Organize classes into a package

DCS 2133 Object Oriented Programming Returning an Object from a Method As we can return a primitive data value from a method, we can return an object from a method also. We return an object from a method, we are actually returning a reference (or an address) of an object. –This means we are not returning a copy of an object, but only the reference of this object

DCS 2133 Object Oriented Programming public class Fraction { private int numerator; private int denominator; public Fraction(int num, int denom) { setNumerator(num); setDenominator(denom); } public int getDenominator( ) { return denominator; } public int getNumerator( ) { return numerator; } public void setDenominator(int denom) { if (denom == 0) { //Fatal error System.err.println("Fatal Error"); System.exit(1); } denominator = denom; } public void setNumerator(int num) { numerator = num; }

DCS 2133 Object Oriented Programming Sample Object-Returning Method Here's a sample method that returns an object: public Fraction simplify( ) { int num = getNumerator(); int denom = getDenominator(); int gcd = gcd(num, denom); Fraction simp; simp = new Fraction(num/gcd, denom/gcd); return simp; } Return type indicates the class of an object we're returning from the method. Return an instance of the Fraction class

DCS 2133 Object Oriented Programming A Sample Call to simplify f1 = new Fraction(24, 36); f2 = f1.simplify(); public Fraction simplify( ) { int num = getNumerator(); int denom = getDenominator(); int gcd = gcd(num, denom); Fraction simp = new Fraction(num/gcd, denom/gcd); return simp; } f1 : Fraction numerator denominator f2 simp : Fraction numerator denominator 3 2

DCS 2133 Object Oriented Programming A Sample Call to simplify (cont'd) public Fraction simplify( ) { int num = getNumerator(); int denom = getDenominator(); int gcd = gcd(num, denom); Fraction simp = new Fraction(num/gcd, denom/gcd); return simp; } f1 = new Fraction(24, 26); : Fraction numerator denominator 3 2 f2 = f1.simplify(); f1 : Fraction numerator denominator f2 simp : Fraction numerator denominator 3 2 The value of simp, which is a reference, is returned and assigned to f2.

DCS 2133 Object Oriented Programming Reserved Word this The reserved word this is called a self-referencing pointer because it refers to an object from the object's method. : Object this The reserved word this can be used in different ways.

DCS 2133 Object Oriented Programming The Use of this in the add Method public Fraction add(Fraction frac) { int a, b, c, d; a = this.getNumerator(); //get the receiving b = this.getDenominator(); //object's num and denom c = frac.getNumerator(); //get frac's num d = frac.getDenominator(); //and denom Fraction sum = new Fraction(a*d + b*c, b*d); return sum; } Fraction f1,f2,f3; f1 = new Fraction(1, 2); f2 = new Fraction(1, 4); f3 = f1.add(f2); // returning a reference to object System.out.println(“Sum of” + f1.toString() + “ and ” + f2.toString() + “ and ” + f3.toString();

DCS 2133 Object Oriented Programming f3 = f1.add(f2) Because f1 is the receiving object (we're calling f1's method), so the reserved word this is referring to f1.

DCS 2133 Object Oriented Programming f3 = f2.add(f1) This time, we're calling f2's method, so the reserved word this is referring to f2.

DCS 2133 Object Oriented Programming Using this to Refer to Data Members In the previous example, we showed the use of this to call a method of a receiving object. It can be used to refer to a data member as well. class MusicCD { int age; public void setAge(int val) { int age; this.age = val; }... }

DCS 2133 Object Oriented Programming Another example… class MusicCD { private String artist; private String title; private String id; public MusicCD(String artist,String title) { this.artist = artist; this.title = title; id = artist.substring(0,2) + “-” + title.substring(0,9); }... }

DCS 2133 Object Oriented Programming Remember… Rules for associating an identifier to a local variable, a parameter and a data member. 1.If there’s a matching local variable declaration or a parameter, then the identifier refers to the local variable or the parameter. 2.Otherwise, if there’s matching data member declaration, then the identifier refers to the data member. 3.Otherwise, it is an error because there’s no matching declaration.

DCS 2133 Object Oriented Programming Overloaded Methods Two or more methods that have same name within the same class. A method's name and number and type of parameters is called the signature Methods can share the same name as long as –they have a different number of parameters (Rule 1) or –their parameters are of different data types when the number of parameters is the same (Rule 2) public void myMethod(int x, int y) {... } public void myMethod(int x) {... } Rule 1 public void myMethod(double x) {... } public void myMethod(int x) {... } Rule 2

DCS 2133 Object Oriented Programming Overloaded Constructor Defining multiple constructors for a class gives the client programmer flexibility in creating objects. The same rules apply for overloaded constructors –this is how we can define more than one constructor to a class public Person( ) {... } public Person(int age) {... } Rule 1 public Pet(int age) {... } public Pet(String name) {... } Rule 2

DCS 2133 Object Oriented Programming Notice that the difference in the return type alone is not enough to overload the methods. For example, the following declaration is invalid public double convert(int num) {... } public float convert(int num) {... }

DCS 2133 Object Oriented Programming Overloaded constructor…cont Example of overloaded constructors. In here, constructors can call other class methods. public Fraction( ) { setNumerator(0); setDenominator(1); } //creates 0/1 public Fraction(int number) { setNumerator(number); setDenominator(1); } //creates number/1 public Fraction(Fraction frac) { setNumerator(frac.getNumerator(); setDenominator(frac.getDenominator()); } //creates copy contructors public Fraction(int num, int denom) { setNumerator(num); setDenominator(denom); }

DCS 2133 Object Oriented Programming Constructors and this To call a constructor from another constructor of the same class, we use the reserved word this. public Fraction( ) { this(0. 1); } public Fraction(int number) { this(number, 1); } public Fraction(Fraction frac) { this(frac.getNumerator(), frac.getDenominator()); } public Fraction(int num, int denom) { setNumerator(num); setDenominator(denom); }

DCS 2133 Object Oriented Programming Without using the reserved word this, we need to define the four constructors like in previous slide (it forces us to repeat the same code): public Fraction( ) { setNumerator(0); setDenominator(1); } public Fraction(int number) { setNumerator(number); setDenominator(1); } public Fraction(Fraction frac) { setNumerator(frac.getNumerator()); setDenominator(frac.getDenominator()); } public Fraction(int num, int denom) { setNumerator(num); setDenominator(denom); }

DCS 2133 Object Oriented Programming Class Methods We use the reserved word static to define a class method. Applies to the class as a whole instead of a specific object of the class Call a static method by using the method call: ClassName. methodName ( arguments ) public static int gcd(int m, int n) { //the code implementing the Euclidean algorithm } public static Fraction min(Fraction f1, Fraction f2) { //convert to decimals and then compare }

DCS 2133 Object Oriented Programming Call-by-Value Parameter Passing When a method is called, –the value of the argument is passed to the matching parameter, and –separate memory space is allocated to store this value. This way of passing the value of arguments is called a pass-by-value or call-by-value scheme. Since separate memory space is allocated for each parameter during the execution of the method, –the parameter is local to the method, and therefore –changes made to the parameter will not affect the value of the corresponding argument.

DCS 2133 Object Oriented Programming Call-by-Value Example class Tester { public void myMethod(int one, double two ) { one = 25; two = 35.4; } Tester tester; int x, y; tester = new Tester(); x = 10; y = 20; tester.myMethod(x, y); System.out.println(x + " " + y); produces 10 20

DCS 2133 Object Oriented Programming Memory Allocation for Parameters

DCS 2133 Object Oriented Programming Memory Allocation for Parameters (cont'd)

DCS 2133 Object Oriented Programming Parameter Passing: Key Points 1. Arguments are passed to a method by using the pass-by- value scheme. 2. Arguments are matched to the parameters from left to right.The data type of an argument must be assignment- compatible with the data type of the matching parameter. 3. The number of arguments in the method call must match the number of parameters in the method definition. 4. Parameters and arguments do not have to have the same name. 5. Local copies, which are distinct from arguments,are created even if the parameters and arguments share the same name. 6. Parameters are input to a method, and they are local to the method.Changes made to the parameters will not affect the value of corresponding arguments.

DCS 2133 Object Oriented Programming Organizing Classes into a Package For a class A to use class B, their bytecode files must be located in the same directory. –This is not practical if we want to reuse programmer- defined classes in many different programs The correct way to reuse programmer-defined classes from many different programs is to place reusable classes in a package. A package is a Java class library.

DCS 2133 Object Oriented Programming Packages – help manage large software system Can contain classes and sub packages Can group classes into a package by semantic similarity Organizing Classes into a Package

DCS 2133 Object Oriented Programming Syntax package ; OR package. ; EXAMPLE 1: package bank; public class Account { private String ownerName; private double balance; //the rest of program } - ownerName - balance + Account (String, double) + add (double) + deduct (double) + getCurrentBalance() + getOwnerName() + setOwnerName(String) Account bank Organizing Classes into a Package

DCS 2133 Object Oriented Programming EXAMPLE 2: // class 1 package bank; class Bicycle { private String owner; private String color //the rest of program } // class 2 package bank; public class Account { private String ownerName; private double balance; //the rest of program } - ownerName - balance + Account (String, double) + add (double) + deduct (double) + getCurrentBalance() + getOwnerName() + setOwnerName(String) Account bank - owner - color + Bicycle (String) + getOwnerO + setOwner() Bicycle 2 classes in a package Organizing Classes into a Package

DCS 2133 Object Oriented Programming EXAMPLE 3: package shipping.domain; class Company { //the rest of program } package shipping.domain; class Vehicle { //the rest of program } package shipping.domain; class Truck{ //the rest of program } package shipping.domain; class RiverRange { //the rest of program } shipping domain CompanyVehicle TruckRiverBarge GUI reports own 0..* classes and packages in a package package shipping.reports; class ZZZZZ { //the rest of program } package shipping.GUI; class ZZZZZ { //the rest of program } Organizing Classes into a Package

DCS 2133 Object Oriented Programming Creating a Package The following steps illustrate the process of creating a package name myutil that includes the Fraction class. 1. Include the statement package myutil; as the first statement of the source file for the Fraction class. 2. The class declaration must include the visibility modifier public as public class Fraction {... } 3. Create a folder named myutil, the same name as the package name. In Java, the package must have a one-to-one correspondence with the folder. 4. Place the modified Fraction class into the myutil folder and compile it. 5. Modify the CLASSPATH environment variable to include the folder that contains the myutil folder.

DCS 2133 Object Oriented Programming The end