Intermediate Java 95-713 Sakir YUCEL MISM/MSIT Carnegie Mellon University Lecture: Initialization & Cleanup Slides adapted from Prof. Steven Roehrig.

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.
23-May-15 Polymorphism. 2 Signatures In any programming language, a signature is what distinguishes one function or method from another In C, every function.
Road Map Introduction to object oriented programming. Classes
CSM-Java Programming-I Spring,2005 Class Design Lesson - 4.
15-Jun-15 Polymorphism. 2 Signatures In any programming language, a signature is what distinguishes one function or method from another In C, every function.
Java Exceptions. Intro to Exceptions  What are exceptions? –Events that occur during the execution of a program that interrupt the normal flow of control.
Chapter 3 Classes and Methods. 2 Knowledge Goals Appreciate the difference between a class in the abstract sense and a class as a Java construct Know.
Intermediate Java Sakir YUCEL MISM/MSIT Carnegie Mellon University Program Control Slides adapted from Steven Roehrig.
Intermediate Java II Sakir YUCEL MISM/MSIT Carnegie Mellon University Lecture: Exception Handling Slides adapted from Prof. Steven Roehrig.
CS 106 Introduction to Computer Science I 03 / 23 / 2007 Instructor: Michael Eckmann.
C++ Classes in Depth. Topics Designing Your Own Classes Attributes and Behaviors Writing Classes in C++ Creating and Using Objects.
Terms and Rules Professor Evan Korth New York University (All rights reserved)
Object-Oriented Programming MISM/MSIT Carnegie Mellon University Lecture 3: Initialization & Cleanup.
Fundamental Programming Structures in Java: Comments, Data Types, Variables, Assignments, Operators.
Java Exceptions. Intro to Exceptions  What are exceptions? –Events that occur during the execution of a program that interrupt the normal flow of control.
10-Aug-15 Classes and Objects in Java. 2 Classes and Objects A Java program consists of one or more classes A class is an abstract description of objects.
MIT AITI 2003 Lecture 7 Class and Object - Part I.
Java Methods By J. W. Rider. Java Methods Modularity Declaring methods –Header, signature, prototype Static Void Local variables –this Return Reentrancy.
Programming Languages and Paradigms Object-Oriented Programming.
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look.
Lecture 22 Miscellaneous Topics 4 + Memory Allocation.
Chapter 4: Initialization and cleanup ● How to initializa an object ● Method overloading ● Cleanup: Finalization and gaurbage collection.
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.
Java Implementation: Part 3 Software Construction Lecture 8.
Initialization & Cleanup Guaranteed initialization with the constructor The name of the constructor is the same as the name of the class.
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.
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.
Programming in Java CSCI-2220 Object Oriented Programming.
Session 7 Methods Strings Constructors this Inheritance.
Everything is an object (CH-2) Manipulating Objects with References. Manipulating Objects with References. String s; String s = “IS2550” String s = new.
Initialization & Cleanup Dr. Ramzi Saifan Slides adapted from Prof. Steven Roehrig.
Rina System development with Java Instructors: Rina Zviel-Girshin Lecture 4.
Chapter 4&5 Defining Classes Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
1 CSC241: Object Oriented Programming Lecture No 02.
Reusing Classes composition The trick is to use the classes without soiling the existing code. In this chapter you’ll see two ways to accomplish.
CSC 212 Object-Oriented Programming and Java Part 2.
Chapter 5 Classes and Methods II Lecture Slides to Accompany An Introduction to Computer Science Using Java (2nd Edition) by S.N. Kamin, D. Mickunas, E.
Chapter 3 Introduction to Classes and Objects Definitions Examples.
Classes Modeling the Object. Objects model the world Classes are programmer defined types that model the parts of a system Class serve as blueprints for.
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.
1 Lecture07: Memory Model 5/2/2012 Slides modified from Yin Lou, Cornell CS2022: Introduction to C.
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.
Today’s lecture Review chapter 5 go over exercises.
Fall 2015CISC/CMPE320 - Prof. McLeod1 CISC/CMPE320 Assignment 3 is due Sunday, the 8 th at 7pm. Today: –Two simple binding examples. –Function Hiding.
Methods What is a method? Main Method the main method is where a stand alone Java program normally begins execution common compile error, trying.
28-Dec-04polymorhism.ppt1 Polymorphism. 28-Dec-04polymorhism.ppt2 signatures in any programming language, a signature is what distinguishes one function.
Dynamic Memory Management & Static Class Members Lecture No 7 Object Oriented Programming COMSATS Institute of Information Technology.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 10 Java Fundamentals Objects/ClassesMethods.
Sadegh Aliakbary Sharif University of Technology Fall 2010.
COP Topics Java Basics - How to write & call your own method - Math methods (static methods) - String methods (instance methods) - Errors Classes.
CompSci 230 S Programming Techniques
Classes and Objects.
Static data members Constructors and Destructors
Friend Class Friend Class A friend class can access private and protected members of other class in which it is declared as friend. It is sometimes useful.
Java Primer 1: Types, Classes and Operators
Chapter 5 Conclusion CIS 61.
Polymorphism 15-Nov-18.
Assessment – Java Basics: Part 1
Java Programming Language
Presentation transcript:

Intermediate Java Sakir YUCEL MISM/MSIT Carnegie Mellon University Lecture: Initialization & Cleanup Slides adapted from Prof. Steven Roehrig

Initialization  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.  We often forgot…  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.  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 Socket needs to have its IP address set.  A Rectangle needs to have its dimensions and location set.  Etc.

What If We Forget?  Things don’t act the way we expect them to!  We only learn about problems at runtime.  Maybe we don’t find out until it’s too late.  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 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.

Constructors  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.  (This implies that overloaded methods are OK in Java.)  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(); title is an empty character sequence author is an empty character sequence numPages is 0  Book usefulBook = new Book(“The TeXBook”, “Donald Knuth”, 483);

Method Overloading  Methods with the same name, but different sets of arguments.  A natural idea (carWash the car? shirtWash the shirt? dogWash the dog? Nah…)  Constructors can be overloaded; so can any function.  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.

Overloading With Primitives  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. void doSomething(long l) { // whatever } : int i = 13; doSomething(i);

The Default Constructor  “But, how come I didn’t have to write constructors for the last homework?”  The compiler will write one for you!  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 Common Error  The compiler gives an error.  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: 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 f.play(4);  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 this Keyword (cont.)  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 “with no this”.  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.

Cleanup  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.  There is no guarantee that such an object will be garbage collected.  Garbage collection is not like destruction (in the C++ sense).

Member Initialization  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”?

Member Initialization (cont.)  You can initialize in a class definition:  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:  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). class Counter { int i = 1; Counter() { i = 7; } Counter(int j) { }; :

Static Member Initialization  Same story; primitives get zero unless initialized, references get null unless initialized.  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.

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; }

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. Before I’m even finished I have to do it again!” // Joan Rivers’ algorithm (pseudo-code) cleanTheHouse() { static String message = “I’m ” message = message + “so ” shout(message + “tired of this!”) cleanTheHouse() }

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

Recursion (cont.)  Factorials are easy: n! = n(n-1)(n-2)    1 long factorial( long number) { if (number <= 1) // base case return 1; else 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