Objects and Classes Eric Roberts CS 106A January 25, 2010.

Slides:



Advertisements
Similar presentations
Programmer-defined classes Part 2. Topics Returning objects from methods The this keyword Overloading methods Class methods Packaging classes Javadoc.
Advertisements

Abstract Data Type Fraction Example
Chapter 4&5 Defining Classes Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Introduction to C Programming
Road Map Introduction to object oriented programming. Classes
ISBN Chapter 11 Abstract Data Types and Encapsulation Concepts.
C# Programming: From Problem Analysis to Program Design1 Creating Your Own Classes C# Programming: From Problem Analysis to Program Design 3rd Edition.
Aalborg Media Lab 23-Jun-15 Inheritance Lecture 10 Chapter 8.
Using Templates Object-Oriented Programming Using C++ Second Edition 11.
Terms and Rules Professor Evan Korth New York University (All rights reserved)
Chapter 10 Classes Continued
Introduction to C Programming
Chapter 6—Objects and Classes The Art and Science of An Introduction to Computer Science ERIC S. ROBERTS Java Objects and Classes C H A P T E R 6 To beautify.
Chapter 6 Objects and Classes. Using the RandomGenerator Class Before you start to write classes of your own, it helps to look more closely at how to.
Introduction to Java Appendix A. Appendix A: Introduction to Java2 Chapter Objectives To understand the essentials of object-oriented programming in Java.
Chapter 6—Objects and Classes The Art and Science of An Introduction to Computer Science ERIC S. ROBERTS Java Objects and Classes C H A P T E R 6 To beautify.
Functions in C++ Eric Roberts CS 106B January 9, 2013.
1 CSCE3193: Programming Paradigms Nilanjan Banerjee Programming Paradigms University of Arkansas Fayetteville, AR
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
COSC 1P03 Data Structures and Abstraction 4.1 Abstract Data Types The advantage of a bad memory is that one enjoys several times the same good things for.
© The McGraw-Hill Companies, 2006 Chapter 4 Implementing methods.
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.
CSCI-383 Object-Oriented Programming & Design Lecture 13.
Class Example - Rationals Rational numbers are represented by the ratio of two integers, a numerator and a denominator, e.g., 2/3. This is opposed to irrational.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 2 Chapter 2 - Introduction to C Programming.
More on Hierarchies 1. When an object of a subclass is instantiated, is memory allocated for only the data members of the subclass or also for the members.
Chapter 6—Objects and Classes The Art and Science of An Introduction to Computer Science ERIC S. ROBERTS Java Objects and Classes C H A P T E R 6 To beautify.
Methods in Java. Program Modules in Java  Java programs are written by combining new methods and classes with predefined methods in the Java Application.
Object-Oriented Programming. An object is anything that can be represented by data in a computer’s memory and manipulated by a computer program.
CSSE501 Object-Oriented Development. Chapter 4: Classes and Methods  Chapters 4 and 5 present two sides of OOP: Chapter 4 discusses the static, compile.
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
Chapter 6 Introduction to Defining Classes. Objectives: Design and implement a simple class from user requirements. Organize a program in terms of a view.
Summing Up Object Oriented Design. Four Major Components: Abstraction modeling real-life entities by essential information only Encapsulation clustering.
Chapter 14 Abstract Classes and Interfaces. Abstract Classes An abstract class extracts common features and functionality of a family of objects An abstract.
1 Programming for Engineers in Python Autumn Lecture 6: More Object Oriented Programming.
Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 1 McGraw-Hill/Irwin Chapter 5 Creating Classes.
COP INTERMEDIATE JAVA Designing Classes. Class Template or blueprint for creating objects. Their definition includes the list of properties (fields)
Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and.
Chapter 4&5 Defining Classes Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Chapter 5 Introduction to Defining Classes
Object Oriented Programming
Chapter 7: Class Inheritance F Superclasses and Subclasses F Keywords: super and this F Overriding methods F The Object Class F Modifiers: protected, final.
Object-Oriented Programming © 2013 Goodrich, Tamassia, Goldwasser1Object-Oriented Programming.
Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class.
Methods Methods are how we implement actions – actions that objects can do, or actions that can be done to objects. In Alice, we have methods such as move,
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
Object Oriented programming Instructor: Dr. Essam H. Houssein.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 2 - Introduction to C Programming Outline.
Objects and Classes Eric Roberts CS 106A January 22, 2016.
Data Representation Eric Roberts CS 106A February 10, 2016.
Lecture 5:Interfaces and Abstract Classes Michael Hsu CSULA.
Notices Assn 2 is due tomorrow, 7pm. Moodle quiz next week – written in the lab as before. Everything up to and including today’s lecture: Big Topics are.
Five-Minute Review 1.What is a method? A static method? 2.What is the motivation for having methods? 3.What role do methods serve in expressions? 4.What.
Classes CS 162 (Summer 2009). Parts of a Class Instance Fields Methods.
Lecture 6:Interfaces and Abstract Classes Michael Hsu CSULA.
Chapter 5 Introduction to Defining Classes Fundamentals of Java.
Lecture 5:Interfaces and Abstract Classes
Eric Roberts and Jerry Cain
Five-Minute Review What is a method? A static method?
slides courtesy of Eric Roberts
Five-Minute Review What is a method? A static method?
CS360 Windows Programming
Object-Oriented Programming
OBJECT ORIENTED PROGRAMMING II LECTURE 8 GEORGE KOUTSOGIANNAKIS
slides courtesy of Eric Roberts
CIS 199 Final Review.
Classes, Objects and Methods
Class Example - Rationals
Presentation transcript:

Objects and Classes Eric Roberts CS 106A January 25, 2010

Once upon a time...

The Smalltalk Language In the history of programming languages I outlined earlier, the language most responsible for bringing object-oriented ideas into the United States was Smalltalk, which was developed by a team at Xerox PARC that included a computer scientist named Adele Goldberg, whose Smalltalk-80 book became the major reference work on the language.

A Tale of Two Companies The emergence of modern computing has a lot to do with the history of two companies in Silicon Valley: Xerox and Apple. In 1970, Xerox established the Palo Alto Research Center, which attracted many of the top computer scientists of the day. That lab pioneered many of the fundamental technologies of modern computing such as graphical user interfaces and object- oriented programming long before they became commonplace. When those technologies did appear, it was not from Xerox....

Smalltalk and Steve Jobs (the movie is not included in the web-based show because of copyright restrictions)

Objects and Classes

Review: Objects and Classes An object is a conceptually integrated data collection that encapsulates state and behavior. A class is a template that defines the common structure for all objects of that class. Each object is created as an instance of one particular class, but a class can serve as a template for many instances. Classes form a hierarchy in which subclasses can inherit the behavior of their superclasses. A constructor is a specialized method that acts as a factory for making new instances of a particular class. In Java, a constructor always has the same name as the class and is invoked by using the new keyword.

Thinking About Objects with thanks to Randall Monroe at xkcd.com clientimplementation abstraction boundary I need a bunch of GRect s. acm.graphics GRect GOval GLine GLabel... GRect class location size color fill status fill color acm.graphics GRect GOval GLine GLabel...

Exercise: Random Circles Write a GraphicsProgram that draws a set of ten circles with randomly chosen sizes, positions, and colors, subject to the condition that the entire circle must fit inside the window. RandomCircles

Section Problem: Animating Circles Your first problem for section this week is to modify the code for this problem so that the circles expand gradually into their final positions, one at a time. GrowingCircles

Defining Your Own Classes The standard form of a class definition in Java looks like this: public class name extends superclass { class body } The extends clause on the header line specifies the name of the superclass. If the extends clause is missing, the new class becomes a direct subclass of Object, which is the root of Java’s class hierarchy. The body of a class consists of a set of Java definitions that are generically called entries. The most common entries are constructors, methods, instance variables, and constants. Each public class must be stored in a separate file whose name is the name of the class followed by.java.

Representing Student Information Understanding the structure of a class is easiest in the context of a specific example. The next four slides walk through the definition of a class called Student, which is used to keep track of the following information about a student: –The name of the student –The student’s six-digit identification number –The number of units the student has earned –A flag indicating whether the student has paid all university fees Each of these values is stored in an instance variable of the appropriate type. In keeping with the modern object-oriented convention used throughout both the book and the ACM Java Libraries, these instance variables are declared as private. All access to these values is therefore mediated by methods exported by the Student class.

/** * The Student class keeps track of the following pieces of data * about a student: the student's name, ID number, the number of * units the student has earned toward graduation, and whether * the student is paid up with respect to university bills. * All of this information is entirely private to the class. * Clients can obtain this information only by using the various * methods defined by the class. */ public class Student { /** * Creates a new Student object with the specified name and ID. name The student's name as a String id The student's ID number as an int */ public Student(String name, int id) { studentName = name; studentID = id; } The Student Class This comment describes the class as a whole. The class header defines Student as a direct subclass of Object. This comment describes the constructor. The constructor sets the instance variables. skip code page 1 of 4

/** * The Student class keeps track of the following pieces of data * about a student: the student's name, ID number, the number of * units the student has earned toward graduation, and whether * the student is paid up with respect to university bills. * All of this information is entirely private to the class. * Clients can obtain this information only by using the various * methods defined by the class. */ public class Student { /** * Creates a new Student object with the specified name and ID. name The student's name as a String id The student's ID number as an int */ public Student(String name, int id) { studentName = name; studentID = id; } /** * Gets the name of this student. The name of this student */ public String getName() { return studentName; } /** * Gets the ID number of this student. The ID number of this student */ public int getID() { return studentID; } /** * Sets the number of units earned. units The new number of units earned */ public void setUnits(int units) { unitsEarned = units; } The Student Class These methods retrieve the value of an instance variable and are called getters. Because the student name and ID number are fixed, there are no corresponding setters. This method changes the value of an instance variable and is called a setter. skip code page 2 of 4

/** * Gets the name of this student. The name of this student */ public String getName() { return studentName; } /** * Gets the ID number of this student. The ID number of this student */ public int getID() { return studentID; } /** * Sets the number of units earned. units The new number of units earned */ public void setUnits(int units) { unitsEarned = units; } /** * Gets the number of units earned. The number of units this student has earned */ public int getUnits() { return unitsEarned; } /** * Sets whether the student is paid up. flag The value true or false indicating paid-up status */ public void setPaidUp(boolean flag) { paidUp = flag; } /** * Returns whether the student is paid up. Whether the student is paid up */ public boolean isPaidUp() { return paidUp; } The Student Class Names for getter methods usually begin with the prefix get. The only exception is for getter methods that return a boolean, in which case the name typically begins with is. skip code page 3 of 4

/** * Gets the number of units earned. The number of units this student has earned */ public int getUnits() { return unitsEarned; } /** * Sets whether the student is paid up. flag The value true or false indicating paid-up status */ public void setPaidUp(boolean flag) { paidUp = flag; } /** * Returns whether the student is paid up. Whether the student is paid up */ public boolean isPaidUp() { return paidUp; } /** * Creates a string identifying this student. The string used to display this student */ public String toString() { return studentName + " (#" + studentID + ")"; } /* Public constants */ /** The number of units required for graduation */ public static final int UNITS_TO_GRADUATE = 180; /* Private instance variables */ private String studentName; /* The student's name */ private int studentID; /* The student's ID number */ private int unitsEarned; /* The number of units earned */ private boolean paidUp; /* Whether student is paid up */ } The Student Class The toString method tells Java how to display a value of this class. All of your classes should override toString. Classes often export named constants. These declarations define the instance variables that maintain the internal state of the class. All instance variables used in the text are private. skip code page 4 of 4

Using the Student Class Once you have defined the Student class, you can then use its constructor to create instances of that class. For example, you could use the following code to create two Student objects: Student chosenOne = new Student("Harry Potter", ); Student topStudent = new Student("Hermione Granger", ); You can then use the standard receiver syntax to call methods on these objects. For example, you could set Hermione’s number-of-units field to 263 by writing or get Harry’s full name by calling topStudent.setUnits(263); chosenOne.getName();

Rational Numbers As a more elaborate example of class definition, section 6.4 defines a class called Rational that represents rational numbers, which are simply the quotient of two integers. Rational numbers can be useful in cases in which you need exact calculation with fractions. Even if you use a double, the floating-point number 0.1 is represented internally as an approximation. The rational number 1 / 10 is exact. Rational numbers support the standard arithmetic operations: a b + c d = ad + bc bd a b – c d = ad – bc bd a b x c d = ac a b c d =.. bd ad bc Addition: Subtraction: Multiplication: Division:

Implementing the Rational Class The next five slides show the code for the Rational class along with some brief annotations. As you read through the code, the following features are worth special attention: –The constructors for the class are overloaded. Calling the constructor with no argument creates a Rational initialized to 0, calling it with one argument creates a Rational equal to that integer, and calling it with two arguments creates a fraction. –The constructor makes sure that the number is reduced to lowest terms. Moreover, since these values never change once a new Rational is created, this property will remain in force. –Operations are specified using the receiver syntax. When you apply an operator to two Rational values, one of the operands is the receiver and the other is passed as an argument, as in r1.add(r2)

The this Keyword The implementation of the Rational class makes use of the Java keyword this, which always refers to the current object. The code, however, uses it in two distinct ways: In the first two versions of the constructor, the keyword this is used to invoke one of the other constructors for this class. 1. In the methods that implement the arithmetic operators, this is used to emphasize that a named field comes from this object rather than from one of the other values of that class. 2. The keyword this is also often used to distinguish between an instance variable and a local variable with the same name. If you include this before the variable name, you indicate to the compiler that you mean the instance variable.

/** * The Rational class is used to represent rational numbers, which * are defined to be the quotient of two integers. */ public class Rational { /** Creates a new Rational initialized to zero. */ public Rational() { this(0); } /** * Creates a new Rational from the integer argument. n The initial value */ public Rational(int n) { this(n, 1); } The Rational Class These constructors are overloaded so that there is more than one way to create a Rational value. These two versions invoke the primary constructor by using the keyword this. skip code page 1 of 5

/** * The Rational class is used to represent rational numbers, which * are defined to be the quotient of two integers. */ public class Rational { /** Creates a new Rational initialized to zero. */ public Rational() { this(0); } /** * Creates a new Rational from the integer argument. n The initial value */ public Rational(int n) { this(n, 1); } /** * Creates a new Rational with the value x / y. x The numerator of the rational number y The denominator of the rational number */ public Rational(int x, int y) { int g = gcd(Math.abs(x), Math.abs(y)); num = x / g; den = Math.abs(y) / g; if (y < 0) num = -num; } /** * Adds the rational number r to this one and returns the sum. r The rational number to be added The sum of the current number and r */ public Rational add(Rational r) { return new Rational(this.num * r.den + r.num * this.den, this.den * r.den); } The Rational Class The primary constructor creates a new Rational from the numerator and denominator. The call to gcd ensures that the fraction is reduced to lowest terms. The add method creates a new Rational object using the addition rule. The two rational values appear in this and r. skip code page 2 of 5

/** * Creates a new Rational with the value x / y. x The numerator of the rational number y The denominator of the rational number */ public Rational(int x, int y) { int g = gcd(Math.abs(x), Math.abs(y)); num = x / g; den = Math.abs(y) / g; if (y < 0) num = -num; } /** * Adds the rational number r to this one and returns the sum. r The rational number to be added The sum of the current number and r */ public Rational add(Rational r) { return new Rational(this.num * r.den + r.num * this.den, this.den * r.den); } /** * Subtracts the rational number r from this one. r The rational number to be subtracted The result of subtracting r from the current number */ public Rational subtract(Rational r) { return new Rational(this.num * r.den - r.num * this.den, this.den * r.den); } /** * Multiplies this number by the rational number r. r The rational number used as a multiplier The result of multiplying the current number by r */ public Rational multiply(Rational r) { return new Rational(this.num * r.num, this.den * r.den); } The Rational Class These methods (along with divide on the next page) work just like the add method but use a different formula. Note that these methods do have access to the components of r. skip code page 3 of 5

/** * Subtracts the rational number r from this one. r The rational number to be subtracted The result of subtracting r from the current number */ public Rational subtract(Rational r) { return new Rational(this.num * r.den - r.num * this.den, this.den * r.den); } /** * Multiplies this number by the rational number r. r The rational number used as a multiplier The result of multiplying the current number by r */ public Rational multiply(Rational r) { return new Rational(this.num * r.num, this.den * r.den); } /** * Divides this number by the rational number r. r The rational number used as a divisor The result of dividing the current number by r */ public Rational divide(Rational r) { return new Rational(this.num * r.den, this.den * r.num); } /** * Creates a string representation of this rational number. The string representation of this rational number */ public String toString() { if (den == 1) { return "" + num; } else { return num + "/" + den; } The Rational Class This method converts the Rational number to its string form. If the denominator is 1, the number is displayed as an integer. skip code page 4 of 5

/** * Divides this number by the rational number r. r The rational number used as a divisor The result of dividing the current number by r */ public Rational divide(Rational r) { return new Rational(this.num * r.den, this.den * r.num); } /** * Creates a string representation of this rational number. The string representation of this rational number */ public String toString() { if (den == 1) { return "" + num; } else { return num + "/" + den; } /** * Calculates the greatest common divisor using Euclid's algorithm. x First integer y Second integer The greatest common divisor of x and y */ private int gcd(int x, int y) { int r = x % y; while (r != 0) { x = y; y = r; r = x % y; } return y; } /* Private instance variables */ private int num; /* The numerator of this Rational */ private int den; /* The denominator of this Rational */ } The Rational Class Euclid’s gcd method is declared to be private because it is part of the implementation of this class and is never used outside of it. As always, the instance variables are private to this class. skip code page 5 of 5

Simulating Rational Calculation The next slide works through all the steps in the calculation of a simple program that adds three rational numbers With rational arithmetic, the computation is exact. If you write this same program using variables of type double, the result looks like this: RoundoffExample 1.0/ / /6.0 =

Adding Three Rational Values csumba public void run() { Rational a = new Rational(1, 2); Rational b = new Rational(1, 3); Rational c = new Rational(1, 6); Rational sum = a.add(b).add(c); println(a + " + " + b + " + " + c + " = " + sum); } TestRational temporary result 1/2 + 1/3 + 1/6 = 1 skip simulation public Rational(int x, int y) { int g = gcd(Math.abs(x), Math.abs(y)); num = x / g; den = Math.abs(y) / g; if (y < 0) num = -num; } ygx this num den public Rational(int x, int y) { int g = gcd(Math.abs(x), Math.abs(y)); num = x / g; den = Math.abs(y) / g; if (y < 0) num = -num; } ygx this num den public Rational(int x, int y) { int g = gcd(Math.abs(x), Math.abs(y)); num = x / g; den = Math.abs(y) / g; if (y < 0) num = -num; } ygx this num den public Rational add(Rational r) { return new Rational( this.num * r.den + r.num * this.den, this.den * r.den ); } this num den 1 2 r num den public Rational(int x, int y) { int g = gcd(Math.abs(x), Math.abs(y)); num = x / g; den = Math.abs(y) / g; if (y < 0) num = -num; } ygx this num den public Rational add(Rational r) { return new Rational( this.num * r.den + r.num * this.den, this.den * r.den ); } this num den 5 6 r num den public Rational(int x, int y) { int g = gcd(Math.abs(x), Math.abs(y)); num = x / g; den = Math.abs(y) / g; if (y < 0) num = -num; } ygx this num den csumba public void run() { Rational a = new Rational(1, 2); Rational b = new Rational(1, 3); Rational c = new Rational(1, 6); Rational sum = a.add(b).add(c); println(a + " + " + b + " + " + c + " = " + sum); }

The End