Java Object-Oriented Programming: Classes, Objects, Constructors, and Static Variables, Lecture notes of Web Design and Development

A review of object-oriented programming (oop) concepts in java, including classes as blueprints for user-defined datatypes, objects as instances of classes, constructors for initializing objects, and static variables and methods associated with the class itself.

Typology: Lecture notes

2011/2012

Uploaded on 11/10/2012

taariq
taariq 🇵🇰

4.4

(16)

61 documents

1 / 12

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
Handout 4-1
Web Design & Development CS-506
- 38 -
Object Oriented Programming
Java is fundamentally object oriented. Every line of code you write in java must be inside
a class (not counting import directives). OOP fundamental stones Encapsulation,
Inheritance and Polymorphism etc. are all fully supported by java.
OOP Vocabulary Review
Classes
Definition or a blueprint of a userdefined datatype
Prototypes for objects
Think of it as a map of the building on a paper
Objects
Nouns, things in the world
Anything we can put a thumb on
Objects are instantiated or created from class
Constructor
A special method that is implicitly invoked. Used to create an Object (that is,
an Instance of the Class) and to initialize it.
Attributes
Properties an object has
Methods
Actions that an object can do
pf3
pf4
pf5
pf8
pf9
pfa

Partial preview of the text

Download Java Object-Oriented Programming: Classes, Objects, Constructors, and Static Variables and more Lecture notes Web Design and Development in PDF only on Docsity!

Web Design & Development CS-

Object Oriented Programming

Java is fundamentally object oriented. Every line of code you write in java must be inside a class (not counting import directives). OOP fundamental stones Encapsulation, Inheritance and Polymorphism etc. are all fully supported by java.

OOP Vocabulary Review

  • Classes
    • Definition or a blueprint of a userdefined datatype
    • Prototypes for objects
    • Think of it as a map of the building on a paper
  • Objects
    • Nouns, things in the world
    • Anything we can put a thumb on
    • Objects are instantiated or created from class
  • Constructor
    • A special method that is implicitly invoked. Used to create an Object (that is, an Instance of the Class) and to initialize it.
  • Attributes
    • Properties an object has
  • Methods
    • Actions that an object can do

Web Design & Development CS-

Defining a Class

Comparison with C++

Some important points to consider when defining a class in java as you probably noticed from the above given skeleton are

  • There are no global variables or functions. Everything resides inside a class. Remember we wrote our main method inside a class. (For example, in HelloWorldApp program)
  • Specify access modifiers (public, private or protected) for each member method or data members at every line. - public: accessible anywhere by anyone - private: Only accessible within this class - protect: accessible only to the class itself and to it’s subclasses or other classes in the same package. - default: default access if no access modifier is provided. Accessible to all classes in the same package.
  • There is no semicolon (;) at the end of class.
  • All methods (functions) are written inline. There are no separate header and implementation files.
  • Automatic initialization of class level data members if you do not initialize them ƒ Primitives o Numeric (int, float etc) with zero

inastance variables and symbolic constants

constructor – how to create and initialize objects

methods – how to manipulate those objects (may or may not include its own “driver”, i.e., main( ))

class Point {

private int xCord; private int yCord;

public Point (……) {……}

public void display (……) { ………. }

} //end of class

Web Design & Development CS-

Task – Defining a Student class

The following example will illustrate how to write a class. We want to write a “Student” class that

  • should be able to store the following characteristics of student
    • Roll No
    • Name
  • Provide default, parameterized and copy constructors
    • Provide standard getters/setters (discuss shortly) for instance variables
      • Make sure, roll no has never assigned a negative value i.e. ensuring the correct state of the object
      • Provide print method capable of printing student object on console

Getters / Setters

The attributes of a class are generally taken as private or protected. So to access them outside of a class, a convention is followed knows as getters & setters. These are generally public methods. The words set and get are used prior to the name of an attribute. Another important purpose for writing getter & setters to control the values assigned to an attribute.

Student Class Code

// File Student.java public class Student { private String name; private int rollNo; // 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 public String getName ( ) { return name; }

Web Design & Development CS-

public int getRollNo ( ) { return rollNo; }

// Default Constructor public Student() { name = “not set”; rollNo = 100; }

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

// Copy Constructor for a new student public Student(Student s) { name = s.name; rollNo = s.rollNo; }

// method used to display method on console

public void print () { System.out.print("Student name: " +name); System.out.println(", roll no: " +rollNo); }

} // end of class

Web Design & Development CS-

s2.setName("usman"); s2.setRollNo(20);

System.out.print("Student name:" + s2.getName()); System.out.println(" rollNo:" + s2.getRollNo());

System.out.println("calling copy constructor"); Student s3 = new Student(s2); //call to copy constructor

s2.print(); s3.print();

s3.setRollNo(-10); //Roll No of s3 would be set to 100

s3.print();

/*NOTE: public vs. private A statement like "b.rollNo = 10;" will not compile in a client of the Student class when rollNo is declared protected or private */

} //end of main } //end of class

Compile & Execute

Compile both classes using javac commad. Run Test class using java command.

Web Design & Development CS-

More on Classes

Static

A class can have static variables and methods. Static variables and methods are associated with the class itself and are not tied to any particular object. Therefore statics can be accessed without instantiating an object. Static methods and variables are generally accessed by class name.

The most important aspect of statics is that they occur as a single copy in the class regardless of the number of objects. Statics are shared by all objects of a class. Non static methods and instance variables are not accessible inside a static method because no this reference is available inside a static method.

We have already used some static variables and methods. Examples are

ƒ System. out .println(“some text”); -- out is a static variable ƒ JOptionPane. showMessageDialog (null, “some text”); -- showMessageDialog is a static method

Garbage Collection & Finalize

Java performs garbage collection and eliminates the need to free objects explicitly. When an object has no references to it anywhere except in other objects that are also unreferenced, its space can be reclaimed.

Before an object is destroyed, it might be necessary for the object to perform some action. For example: to close an opened file. In such a case, define a finalize() method with the actions to be performed before the object is destroyed.

finalize

When a finalize method is defined in a class, Java run time calls finalize() whenever it is about to recycle an object of that class. It is noteworthy that a garbage collector reclaims objects in any order or never reclaims them. We cannot predict and assure when garbage collector will get back the memory of unreferenced objects.

The garbage collector can be requested to run by calling System.gc() method. It is not necessary that it accepts the request and run.

Web Design & Development CS-

// gettter of static countStudents variable public static int getCountStudents(){ return countStudents; }

// Default Constructor public Student() { name = “not set”; rollNo = 100; countStudents += 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 countStudents += 1; }

// Copy Constructor for a new student public Student(Student s) { name = s.name; rollNo = s.rollNo; countStudents += 1; }

// method used to display method on console public void print () { System.out.print("Student name: " +name); System.out.println(", roll no: " +rollNo); }

// overriding toString method of java.lang.Object class public String toString(){ return “name: ” + name + “ RollNo: ” + rollNo; }

// overriding finalize method of Object class public void finalize(){ countStudents -= 1; }

} // end of class

Next, we’ll write driver class. After creating two objects of student class, we deliberately loose object’s reference and requests the JVM to run garbage collector to reclaim the memory. By printing countStudents value, we can confirm that. Coming up code is of the Test class.

Web Design & Development CS-

// File Test.java

public class Test{

public static void main (String args[]){

int numObjs;

// printing current number of objects i.e 0 numObjs = Student.getCountStudents(); System.out.println(“Students Objects” + numObjects);

// Creating first student object & printing its values Student s1 = new Student("ali", 15); System.out.println(“Student: ” + s1.toString());

// printing current number of objects i.e. 1 numObjs = Student.getCountStudents(); System.out.println(“Students Objects” + numObjects);

// Creating second student object & printing its values Student s2 = new Student("usman", 49);

// implicit call to toString() method System.out.println(“Student: ” + s2);

// printing current number of objects i.e. 2 numObjs = Student.getCountStudents(); System.out.println(“Students Objects” + numObjects);

// loosing object reference s1 = null

// requesting JVM to run Garbage collector but there is // no guarantee that it will run System.gc();

// printing current number of objects i.e. unpredictable numObjs = Student.getCountStudents(); System.out.println(“Students Objects” + numObjects);

} //end of main } //end of class