Static, Final & Memory Management

Similar documents
Object Oriented Programming

Lec 1-13 HAND OUTS WEB DESIGN AND DEVELOPMENT

Web Design & Development CS506

AP Computer Science Chapter 10 Implementing and Using Classes Study Guide

What is Inheritance?

CMSC 132: Object-Oriented Programming II

Day 3. COMP 1006/1406A Summer M. Jason Hinek Carleton University

CMSC131. Creating a Datatype Class Continued Exploration of Memory Model. Reminders

Lecture 3. COMP1006/1406 (the Java course) Summer M. Jason Hinek Carleton University

Example: Fibonacci Numbers

Inheritance Motivation

Inheritance. Inheritance allows the following two changes in derived class: 1. add new members; 2. override existing (in base class) methods.

Java How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved.

TOPIC 12 CREATING CLASSES PART 1

CS-202 Introduction to Object Oriented Programming

CONSTRUCTOR & Description. String() This initializes a newly created String object so that it represents an empty character sequence.

Programming II (CS300)

PIC 20A The Basics of Java

C08: Inheritance and Polymorphism

Object Oriented Programming is a programming method that combines: Advantage of Object Oriented Programming

CmSc 150 Fundamentals of Computing I. Lesson 28: Introduction to Classes and Objects in Java. 1. Classes and Objects

(12-1) OOP: Polymorphism in C++ D & D Chapter 12. Instructor - Andrew S. O Fallon CptS 122 (April 3, 2019) Washington State University

Chapter 6 Introduction to Defining Classes

LECTURE 2 (Gaya College of Engineering)

JAVA GUI PROGRAMMING REVISION TOUR III

Create a Java project named week10

Java: Classes. An instance of a class is an object based on the class. Creation of an instance from a class is called instantiation.

CMSC 132: Object-Oriented Programming II

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub

COP 3330 Final Exam Review

COMP 250 Winter 2011 Reading: Java background January 5, 2011

CS1004: Intro to CS in Java, Spring 2005

Selected Questions from by Nageshwara Rao

Programming II (CS300)

3.Constructors and Destructors. Develop cpp program to implement constructor and destructor.

Lecture 02, Fall 2018 Friday September 7

Recursion 1. Recursion is the process of defining something in terms of itself.

CMSC131. Objects: Designing Classes and Creating Instances

Software and Programming 1

Programming II (CS300)

7. C++ Class and Object

Classes and Objects 3/28/2017. How can multiple methods within a Java class read and write the same variable?

Distributed Systems Recitation 1. Tamim Jabban

Introduction to Programming Using Java (98-388)

CSC1322 Object-Oriented Programming Concepts

Binghamton University. CS-140 Fall Problem Solving. Creating a class from scratch

CA341 - Comparative Programming Languages

And Even More and More C++ Fundamentals of Computer Science

CS 1331 Exam 1 ANSWER KEY

Exercise: Singleton 1

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

User Defined Classes. CS 180 Sunil Prabhakar Department of Computer Science Purdue University

20 Most Important Java Programming Interview Questions. Powered by

INHERITANCE. Spring 2019

Chapter 12. OOP: Creating Object-Oriented Programs The McGraw-Hill Companies, Inc. All rights reserved. McGraw-Hill

Instance Members and Static Members

Exercises Software Development I. 08 Objects II. Generating and Releasing Objects (Constructors/Destructors, this, Object cloning) December 3rd, 2014

Java Fundamentals (II)

Chapter 4 Java Language Fundamentals

Abstract Classes. Abstract Classes a and Interfaces. Class Shape Hierarchy. Problem AND Requirements. Abstract Classes.

An Introduction to C++

Chapter 10. Class & Objects in JAVA. By: Deepak Bhinde PGT Com.Sc.

Java Object Oriented Design. CSC207 Fall 2014

This Week. Fields and Variables. W05 Example 1: Variables & Fields. More on Java classes. Constructors. Modifiers

Unit 5: More on Classes/Objects Notes

Day 4. COMP1006/1406 Summer M. Jason Hinek Carleton University

Assumptions. History

Object Oriented Design

CS100J, Fall 2003 Preparing for Prelim 1: Monday, 29 Sept., 7:30 9:00PM

CSC 1214: Object-Oriented Programming

Note: Each loop has 5 iterations in the ThreeLoopTest program.

CS1020: DATA STRUCTURES AND ALGORITHMS I

Lesson 10A OOP Fundamentals. By John B. Owen All rights reserved 2011, revised 2014

Data Structures (list, dictionary, tuples, sets, strings)

Lecture 4: Extending Classes. Concept

Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur

5.6.1 The Special Variable this

C10: Garbage Collection and Constructors

OBJECT ORIENTED PROGRAMMING USING C++ CSCI Object Oriented Analysis and Design By Manali Torpe

Programming - 2. Common Errors

Object-Oriented Design Lecture 3 CSU 370 Fall 2007 (Pucella) Friday, Sep 14, 2007

Object Oriented Programming

CS 231 Data Structures and Algorithms, Fall 2016

Distributed Systems Recitation 1. Tamim Jabban

CS360 Lecture 5 Object-Oriented Concepts

Brief Summary of Java

EEE-425 Programming Languages (2013) 1

Islamic University of Gaza Faculty of Engineering Computer Engineering Department

Chapter 4: Writing Classes

Informatik II (D-ITET) Tutorial 6

COMSC-051 Java Programming Part 1. Part-Time Instructor: Joenil Mistal

Lecture 36: Cloning. Last time: Today: 1. Object 2. Polymorphism and abstract methods 3. Upcasting / downcasting

Java. Classes 3/3/2014. Summary: Chapters 1 to 10. Java (2)

CS-140 Fall 2017 Test 1 Version Practice Practice for Nov. 20, Name:

1 Shyam sir JAVA Notes

Day 2. COMP 1006/1406A Summer M. Jason Hinek Carleton University

C11: Garbage Collection and Constructors

CS 1331 Exam 1. Fall Failure to properly fill in the information on this page will result in a deduction of up to 5 points from your exam score.

Software Development With Java CSCI

Week 3 Classes and Objects

Transcription:

Static, Final & Memory Management The static keyword What if you want to have only one piece of storage regardless of how many objects are created or even no objects are created? What if you need a method that isn t associated with any particular object of the class? That is, you need a method that you can call even no objects are created The static keyword comes into play for solving the above sated problem. When you use static with something (data or method), the data or method is not tied to any particular object. Class Variables The declaration of a data member inside the class using the static keyword results in a class variable. There is only one copy of the class variables exist in the memory. One of the significant things about the class variables is that all instances (objects) of the class share the class variables. It is not necessary to instantiate an object of a class to access class variables as it happens with the case of instance variables (To access an instance variable, you need an object). Class variables are accessed using the name of the class and name of the class variable joined by the dot operator (.). However you can also access class variables using objects but this practice is generally avoided. Remember that since all objects of the class share the class variable, if any object modifies it, it is modified for all the objects of the class. Class Methods The declaration of a member method inside the class using the static keyword results in a class method. This resulted in one copy of the static method for class. Same as with the class variables, class methods can be invoked (call) without a requirement to instantiate an object of the class. Class methods similarly to class variables are accesses by class name or object of the class but the later approach is avoided generally. Dot operator is used for accessing class methods on the same pattern of class variables. Umair 2006, All Rights Reserved - 1 - TA: Munawar Nadeem

Example We have a student class with static variable countstudents and static method getcountstudents. The non-static members include name, roll no, getter/setter and tostring method. Suppose that we create two objects of Student class than memory picture look like one given below. Note that there is only one copy of static members. Object: ali Type: Student Name: ali raza Roll No: 5 Methods: getname, setname getrollno, setrollno tostring Class: Student countstudents: 2 Method: getcountstudents() Object: usman Type: Student Name: usman shahid Roll No: 5 Methods: getname, setname getrollno, setrollno tostring Points to Remember Occurs as a single copy in the class regardless of how many objects are created Static (class) variables & methods are not associated with the object, they belong to class They exist prior the creation of any object A static method have no this reference as they belong to class and this belongs to objects The static method can only access static members (variables + methods) and cannot access non-static members(instance variables + member methods) of a class Umair 2006, All Rights Reserved - 2 - TA: Munawar Nadeem

Memory Management Java manages the memory itself and performs the garbage collection and eliminates the need to free objects explicitly as it happened with C++. When an object has no references to it anywhere except in other objects that are also unreferenced, its space can be reclaimed. Before the object is destroyed, it might be necessary for the object to perform some actions. For example, to close an opened file. How the programmer can make sure that necessary tasks would be performed before its (object) memory reclaimed by the garbage collector. finalize ( ) method The finalize method comes into picture for solving the above mentioned problem. Define a finalize method inside a class and write any clean up code like closing a connection inside it. You can never call it directly. Java ensures that finalize method must be called before any object s occupied memory is reclaimed. A garbage collector reclaims objects in any order and we can not predict when the garbage collector will free the memory. System.gc() However, we can request to JVM to run the garbage collector to reclaim unreferenced memory. But remember, it s a request, it doest not guaranteed that garbage collector will run. Finalize is Not Destructor C++ programmers should take into an account that finalize method in java is not a destructor. The destructor in C++, if exists, is always invoked when the object goes out of scope (as it is done by using the delete operator to return the memory back to the system). Freeing the memory is the programmer responsibility. Even though, the finalize method is always invoked before the garbage collector reclaims memory in java, but we doesn t specify/use any such delete operation as it is the responsibility of garbage collector. We only can write any clean up code into it. The job of freeing the memory is taken away from the programmer Umair 2006, All Rights Reserved - 3 - TA: Munawar Nadeem

Example Code We make some modifications to our Student class defined in the last handout. This example code demonstrates the usage of static and finalizes method. The changes made in Student class are highlighted as bold. A static variable countstudensts is added to the class with its getter method, to keep track of how many objects currently reside in the memory. In this class, tostring and finalize methods are overridden as they are present in the Object class and in java every class by default inherits from Object class. Inheritance and overriding are going to be discussed in greater detail in coming handouts Student Class Code // File Student.java /* Demonstrates the most basic features of a class. A student is defined by their name and rollno. There are standard getter/setters for name and rollno. */ NOTE A well documented class should include an introductory comment like this. Don't get into all the details just introduce the landscape. public class Student { private String name; private int rollno; private static int countstudents = 0; public staic int getcountstudents ( ) { Return countstudents; // Standard Setters public void setname (String name) { this.name = name; // Note the masking of class level variable rollno public void setrollno (int rollno) { if (rollno > 0) { this.rollno = rollno; else { this.rollno = 100; // Standard Getters Umair 2006, All Rights Reserved - 4 - TA: Munawar Nadeem

public String getname ( ) { return name; public int getrollno ( ) { return rollno; // Default Constructor public Student() { name = not set ; rollno = 100; countstudnets + = 1; // parameterized Constructor for a new student public Student(String name, int rollno) { setname(name); //call to setter of name setrollno(rollno); //call to setter of rollno countstudnets + = 1; // Copy Constructor for a new student public Student(Student s) { name = s.name; rollno = s.rollno; countstudnets + = 1; // method used to display method on console public void print () { System.out.println("Student name:" +name+); System.out.println(", roll no:" +rollno); // Overridden methods // Overriding tostring method of class java.lang.object public String tostring () { return ("name: "+name + "RollNo: " + rollno); //Overriding finalize method of Object class protected void finalize () { countstudents -= 1; // end of class Umair 2006, All Rights Reserved - 5 - TA: Munawar Nadeem

Client Code or Driver Program // File Test.java public class Test{ public static void main (String args[]){ int numobjs; numobjs = Student.getCountStudents(); System.out.println("Students Objects:"+numObjs); Student s1 = new Student("ali", 15); System.out.println("Student:" + s1.tostring() ); numobjs = Student.getCountStudents(); System.out.println("Students Objects:"+numObjs); Student s2 = new Student("usman", 49); //implicit call to tostring() System.out.println("Student:" +s2); numobjs = Student.getCountStudents(); System.out.println("Students Objects:"+numObjs); s1 = null; // request the JVM to run the garbage collector But there is // no gaurantee that garbage collector will run System.gc(); numobjs = Student.getCountStudents(); System.out.println("Students Objects:"+numObjs); //end of main //end of class Compile & Execute Compile both classes using javac command. Run Test class more than once using java command to figure out the difference in outputs because we never know, garbage collector will run or not in this turn. Umair 2006, All Rights Reserved - 6 - TA: Munawar Nadeem

The final keyword Some instance variables need to be modified and some do not. Such variables are known as constants (Constants variables, once declared + initialized, their values cannot be modified later in any part of the program). In java, keyword final is used to achieve the above stated effects. The programmer may use the keyword final to specify that a variable is not modifiable (constant) and that any attempt made to modify final variable results in compile time error. The final variables must be initialized at the time of their declaration or in every constructor of the class. Declaring final Variable The following snippet of code shows the both approaches of declaring and initializing final variables. // File FianlTest.java public class FinalTest { public final int INCREMENT = 5; public final int DECREMENT; // Default Constructor public FinalTest() { DECREMENT = 3; public usefinal( ) { int a = 2; a = a + INCREMENT; compile time error, can t modify constant //DECRMENT++; // end of class Note: It is strongly recommended to follow naming conventions. -------------------------- Umair 2006, All Rights Reserved - 7 - TA: Munawar Nadeem

References: Sun java tutorial: http://java.sun.com/docs/books/tutorial/java Java tutorial by Dick Baldwin: http://www.dickbaldwin.com/java Thinking in java by Bruce Eckle Umair 2006, All Rights Reserved - 8 - TA: Munawar Nadeem