Presentation is loading. Please wait.

Presentation is loading. Please wait.

Lecture 6 Object Oriented Programming Using Java

Similar presentations


Presentation on theme: "Lecture 6 Object Oriented Programming Using Java"— Presentation transcript:

1 Lecture 6 Object Oriented Programming Using Java
By Rashid Ahmad Department of Computer Science University of Peshawar

2 Finalize Method and Garbage Collection
Each object you create uses various system resources, such as memory. To avoid resource leaks we need a disciplined way to give resources back to the system. The JVM performs automatic garbage collection to reclaim the memory occupied by objects that are no longer in use. Memory leaks are supposed to occur less times in Java. Finalize Method and Garbage Collection

3 Where to use static variables?
Static Class Members A static variable represents class-wide information. That is, all objects of the class share the same piece of data. The declaration of the static variable starts with the (static) keyword. Where to use static variables?

4 Static Members Example
public class Employee { private String firstName; private String lastName; private static int count = 0; public Employee(String first, String last){ firstName = first; lastName = last; count++; System.out.printf("Employee Constructor: %s %s; count = %d\n", firstName, lastName, count); } Employee Class

5 Static Members Example
protected void finalize(){ count--; System.out.printf("Employee finalizer: %s %s: count = %d\n", firstName, lastName, count); } public String getFirstName(){ return firstName; public String getLastName(){ return lastName; public static int getCount(){ return count; Employee Class

6 Static Members Example
public class StaticExample { public static void main(String[] args) { System.out.printf("Employee before instanstiation: %d\n", Employee.getCount()); Employee e1 = new Employee("Aslam","Khan"); Employee e2 = new Employee("Muhammad","Salman"); System.out.println("\nEmployee after instanstiation: "); System.out.printf("via e1.getCount(): %d\n", e1.getCount()); System.out.printf("via e2.getCount(): %d\n", e2.getCount()); System.out.printf("via Employee.getCount(): %d\n", Employee.getCount()); Main Class

7 Static Members Example
System.out.printf("\nEmployee 1: %s %s\nEmployee 2: %s %s\n\n", e1.getFirstName(), e1.getLastName(), e2.getFirstName(), e2.getLastName()); e1 = null; e2 = null; System.gc(); System.out.printf("\nEmployee after Garbage Collection: %d\n", Employee.getCount()); } Main Class


Download ppt "Lecture 6 Object Oriented Programming Using Java"

Similar presentations


Ads by Google