DATA STRUCTURES Lecture: Initialization & Cleanup Slides adapted from Prof. Steven Roehrig.

Slides:



Advertisements
Similar presentations
Objects and Classes Part II
Advertisements

Exceptions CSE301 University of Sunderland Harry Erwin, PhD.
DATA STRUCTURES Lecture: Interfaces Slides adapted from Prof. Steven Roehrig.
Lecture 9: More on objects, classes, strings discuss hw3 assign hw4 default values for variables scope of variables and shadowing null reference and NullPointerException.
Web Application Development Slides Credit Umair Javed LUMS.
Chapter 4&5 Defining Classes Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
June 1, 2000 Object Oriented Programming in Java (95-707) Java Language Basics 1 Lecture 6 Object Oriented Programming in Java Language Basics Objects.
CERTIFICATION OBJECTIVES Use Class Members Develop Wrapper Code & Autoboxing Code Determine the Effects of Passing Variables into Methods Recognize when.
Lecture 2: Object Oriented Programming I
Road Map Introduction to object oriented programming. Classes
CSM-Java Programming-I Spring,2005 Class Design Lesson - 4.
Java Exceptions. Intro to Exceptions  What are exceptions? –Events that occur during the execution of a program that interrupt the normal flow of control.
Evan Korth New York University Computer Science I Classes and Objects Professor: Evan Korth New York University.
26-Jun-15 Polymorphism. 2 Legal assignments Widening is legal Narrowing is illegal (unless you cast) class Test { public static void main(String args[])
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)
Object-Oriented Programming MISM/MSIT Carnegie Mellon University Lecture 3: Initialization & Cleanup.
Java Exceptions. Intro to Exceptions  What are exceptions? –Events that occur during the execution of a program that interrupt the normal flow of control.
Java Methods By J. W. Rider. Java Methods Modularity Declaring methods –Header, signature, prototype Static Void Local variables –this Return Reentrancy.
OOP Languages: Java vs C++
Object-Oriented Programming Concepts
Programming Languages and Paradigms Object-Oriented Programming.
Chapter 4: Initialization and cleanup ● How to initializa an object ● Method overloading ● Cleanup: Finalization and gaurbage collection.
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
Classes and Objects. Topics The Class Definition Declaring Instance Member Variables Writing Instance Member Methods Creating Objects Sending Messages.
Object Oriented Programming: Java Edition By: Samuel Robinson.
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.
Algorithm Programming Bar-Ilan University תשס"ח by Moshe Fresko.
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.
More about Class 靜宜大學資工系 蔡奇偉副教授 ©2011. 大綱 Instance Class Members Class members can be associated with an instance of the class or with the class as a.
Java Objects and Classes. Overview n Creating objects that belong to the classes in the standard Java library n Creating your own classes.
Constructors CMSC 202. Object Creation Objects are created by using the operator new in statements such as… The following expression invokes a special.
Object Based Programming Chapter 8. 2 In This Chapter We will learn about classes Garbage Collection Data Abstraction and encapsulation.
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.
C# Classes and Inheritance CNS 3260 C#.NET Software Development.
Session 7 Methods Strings Constructors this Inheritance.
Initialization & Cleanup Dr. Ramzi Saifan Slides adapted from Prof. Steven Roehrig.
Dale Roberts Object Oriented Programming using Java - Final and Static Keywords Dale Roberts, Lecturer Computer Science, IUPUI
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 26 - Java Object-Based Programming Outline 26.1Introduction.
COP 2800 Lake Sumter State College Mark Wilson, Instructor.
Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and.
Classes. Constructor A constructor is a special method whose purpose is to construct and initialize objects. Constructor name must be the same as the.
Chapter 4&5 Defining Classes Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Constructors & Garbage Collection Ch. 9 – Head First Java.
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.
Chapter 3 Introduction to Classes and Objects Definitions Examples.
Finalizers, this reference and static Sangeetha Parthasarathy 06/13/2001.
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.
Object Oriented Programming
SOEN 343 Software Design Section H Fall 2006 Dr Greg Butler
1 Lecture07: Memory Model 5/2/2012 Slides modified from Yin Lou, Cornell CS2022: Introduction to C.
Fall 2015CISC/CMPE320 - Prof. McLeod1 CISC/CMPE320 Assignment 3 is due Sunday, the 8 th at 7pm. Today: –Two simple binding examples. –Function Hiding.
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.
Methods What is a method? Main Method the main method is where a stand alone Java program normally begins execution common compile error, trying.
Dynamic Memory Management & Static Class Members Lecture No 7 Object Oriented Programming COMSATS Institute of Information Technology.
Garbage Collection It Is A Way To Destroy The Unused Objects. To do so, we were using free() function in C language and delete() in C++. But, in java it.
Lecture 9: Object and Classes Michael Hsu CSULA. 2 OO Programming Concepts Object-oriented programming (OOP) involves programming using objects. An object.
Object Based Programming Chapter 8. 2 Contrast ____________________ Languages –Action oriented –Concentrate on writing ________________ –Data supports.
Sadegh Aliakbary Sharif University of Technology Fall 2010.
Classes and Objects.
Static data members Constructors and Destructors
Java Primer 1: Types, Classes and Operators
Java Programming Language
Assessment – Java Basics: Part 1
Web Design & Development Lecture 4
CS 240 – Advanced Programming Concepts
Presentation transcript:

DATA STRUCTURES 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” CS 340 2

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. CS 340 3

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 CS 340 4

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. CS 340 5

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. You use a constructor when you create an object. CS 340 6

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

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); CS 340 8

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 A default constructor has no arguments (but still has the same name as the class) CS 340 9

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(); CS

QUESTIONS? CS

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. CS

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); CS

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. CS

The this Keyword (cont.) A reference to the “current” object is 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(); } CS

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

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. CS

Cleanup Java has a garbage collector that reclaims memory. When should the garbage collector cleanup? If an object “can’t be reached” by a chain of references from a reference on the stack No guarantees for gc (garbage collection) System.gc( ) CS

How does GC work? Stop-and-Copy Mark and Sweep Just In Time (JIT) CS

QUESTIONS? CS

Member Initialization Unitialized variables are a common source of bugs. What about primitives? Is the initialized value (zero) any better than a “garbage value”? CS

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(); : } CS

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. class Counter { int i = 1; Counter() { i = 7; } Counter(int j) { }; : CS

Static Member Initialization 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. CS

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

C# vs Java Constructors! CS

Constructors / Destructors 27 JavaC# class SuperHero { private int mPowerLevel; public SuperHero() { mPowerLevel = 0; } public SuperHero(int powerLevel) { this.mPowerLevel= powerLevel; } // No destructors, just override the finalize method protected void finalize() throws Throwable { super.finalize(); // Always call parent's finalizer } class SuperHero { private int mPowerLevel; public SuperHero() { mPowerLevel = 0; } public SuperHero(int powerLevel) { this.mPowerLevel= powerLevel; } ~SuperHero() { // Destructor code to free unmanaged resources. // Implicitly creates a Finalize method. }

QUESTIONS? CS