MIT AITI 2003 Lecture 8 Class And Object II.

Slides:



Advertisements
Similar presentations
Chapter 1 Object-Oriented Concepts. A class consists of variables called fields together with functions called methods that act on those fields.
Advertisements

IMPLEMENTING CLASSES Chapter 3. Black Box  Something that magically does its thing!  You know what it does but not how.  You really don’t care how.
Objectives Introduction to Inheritance and Composition (Subclasses and SuperClasses) Overriding (and extending), and inheriting methods and constructors.
1 CS 171: Introduction to Computer Science II Review: OO, Inheritance, and Libraries Ymir Vigfusson.
CS2200 Software Development Lecture: Object class A. O’Riordan, 2008.
Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 8: Classes and Objects.
Inheritance Part II. Lecture Objectives To learn about inheritance To understand how to inherit and override superclass methods To be able to invoke superclass.
GETTING INPUT Simple I/O. Simple Input Scanner scan = new Scanner(System.in); System.out.println("Enter your name"); String name = scan.nextLine(); System.out.println("Enter.
(c) University of Washington04-1 CSC 143 Java Inheritance Example (Review)
MIT AITI 2002 Abstract Classes, Interfaces. Abstract Classes What is an abstract class? An abstract class is a class in which one or more methods is declared,
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
Object Oriented Programming Concepts OOP – reasoning about a program as a set of objects rather than as a set of actions Object – a programming entity.
1 Object-Oriented Software Engineering CS Interfaces Interfaces are contracts Contracts between software groups Defines how software interacts with.
COP INTERMEDIATE JAVA Designing Classes. Class Template or blueprint for creating objects. Their definition includes the list of properties (fields)
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.
Inheritance - Polymorphism ITI 1121 Nour El Kadri.
Copyright 2010 by Pearson Education Building Java Programs Chapter 8 Lecture 8-2: Object Behavior (Methods) and Constructors, Encapsulation, this reading:
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
Inheritance (Part 5) Odds and ends 1. Static Methods and Inheritance  there is a significant difference between calling a static method and calling a.
Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 1 McGraw-Hill/Irwin Chapter 5 Creating Classes.
Introduction to Java Chapter 7 - Classes & Object-oriented Programming1 Chapter 7 Classes and Object-Oriented Programming.
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 5 Objects and Classes Inheritance. Solution Assignments 3 & 4 Review in class…..
Chapter 4&5 Defining Classes Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Programming With Java ICS201 University Of Ha’il1 Chapter 7 Inheritance.
CS305j Introduction to Computing Classes II 1 Topic 24 Classes Part II "Object-oriented programming as it emerged in Simula 67 allows software structure.
Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
Classes, Interfaces and Packages
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
1 Object-Oriented Programming Inheritance. 2 Superclasses and Subclasses Superclasses and Subclasses  Superclasses and subclasses Object of one class.
POLYMORPHISM Chapter 6. Chapter Polymorphism  Polymorphism concept  Abstract classes and methods  Method overriding  Concrete sub classes and.
5.1 Basics of defining and using classes A review of class and object definitions A class is a template or blueprint for an object A class defines.
CS 116 OBJECT ORIENTED PROGRAMMING II LECTURE 6 Acknowledgement: Contains materials provided by George Koutsogiannakis and Matt Bauer.
COMPUTER SCIENCE & TECHNOLOGY DEGREE PROGRAMME FACULTY OF SCIENCE & TECHNOLOGY UNIVERSITY OF UVA WELLASSA ‏ Properties of Object Oriented Programming.
Copyright 2010 by Pearson Education Building Java Programs Chapter 8 Lecture 8-3: Constructors; Encapsulation reading: self-checks: #13-18,
Geoff Holmes and Bernhard Pfahringer COMP206-08S General Programming 2.
Java Programming: Guided Learning with Early Objects Chapter 9 Inheritance and Polymorphism.
Copyright 2010 by Pearson Education Building Java Programs Chapter 8 Lecture 8-2: Object Behavior (Methods) and Constructors, Encapsulation, this reading:
Objects and Classes. F OO Programming Concepts F Creating Objects and Object Reference Variables –Differences between primitive data type and object type.
Topic: Classes and Objects
Object-Oriented Concepts
Classes and Objects Introduced
Data Structures and Algorithms revision
Chapter 11 Inheritance and Polymorphism
Inheritance and Polymorphism
Inheritance "Question: What is the object oriented way of getting rich? Answer: Inheritance.“ “Inheritance is new code that reuses old code. Polymorphism.
Computer Science II Exam 1 Review.
Subroutines Idea: useful code can be saved and re-used, with different data values Example: Our function to find the largest element of an array might.
Overloading and Constructors
Chapter 9 Inheritance and Polymorphism
null, true, and false are also reserved.
OBJECT ORIENTED PROGRAMMING II LECTURE 8 GEORGE KOUTSOGIANNAKIS
Java Programming Language
Object initialization: constructors
Building Java Programs
Building Java Programs
Building Java Programs
Object-Oriented Programming: Classes, Inheritance, and Interfaces
Building Java Programs
Dr. R Z Khan Handout-3 Classes
Object-Oriented Programming: Classes, Inheritance, and Interfaces
Building Java Programs
CMPE212 – Reminders Assignment 2 due next Friday.
Chapter 11 Inheritance and Encapsulation and Polymorphism
Overloading Each method has a signature: its name together with the number and types of its parameters Methods Signatures String toString()
Building Java Programs
Introduction to Computer Science and Object-Oriented Programming
Presentation transcript:

MIT AITI 2003 Lecture 8 Class And Object II

Objective Represent a Point object The state includes point coordinates, a point label, etc. The “behavior” of a point: Finding the x, y properties, finding distance to another point, etc. We want to write our own data type called Point. A Point is an abstraction that hides all the operations we might want to do with a geometric point.

A Class Defining a New Data Type class Point { // Data Fields (can use all other object types defined) double x; double y; String label; boolean errorFlag = false; // initialized Point origin; } _____________________________ Point myPoint = new Point();

Using the New Data Type If no constructor defined in class, you are given Default Constructor  Initializes all empty fields of state to 0 or null. Point aPoint = new Point(); aPoint.x = 4.5; aPoint.y = 3.2; aPoint.label = “Point A”; aPoint.origin = new Point(); aPoint.origin.x = 0.0; aPoint.origin.y = 0.0; aPoint.origin.label = “Origin”; aPoint.origin.origin  PROBLEM

Static Keyword 1. Want all Point Objects to share same Origin. Point aPoint = new Point(); Point bPoint = new Point(); aPoint.origin is a separate object from bPoint.origin. SOLUTION: Use static keyword. Now, all Point objects share a common origin: aPoint.origin is same object as bPoint.origin.

How does the Static Keyword affect Attributes When you create a static attribute it “only exists in the class”. Although each new object has that specific variable, that variable is only a reference to the same variable in the class. This means: For all the objects created from that class the static variable will have the same value in all the objects since they all refer to the same place in the class If the variables is changed in one of the objects/class this will change this variable in all objects/class since it really only exists in one place.

How does the Static Keyword affect Methods Like static attributes, static methods only exist in the class. Static methods cannot refer to non-static variables in the class.

Final Keyword 2. Want Origin to never change. Point aPoint = new Point(); aPoint.origin = new Point(); aPoint.origin.x = 0.0; aPoint.origin = new Point();// Bad – Changes origin Want to finalize the origin. SOLUTION: Use final keyword. Now, all Point objects have the same origin that cannot change.

How does the final Keyword affect attributes and methods? It does not let you change the value of a variable after it has been initialized. A final variable is a constant. A final method: prevents someone from overriding the method in a subclass (discussed in a later lecture).

Revised Point Class class Point { double x; double y; String label = “node point”; boolean errorFlag = false; // Added a totalPoints field for counting objects. static int totalPoints = 0; static final Point origin = new Point(); }

Review Example: class Point3D Identify class variables (those belonging to all 3DPoint objects) Identify instance variables (those particular to each 3DPoint object) What happens here to p1.x, p2.x, p1.y, p2.y, and p1.z, p2.z after each statement? Point3D p1 = new Point3D(); Point3D p2 = new Point3D(); p1.x = 1.0; p1.y = 2.0; p2.x = 3.0; p2.y = 4.0; Point3D.z = 8.2; p2.z = 9.9; class Point3D { double x; static double y; static final double z = 7.0; }

Adding Constructors x = xPos; y = yPos; ++totalPoints; } class Point { double x, y; String label = “node point”; boolean errorFlag = false; static int totalPoints = 0; static final Point origin = new Point(0.0, 0.0); // Construct a new Point – Initialize All empty variables (state). Point(double xPos, double yPos) { x = xPos; y = yPos; ++totalPoints; } } // End Class Point

Multiple Constructors class Point { … static int totalPoints = 0; static final Point origin = new Point(0.0, 0.0, “Origin”); // Construct a new Point given coordinates. Point(double x, double y) { this.x = x; this.y = y; ++totalPoints; } // Another overloaded constructor using this keyword. Point(double x, double y, String label) { this(x, y); //calls alternate constructor this.label = label; } // End Class Point

this Keyword The this keyword is a reference within the class to the object instance that is being created. Inside the class Point, the this reference points to the specific Point object being created. this.x is the same as using the object’s x parameter unmistakably. this() would call the default constructor. this(4.4, 2.8) would call the first constructor. this.doMethod() would call the object’s method.

References/ Constructors Again Using 1st Constructor: Point pointA = new Point(2.3, 4.8); Using 2nd Constructor: Point pointB = new Point(5.0, 8.9, “point label B”); Creating a reference to an object already made: No NEW Object Created: Must be careful: Multiple references may change same object Point getOrigin = Point.origin; Point anotherReferenceToPointA = pointA;

A Picture Representation After 2 Point Objects Created Object A Static Point.totalPoints Shared between all objects. Can Increment as more objects made. Point A = new Point(5.4, 2.8); x = 5.4 y = 2.8 label = “node point” totalPoints = origin = totalPoints = 3; Static Final Point.origin Shared, Cannot Change Object B Point B = new Point(2.0, 3.0); x = 0.0 y = 0.0 label = “Origin” totalPoints = origin = x = 2.0 y = 3.0 label = “node point” totalPoints = origin =

Objects Continued class Main { public static void main(String[] args) { Point A = new Point(2.0, 3.2); A.x = 5.0; Point.totalPoints = 8; // Or… A.totalPoints = 8; } /**Problem: Same problem as shown in Apple example. Violates the abstraction concept of a Point object. **/

Encapsulation, Preventing Access Want to hide implementation of Point object: We want to work with Points using Point methods, and try to keep data issues under the surface. Type Name POINT Data Fields: x, y, … Keep Hidden new Point(…) getX() getY() getNumberOfPoints() Interface of Object: (Constructor) Methods

Private, Public, (Protected), Nothing Specified. REVIEW Private, Public, (Protected), Nothing Specified. Private: Can only access variable or method within the class itself. Public: Can access variable or method everywhere. Protected: (used in inheritance) Nothing Specified: So far, we have not specified any private or public access. This means the variable or method is accessible in the same package (for now, the same as public)

Using Private, Public, (Protected) Access Modifiers public class Point { private double x, y; private String label = “node point”; private boolean errorFlag = false; private static int totalPoints = 0; public static final Point origin = new Point(0.0, 0.0, “Origin”); // Constructors // If we make a constructor private, we can’t use it outside class. So now the user can only call the second constructor private Point(double x, double y) { this.x = x; this.y = y; ++totalPoints; } public Point(double x, double y, String label) { this(x, y); this.label = label;

Access Into Point Object Which statements can we now perform outside the Point class (e.g. in another class with a main() method) ? Point p = new Point(4.4, 2.4); Point p = new Point(4.4, 2.8, “A new Point”); p.totalPoints = 5; Point.totalPoints = 5; p.x = 4; Point origin = p.origin; Point.origin = new Point(3.8, 4.4, “New Origin”);

Making Objects Useful: Methods Now we can create a point object from x, y coordinates and a label, and encapsulate the data. All private fields are hidden. We are given public fields, and public methods. But, we may still want to access private fields (but not change them). So we use functions and methods. We want to now do useful things with the data using methods/functions. Function declarations follow: Access static/final return type function name and arguments public double getX() public double getY() public string getLabel() public static int getNumberOfPoints() public double distanceTo(Point pointTwo)

Methods / Functions Review Arguments 1…N FUNCTION returnType answer Type1 arg1 Type2 arg2 … TypeN argN Function: Returns distance from this to pointTwo distanceTo Point pointTwo double distance

public class Point { } // End Class Point public double getX() { return x; } public double getY() { return y; } public String getLabel() { return label; } public static int getNumberOfPoints() { return totalPoints; // totalPoints is a static data field. } public double distanceTo(Point pointTwo) { if if (pointTwo == null) { errorFlag = true; // Better: throw a runtime exception. return 0.0; } } // Pythagorean Theorem double xDis = (x - pointTwo.x); double yDis = (y – pointTwo.y); return Math.sqrt(xDis * xDis + yDis * yDis); } // End Class Point

Using the Methods Here are sample uses of the Point methods. What is printed out? Point pOne = new Point(4.5, 5.5, “node point One”); Point pTwo = new Point(3.3, 3.3, “node point Two”); System.out.println(“Including origin, we made ” + Point.getNumberOfPoints() + “ points.”); System.out.println(“Distance from ” + pOne.getLabel() + “ to “ + pTwo.getLabel() + “ equals: ” + pOne.distanceTo(pTwo) );

Methods Automatically Given From Object (SuperClass) Methods for All Objects: toString(), equals(), getClass(), hashCode(), notify(), notifyAll(), wait() Object (Base Class) For Our Point Class: We may want to override or redefine toString() equals() Must use same function declaration As specified in super class Object. Point Derived Class

public class Point { } // End Class Point // Data Fields … // Constructors // New Methods // Overriden Methods (function declarations found in Object super class). public boolean equals(Object pTwo) { if (pTwo == null) return false; if (!(pTwo instanceof Point)) return false; Point pointTwo = (Point) pTwo; return ( (pointTwo.x == x) && (pointTwo.y == y) && (pointTwo.label.equals(label)) ); } public String toString() { return label + “: “ + Double.toString(x) + “, “ + y; } // End Class Point

POINT public class Point { +getX() +getY() +getNumberOfPoints() // Data Fields private double x, y; private String label = “node point”; private boolean errorFlag = false; private static int totalPoints = 0; public static final Point origin = new Point(0.0, 0.0, “Origin”); //Constructors private Point(double x, double y) {} public Point(double x, double y, String label) {} // New Methods public double getX() {} public double getY() {} public String getLabel() {} public static intgetNumberOfPoints(){} public double distanceTo(PointpointTwo) {} // Overriden Methods public boolean equals(Object pointTwo) {} public String toString() {} } // End Class Point POINT x y label totalPoints errorFlag origin +getX() +getY() +getNumberOfPoints() +distanceTo(Point two) +equals(Object two) +toString()

Review We can now understand Java object types better. Have finished a simple representation of a Point. We have created our own Point type. We can now understand Java object types better. These are classes someone else wrote for us. We can just use these objects and manipulate them using methods given to us. We do not have to know about their detailed code implementation. Browse : java.sun.com for Java 1.3 or 1.4 API for various java classes that are helpful.

A Helpful Java Defined Type: A Vector import java.util.Vector A Vector class holds elements of type Object. It is the same as an array, but can expand automatically if more objects are inserted, and can hold any type of Object. Vector points = new Vector(); // Define empty Vector. // Vector with 100 elements, but can expand. Vector points = new Vector(100);

Vector Methods A Few Important Methods Provided For Us: import java.util.Vector A Few Important Methods Provided For Us: // returns number of Objects stored in the Vector. int size() { …. } // adds a new object to this Vector list of objects. void addElement(Object newObject) { …. } // returns object at index i of this Vector list. Object elementAt(index i) { …. }

Vector Example public class SimpleVectorApplication { import java.lang.Vector public class SimpleVectorApplication { public static void main(String[] args) { Vector points = new Vector(); Point a = new Point(1.0, 1.0); Point b = new Point(2.0, 2.0); Point c = new Point(3.0, 3.0); points.addElement(a); points.addElement(b); points.addElement(c); for (int k=0; k < points.size(); k++) { System.out.println( points.elementAt(k) ); }

Independent Study Questions

Problem 1: Private/Public Concept class SingletonPoint { private String name = “Only One Object Made Of Type ME”; private static final singleton = new SingletonPoint(); private SingletonPoint() { } public static SingletonPoint getInstance() { return singleton; } public String getName() { return name; } } Above – How can we use the SingletonPoint object if the constructor is private?

Prob 2: Abstract Data Type- IntSet Want to represent a set of integers (x1, x2, …xN) Goal is to manipulate a set of integers. From Programming Data Abstractions: Liskov, Barbara.

Prob. 2: Abstract Data Type- IntSet Want to represent a set of integers (x1, x2, …xN) public class IntSet { public IntSet() public void insert(int x) public void remove(int x) public boolean contains(int x) public int size() public boolean isSubsetOf(IntSet s) } From Programming Data Abstractions: Liskov, Barbara.

Problem 3: Bank Accounts Want to represent a BankAccount Object: Goal is to have a bank account object with methods such as deposit, withdraw, transfer to another bank account, etc. public class BankAccount { private double savings = 0.0; private int accountID = 0; public BankAccount(accountID) {} public boolean withdraw(double amount) { } public void deposit(double amount) {} public boolean transferTo(BankAccount other) {} }

Problem 3 Continued…. BankAccount Object: Once we have an account object, we can think in an object oriented way to design larger programs and systems. To write a bank account application, we think about: A Bank Type to represent banks. Maybe want a Transaction object. (A Transaction is between a Bank and a Person with an Account). To finish the application – probably need a bank database/file to deal with storing account info. (File IO introduced soon). Could make a GUI (graphics interface) for someone to access account info on web. Synchronization problems, security, etc.

Intro To Objects END Well designed Objects are the building blocks for larger object oriented systems. Now, our goal is to write larger programs that utilize many objects.