Object-Oriented Programming 95-712 MISM/MSIT Carnegie Mellon University Lecture 3: Initialization & Cleanup.

Slides:



Advertisements
Similar presentations
DATA STRUCTURES Lecture: Interfaces Slides adapted from Prof. Steven Roehrig.
Advertisements

June 1, 2000 Object Oriented Programming in Java (95-707) Java Language Basics 1 Lecture 6 Object Oriented Programming in Java Language Basics Objects.
DATA STRUCTURES Lecture: Initialization & Cleanup Slides adapted from Prof. Steven Roehrig.
CERTIFICATION OBJECTIVES Use Class Members Develop Wrapper Code & Autoboxing Code Determine the Effects of Passing Variables into Methods Recognize when.
Road Map Introduction to object oriented programming. Classes
CSM-Java Programming-I Spring,2005 Class Design Lesson - 4.
CS 106 Introduction to Computer Science I 03 / 23 / 2007 Instructor: Michael Eckmann.
1 Chapter 2 Introductory Programs. 2 Getting started To create and run a Java program –Create a text file with a.java extension for the source code. For.
C++ Classes in Depth. Topics Designing Your Own Classes Attributes and Behaviors Writing Classes in C++ Creating and Using Objects.
Intermediate Java Sakir YUCEL MISM/MSIT Carnegie Mellon University Lecture: Initialization & Cleanup Slides adapted from Prof. Steven Roehrig.
Terms and Rules Professor Evan Korth New York University (All rights reserved)
Options for User Input Options for getting information from the user –Write event-driven code Con: requires a significant amount of new code to set-up.
MIT AITI 2003 Lecture 7 Class and Object - Part I.
OOP Languages: Java vs C++
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 l Array Basics l Arrays in Classes and Methods l Programming with Arrays.
Chapter 4: Initialization and cleanup ● How to initializa an object ● Method overloading ● Cleanup: Finalization and gaurbage collection.
Presented by: Mojtaba Khezrian. Agenda Object Creation Object Storage More on Arrays Parameter Passing For Each VarArgs Spring 2014Sharif University of.
Java Class Syntax CSIS 3701: Advanced Object Oriented Programming.
Classes and Objects. Topics The Class Definition Declaring Instance Member Variables Writing Instance Member Methods Creating Objects Sending Messages.
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.
1 C - Memory Simple Types Arrays Pointers Pointer to Pointer Multi-dimensional Arrays Dynamic Memory Allocation.
CMSC 202 Arrays. Aug 6, Introduction to Arrays An array is a data structure used to process a collection of data that is all of the same type –An.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2009 Pearson Education, Inc., Upper.
Arrays Module 6. Objectives Nature and purpose of an array Using arrays in Java programs Methods with array parameter Methods that return an array Array.
What is an Array? An array is a collection of variables. Arrays have three important properties: –group of related items(for example, temperature for.
Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 1, page 1 Sun Certified Java 1.4 Programmer Chapter 1 Notes Gary Lance
Initialization & Cleanup Guaranteed initialization with the constructor The name of the constructor is the same as the name of the class.
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 6 l Array Basics l Arrays and Methods l Programming with Arrays.
What does a computer program look like: a general overview.
Constructors CMSC 202. Object Creation Objects are created by using the operator new in statements such as… The following expression invokes a special.
12-CRS-0106 REVISED 8 FEB 2013 CSG2H3 Object Oriented Programming.
Java Classes. Consider this simplistic class public class ProjInfo {ProjInfo() {System.out.println("This program computes factorial of number"); System.out.println("passed.
ADTs and C++ Classes Classes and Members Constructors The header file and the implementation file Classes and Parameters Operator Overloading.
Peyman Dodangeh Sharif University of Technology Fall 2013.
Sadegh Aliakbary Sharif University of Technology Spring 2011.
Object-Oriented Programming Instructor: Peyman Dodangeh Sharif University of Technology Lecture 3: Initialization & Cleanup andrew.cmu.edu/user/syucel/Java/lectures.html.
More About Objects and Methods Chapter 5. Outline Programming with Methods Static Methods and Static Variables Designing Methods Overloading Constructors.
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
Programming in Java CSCI-2220 Object Oriented Programming.
Session 7 Methods Strings Constructors this Inheritance.
Initialization & Cleanup Dr. Ramzi Saifan Slides adapted from Prof. Steven Roehrig.
Rina System development with Java Instructors: Rina Zviel-Girshin Lecture 4.
Method Overloading  Methods of the same name can be declared in the same class for different sets of parameters  As the number, types and order of the.
CSC 212 Object-Oriented Programming and Java Part 2.
Methods. Methods also known as functions or procedures. Methods are a way of capturing a sequence of computational steps into a reusable unit. Methods.
Classes and Objects CS177 Rec 10. Announcements Project 4 is posted ◦ Milestone due on Nov. 12. ◦ Final submission due on Nov. 19. Exam 2 on Nov. 4 ◦
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 9 Java Fundamentals Objects/ClassesMethods Mon.
CMSC 202 Arrays 2 nd Lecture. Aug 6, Array Parameters Both array indexed variables and entire arrays can be used as arguments to methods –An indexed.
Static?. Static Not dynamic class Widget { static int s; int d; // dynamic // or instance // variable }
CMSC 202 Advanced Section Classes and Objects: Object Creation and Constructors.
1 Becoming More Effective with C++ … Day Two Stanley B. Lippman
Programming Fundamentals. Topics to be covered Today Recursion Inline Functions Scope and Storage Class A simple class Constructor Destructor.
Peyman Dodangeh Sharif University of Technology Spring 2014.
Topic 8Classes, Objects and Methods 1 Topic 8 l Class and Method Definitions l Information Hiding and Encapsulation l Objects and Reference Classes, Objects,
Week 10 - Wednesday.  What did we talk about last time?  Method example  Roulette simulation  Types in Java.
Arrays Chapter 7. MIS Object Oriented Systems Arrays UTD, SOM 2 Objectives Nature and purpose of an array Using arrays in Java programs Methods.
C# Programming Methods.
Struct s (7.4) Used as data aggregates for an entity can be different types of data e.g. for student id, name, GPA, address,... Similar to classes, but.
Extra Recitations Wednesday 19:40-22:30 FENS L055 (tomorrow!) Friday 13:40-16:30 FENS L063 Friday 17: :30 FENS L045 Friday 19:40-22:30 FENS G032.
Fall 2015CISC/CMPE320 - Prof. McLeod1 CISC/CMPE320 Assignment 3 is due Sunday, the 8 th at 7pm. Today: –Two simple binding examples. –Function Hiding.
Chapter 5: Arrays in Java. The objectives of this chapter are:  1. To discuss the creation and use of Arrays.   2. To continue to use the String class.
Object Oriented Programming Lecture 2: BallWorld.
COP Topics Java Basics - How to write & call your own method - Math methods (static methods) - String methods (instance methods) - Errors Classes.
Java Applet Programming Barry Sosinsky Valda Hilley
Java Primer 1: Types, Classes and Operators
Chapter 5 Conclusion CIS 61.
Advanced Programming Behnam Hatami Fall 2017.
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.
Java Programming Language
Review for Midterm 3.
Presentation transcript:

Object-Oriented Programming MISM/MSIT Carnegie Mellon University Lecture 3: Initialization & Cleanup

Initialization In “C”-style programming, structures were glued-together primitive types, and functions were separate. In “C”-style programming, structures were glued-together primitive types, and functions were separate. If a structure needed initialization, the programmer had to remember to do it. If a structure needed initialization, the programmer had to remember to do it. We often forgot… We often forgot… Just as bad, we also forgot to “clean up” Just as bad, we also forgot to “clean up”

What Needs to be Initialized? A stream for file reading needs to be attached to the file. A stream for file reading needs to be attached to the file. An array of Vectors needs to have the Vectors created (and themselves initialized). An array of Vectors needs to have the Vectors created (and themselves initialized). A Checkbox needs to have its state set, and perhaps be associated with an ActionListener. A Checkbox needs to have its state set, and perhaps be associated with an ActionListener. A Socket needs to have its IP address set. A Socket needs to have its IP address set. A Rectangle needs to have its dimensions and location set. A Rectangle needs to have its dimensions and location set. Etc. Etc.

What If We Forget? Things don’t act the way we expect them to! Things don’t act the way we expect them to! We only learn about problems at runtime. We only learn about problems at runtime. Maybe we don’t find out until it’s too late. Maybe we don’t find out until it’s too late. Common culprits: Common culprits: –references that lead nowhere –garbage values

How Does Java Help? Java initializes all class member variables to zero whenever we create an object. Java initializes all class member variables to zero whenever we create an object. Java allows us to write constructors, special methods, one of which will be called on object creation. Java allows us to write constructors, special methods, one of which will be called on object creation. Java refuses to create an object (compile error) if we haven’t provided the right kind of constructor. Java refuses to create an object (compile error) if we haven’t provided the right kind of constructor.

Constructors A constructor method has the same name as the class. It has no return type. A constructor method has the same name as the class. It has no return type. There can be many different constructors, each with a distinct argument signature. There can be many different constructors, each with a distinct argument signature. (This implies that overloaded methods are OK in Java.) (This implies that overloaded methods are OK in Java.) You specify the particular constructor you want when you create an object. You specify the particular constructor you want when you create an object.

Example Constructor class Book { String title; String author; int numPages; Book() { }// default constructor Book(String t, String a, int p) { title = t; author = a; numPages = p; }

Making Books Book uselessBook = new Book(); Book uselessBook = new Book(); –title is an empty character sequence –author is an empty character sequence –numPages is 0 Book usefulBook = new Book(“The TeXBook”, “Donald Knuth”, 483); Book usefulBook = new Book(“The TeXBook”, “Donald Knuth”, 483);

Method Overloading Methods with the same name, but different sets of arguments. Methods with the same name, but different sets of arguments. A natural idea (carWash the car? shirtWash the shirt? dogWash the dog? Nah…) A natural idea (carWash the car? shirtWash the shirt? dogWash the dog? Nah…) Constructors can be overloaded; so can any function. Constructors can be overloaded; so can any function. This is OK, but not recommended: This is OK, but not recommended: –void print(String s, int i) –void print(int i, String s) You can’t overload on the return type alone. You can’t overload on the return type alone.

Overloading With Primitives The compiler tries to find an exact match, but will promote (“widen”) a value if necessary. The compiler tries to find an exact match, but will promote (“widen”) a value if necessary. The compiler won’t narrow without an explicit cast. The compiler won’t narrow without an explicit cast. void doSomething(long l) { // whatever } : int i = 13; doSomething(i);

The Default Constructor “But Steve, how come I didn’t have to write constructors for the last homework?” “But Steve, how come I didn’t have to write constructors for the last homework?” The compiler will write one for you! The compiler will write one for you! But only if you haven’t written any constructors at all (for this class). But only if you haven’t written any constructors at all (for this class). A default constructor has no arguments (but still has the same name as the class). A default constructor has no arguments (but still has the same name as the class).

A Common Error The compiler gives an error. The compiler gives an error. Normally, you always provide a default constructor that does as much as possible (but not too much!). Normally, you always provide a default constructor that does as much as possible (but not too much!). class Book { String title; String author; int numPages; Book(String t, String a, int n) { title = t; author = a, numPages = n; } : Book b = new Book();

The this Keyword A common “C” idiom: A common “C” idiom: MusicFile f = new MusicFile(“Yardbirds”) play(&f, 4);// play the 4th track In object-oriented style, we want to “send a message” to an object, so in Java we say In object-oriented style, we want to “send a message” to an object, so in Java we sayf.play(4); The compiler knows which object (f in this case) the method is being called for. The compiler knows which object (f in this case) the method is being called for. The compiler sends this information to the method, in the form of a reference to f. The compiler sends this information to the method, in the form of a reference to f.

The this Keyword (cont.) If necessary, we can get a reference to the “current” object; it’s called this. If necessary, we can get a reference to the “current” object; it’s called this. public class Leaf { int i = 0; Leaf increment() { i++; return this; } void print() { System.out.println(“i = ” + i); } public static void main(String[] args) { Leaf x = new Leaf(); x.increment().increment().increment().print(); }

Other Uses of this public class Flower { int petalCount = 0; String s = new String(“null”); Flower(int petals) { petalCount = petals; } Flower(String ss) { s = ss; } Flower(String s, int petals) { this(petals); //! this(s); // can’t do it twice this.s = s; } Flower() { this(“hi”, 47); }// default constructor }

So, What Is A static Method? It’s a method that belongs to the class but not to any instance. It’s a method that belongs to the class but not to any instance. It’s a method “with no this”. It’s a method “with no this”. You can’t call non-static methods from within a static method. You can’t call non-static methods from within a static method. You can call a static method without knowing any object of the class. You can call a static method without knowing any object of the class.

Cleanup Java has a garbage collector that reclaims memory. Java has a garbage collector that reclaims memory. If an object “can’t be reached” by a chain of references from a reference on the stack (or static storage), it is garbage. If an object “can’t be reached” by a chain of references from a reference on the stack (or static storage), it is garbage. There is no guarantee that such an object will be garbage collected. There is no guarantee that such an object will be garbage collected. Garbage collection is not like destruction (in the C++ sense). Garbage collection is not like destruction (in the C++ sense).

Member Initialization Unitialized variables are a common source of bugs. Unitialized variables are a common source of bugs. –Using an unititialized variable in method gets a compiler error. –Primitive data members in classes automatically get initialized to “zero”. Is the initialized value (zero) any better than a “garbage value”? Is the initialized value (zero) any better than a “garbage value”?

Member Initialization (cont.) You can initialize in a class definition: You can initialize in a class definition: This is very surprising to C++ programmers! This is very surprising to C++ programmers! class Notebook { long ram = ; String name = new String(“IBM”); float price = ; Battery bat = new Battery(); Disk d; // a null reference int i = f(); : }

Constructors Again You can have both class initialization and constructor initialization: You can have both class initialization and constructor initialization: The order of initialization follows the order of the initialization statements in the class definition. The order of initialization follows the order of the initialization statements in the class definition. It’s done before any constructor initialization, so it may be done twice (as Counter illustrates). It’s done before any constructor initialization, so it may be done twice (as Counter illustrates). class Counter { int i = 1; Counter() { i = 7; } :

Static Member Initialization Same story; primitives get zero unless initialized, references get null unless initialized. Same story; primitives get zero unless initialized, references get null unless initialized. Static initialized either Static initialized either –when the first object of the type is created, or –at the time of the first use of the variable. If you never use it, it’s never initialized. If you never use it, it’s never initialized.

Arrays Arrays in Java are not aggregates, as in C/C++. They are objects. Arrays in Java are not aggregates, as in C/C++. They are objects. An array is a sequence of homogeneous primitives or objects, labeled by a single name. An array is a sequence of homogeneous primitives or objects, labeled by a single name. Square brackets [ ] are used to define and access them. Square brackets [ ] are used to define and access them. Every array has a built-in read-only length attribute. Every array has a built-in read-only length attribute.

Array Initialization Arrays are objects, so if you say Arrays are objects, so if you say int[] idNumbers; all you get is a reference (named idNumbers). You don’t say how big the array is when you create the reference, only when you initialize it. You don’t say how big the array is when you create the reference, only when you initialize it.

Using Arrays Because even arrays of primitive types are objects, “strange behavior” can result: Because even arrays of primitive types are objects, “strange behavior” can result: public class ArrayTest { public static void main(String[] args) { int[] a1 = {1,2,3,4}; int[] a2; a2 = a1; for (int i = 0; i < a1.length; i++) a2[i]++; for (int i = 0; i < a1.length; i++) System.out.println("a1[" + i + "] = " + a1[i]); }

Using Arrays (cont.) The memory picture can be visualized like this: The memory picture can be visualized like this: array elements array length a1a2 before a2 = a array elements array length a1a2 after a2 = a1

Using Arrays (cont.) If you want a copy, do it yourself: If you want a copy, do it yourself: If you index outside of the array: If you index outside of the array: for (int i = 0; i < a1.length + 1; i++) for (int i = 0; i < a1.length + 1; i++) you get a runtime exception: java.lang.ArrayIndexOutOfBoundsException: 4 at ArrayTest.main(ArrayTest.java:11) int[] a3 = new int[a1.length]; for (int i = 0; i < a1.length; i++) a3[i] = a1[i];

Arrays of Strings String[] names;// just a reference names = new String[3];// an array of references names[0] = "Alzadjala"; names[1] = "Areepurath"; names[2] = "Ariffin"; System.out.println("The number of students” + “in Java class is ” + names.length);

Variable-Length Argument Lists class A { int i; } public class VarArgs { static void f(Object[] x) { for (int i = 0; i < x.length; i++) System.out.println(x[i]); } public static void main(String[] args) { f(new Object[] {"one", "two", "three" }) ; f(new Object[] {new A(), new A(), new A() } ); f(new Object[] { new Integer(47), new VarArgs(), new Float(3.14), new Double(11.11) } ); }

Variable-Length Argument Lists This prints This

Add toString() to Class A class A { int i; public String toString() { return new String("" + i); // or this: // return “” + i; // but not this: // return i; }

Multi-Dimensional Arrays From simple: From simple: int[][] a1 = { {1, 2, 3}, {4, 5, 6} }; to complex: to complex: int[][][] a4 = new int[2][][]; for (int i = 0; i < a4.length; i++) { a4[i] = new int[i+1]; a4[i] = new int[i+1]; for (int j = 0; j < a4[i].length; j++) for (int j = 0; j < a4[i].length; j++) a4[i][j] = new int[i+j]; a4[i][j] = new int[i+j];}

Fill The Last Array Like This for (int i = 0; i < a4.length; i++) for (int j = 0; j < a4[i].length; j++) for (int j = 0; j < a4[i].length; j++) for (int k = 0; k < a4[i][j].length; k++) for (int k = 0; k < a4[i][j].length; k++) a4[i][j][k] = i*j*k; // silly values a4[i][j][k] = i*j*k; // silly values

Example of a Simple Time Class public class Time { int hour; int minute; int second; Time() { setTime(0, 0, 0); } Time(int h) { setTime(h, 0, 0); } Time(int h, int m) { setTime(h, m, 0); } Time(int h, int m, int s) { setTime(h, m, s); }

Time Class (cont.) Time setTime(int h, int m, int s) { setHour(h); setMinute(m); setSecond(s); return this; } Time setHour(int h) { hour = (( h >= 0 && h < 24 ) ? h : 0 ); return this; }

Time Class (cont.) Time setMinute(int m) { minute = (( m >= 0 && m < 60 ) ? m : 0 ); return this; } Time setSecond(int s) { second = ((s >= 0 && s < 24 ) ? s : 0 ); return this; } int getHour() { return hour; } int getMinute() { return minute; } int getSecond() { return second; }

Time Class (cont.) public String toString() { return ( ( hour == 12 || hour == 0 ) ? 12 : hour % 12 ) + ":" + ( minute < 10 ? "0" : "" ) + minute + ":" + ( second < 10 ? "0" : "" ) + second + ( hour < 12 ? " AM" : " PM" ) ; }

Time Class Driver public class TestTime { public static void main(String[] args) { Time t1 = new Time(); Time t2 = new Time(20, 3, 45); t1.setHour(7).setMinute(32).setSecond(23); System.out.println("t1 is " + t1); System.out.println("t2 is " + t2); }

Miscellaneous Topics: Recursion Joan Rivers says “I hate cleaning my house. A month later I just have to do it again!” Joan Rivers says “I hate cleaning my house. A month later I just have to do it again!” // Joan Rivers’ algorithm (pseudo-code) cleanTheHouse() { static String message = “I’m ” static String message = “I’m ” wait one month wait one month message = message + “so ” message = message + “so ” shout(message + “tired of this!”) shout(message + “tired of this!”) cleanTheHouse() cleanTheHouse()}

Recursion A method that calls itself. A method that calls itself. At each call, new local variables are created. At each call, new local variables are created. There must be a stopping condition! Joan doesn’t have one… There must be a stopping condition! Joan doesn’t have one… Often a natural way to express a problem. Often a natural way to express a problem. Iteration might be better, because of the overhead of function calls and extra storage. Iteration might be better, because of the overhead of function calls and extra storage. It’s not always easy to convert recursion into iteration. It’s not always easy to convert recursion into iteration.

Recursion (cont.) Factorials are easy: n! = n(n-1)(n-2)    1 Factorials are easy: n! = n(n-1)(n-2)    1 long factorial( long number) { if (number <= 1) // base case if (number <= 1) // base case return 1; return 1; else else return number * factorial(number - 1); return number * factorial(number - 1);}

Deitel & Deitel’s Illustration 5! 5 * 4! 4 * 3! 3 * 2! 2 * 1! 1 5! 5 * 4! 4 * 3! 3 * 2! 2 * 1! 1 1 returned 2! = 2*1=2 returned 3! = 3*2 = 6 returned 4! = 4*6 = 24 returned 5! = 5*24 = 120 returned Recursive calls Recursive returns

Let’s Try An Applet import java.awt.Graphics; import java.applet.Applet; public class FactorialTest extends Applet { public void paint(Graphics g) { int yPosition = 25; for (long i = 0; i < 10; i++) { g.drawString(i + "! = " + factorial(i), 25, yPosition); yPosition += 15; } public long factorial(long number) {…} }

The Output in Together In the Run Configuration dialog, select the Applet tab!

In the Command Line World In an editor, create a file containing: code=“FactorialTest.class” width=235 height=250> Save it as Factorial.html

The Output in AppletViewer D:\Together5.02\out\classes\FactorialApplet>appletviewer Factorial.html