Initialization & Cleanup Dr. Ramzi Saifan Slides adapted from Prof. Steven Roehrig.

Slides:



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

Web Application Development Slides Credit Umair Javed LUMS.
Chapter 4&5 Defining Classes Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
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.
OOP Using Classes - I. Structures vs. Classes C-style structures –No “interface” If implementation changes, all programs using that struct must change.
Road Map Introduction to object oriented programming. Classes
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.
19-Jun-15 Polymorphism. 2 Signatures In any programming language, a signature is what distinguishes one function or method from another In C, every function.
CS 106 Introduction to Computer Science I 03 / 23 / 2007 Instructor: Michael Eckmann.
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.
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.
1 Inheritance and Polymorphism Chapter 9. 2 Polymorphism, Dynamic Binding and Generic Programming public class Test { public static void main(String[]
Chapter 4: Initialization and cleanup ● How to initializa an object ● Method overloading ● Cleanup: Finalization and gaurbage collection.
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.
Lecture # 8 Constructors Overloading. Topics We will discuss the following main topics: – Static Class Members – Overloaded Methods – Overloaded Constructors.
1. 2 Reference... Student stu; Reference of Student stu When the reference is created it points to a null value. Before access the reference, objects.
Initialization & Cleanup Guaranteed initialization with the constructor The name of the constructor is the same as the name of the class.
Inheritance and Polymorphism Daniel Liang, Introduction to Java Programming.
More about Class 靜宜大學資工系 蔡奇偉副教授 ©2011. 大綱 Instance Class Members Class members can be associated with an instance of the class or with the class as a.
Constructors CMSC 202. Object Creation Objects are created by using the operator new in statements such as… The following expression invokes a special.
ECE122 Feb. 22, Any question on Vehicle sample code?
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.
Comp 248 Introduction to Programming Chapter 4 & 5 Defining Classes Part B Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.
Dale Roberts Object Oriented Programming using Java - Final and Static Keywords Dale Roberts, Lecturer Computer Science, IUPUI
Rina System development with Java Instructors: Rina Zviel-Girshin Lecture 4.
COP3502 Programming Fundamentals for CIS Majors 1 Instructor: Parisa Rashidi.
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.
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.
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.
1 Chapter 3 – Object-Based Programming 2 Initializing Class Objects: Constructors Class constructor is a specical method to initialise instance variables.
Programming With Java ICS201 University Of Ha’il1 Chapter 7 Inheritance.
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 ◦
Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
Classes Methods and Properties. Introduction to Classes and Objects In object-oriented programming terminology, a class is defined as a kind of programmer-defined.
More on Objects Mehdi Einali Advanced Programming in Java 1.
1 Static Variable and Method Lecture 9 by Dr. Norazah Yusof.
Topics Instance variables, set and get methods Encapsulation
Object-Oriented Programming and Problem Solving Dr. Ramzi Saifan Introduction and basics of Java Slides adapted from Steven Roehrig.
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.
28-Dec-04polymorhism.ppt1 Polymorphism. 28-Dec-04polymorhism.ppt2 signatures in any programming language, a signature is what distinguishes one function.
Object Based Programming Chapter 8. 2 Contrast ____________________ Languages –Action oriented –Concentrate on writing ________________ –Data supports.
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
Object Oriented Programming
Object Oriented Programming in java
Assessment – Java Basics: Part 1
Basics of OOP A class is the blueprint of an object.
Object Oriented Programming in java
Fundamental OOP Programming Structures in Java: Comments, Data Types, Variables, Assignments, Operators.
In this class, we will cover:
Chapter 7 Objects and Classes
Presentation transcript:

Initialization & Cleanup Dr. Ramzi Saifan Slides adapted from Prof. Steven Roehrig

What Needs to be Initialized?  A name for a student  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 (Wash the car? Wash the shirt? Wash the dog? …. etc)  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  If 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.  Static methods cannot use this keyword.  You can’t access non-static methods or variable from within a static method. They must use an object reference.  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, it is garbage and will be removed from memory.

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

Final  Means that the value cannot be modified  If a variable was defined as final, its initialization should be either in: The Definition statement Or, in each constructor  Final static: like defining a constant in C++. It should be initialized on definition time.

Add toString() to Class A class A { int i; int j; public String toString() { return new String(“I = " + i + “, j = “ + j); //Or // return “” + i; // but not: // 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); }