ZeePedia buy college essays online


Web Design and Development

<<< Previous JAVA: Object Oriented Programming Next >>>
 
img
Web Design & Development ­ CS506
VU
Lesson 4
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 user-defined 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
Defining a Class
class
Point {
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)
23
img
Web Design & Development ­ CS506
VU
­
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
o  Char with null
o  Boolean with false
Object References
­  With null
Note: Remember, the same rule is not applied to local variables (defined inside method
body). Using a local variable without initialization is a compile time error
Public void someMethod( ) {
int x; //local variable
System.out.println(x); // compile time error
}
­
Constructor
­
Same name as class name
­
Does not have a return type
­
No initialization list
­
JVM provides a zero argument (default) constructor only if a class doesn't define it's
own constructor
­
Destructors
­  Are not required in java class because memory management is the responsibility
of JVM.
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
24
img
Web Design & Development ­ CS506
VU
­
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;
}
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) {
25
img
Web Design & Development ­ CS506
VU
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
Using a Class
Objects of a class are always created on heap using the "new" operator followed by constructor
·
Student s = new Student ( ); // no pointer operator "*" between Student and s
·
Only String constant is an exception
String greet = "Hello" ;  // No new operator
·
However you can also use
String greet2 = new String("Hello");
Members of a class ( member variables and methods  also known as instance
variables/methods ) are accessed using "." operator. There is no "Ę" operator in java
s.setName("Ali");
sĘsetName("Ali") is incorrect and will not compile in java
Note: Objects are always passed by reference and primitives are always passed by value in java.
Task - Using Student Class
Create objects of student class by calling default, parameterize and copy constructor
Call student class various methods on these objects
Student client code
// File Test.java
/* This class create Student class objects and demonstrates
how to call various methods on objects
*/
public class Test{
public static void main (String args[]){
// Make two student obejcts
Student s1 = new Student("ali", 15);
Student s2 = new Student(); //call to default costructor
s1.print(); // display ali and 15
s2.print(); // display not set and 100
26
img
Web Design & Development ­ CS506
VU
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.
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
27
img
Web Design & Development ­ CS506
VU
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.
Example Code: using static & finalize ()
We want to count exact number of objects in memory of a Student class the one defined earlier. For
this purpose, we'll modify Student class.
Add a static variable countStudents that helps in maintaining the count of student objects.
Write a getter for this static variable. (Remember, the getter also must be static one. Hoping
so, you know the grounds).
In all constructors, write a code that will increment the countStudents by one.
Override finalize() method and decrement the countStudents variable by one.
Override toString() method.
Class Object is a superclass (base or parent) class of all the classes in java by default. This class has
already finalize() and toString() method (used to convert an object state into string). Therefore we are
actually overriding these methods over here. (We'll talk more about these in the handout on
inheritance).
By making all above modifications, student class will look like
// File Student.java
public class Student {
28
img
Web Design & Development ­ CS506
VU
private String name;
private int rollNo;
private static int countStudents = 0;
// 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;
}
public int getRollNo ( ) {
return rollNo;
}
// 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);
29
img
Web Design & Development ­ CS506
VU
}
// 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.
// 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();
30
img
Web Design & Development ­ CS506
VU
// printing current number of objects i.e. unpredictable
numObjs = Student.getCountStudents();
System.out.println("Students Objects" + numObjects);
} //end of main
} //end of class
The compilation and execution of the above program is given below. Note that output may be
different one given here because it all depends whether garbage collector reclaims the memory or
not. Luckily, in my case it does.
Reference:
Sun java tutorial: http://java.sun.com/docs/books/tutorial/java
Thinking in java by Bruce Eckle
Beginning Java2 by Ivor Hortan
Example code, their explanations and corresponding execution figures for this handout are
taken from the book JAVA A Lab Course by Umair Javed. This material is available just for
the use of VU students of the course Web Design and Development and not for any other
commercial purpose without the consent of author.
31