Download Java Object-Oriented Programming: Classes, Objects, Constructors, and Static Variables and more Lecture notes Web Design and Development in PDF only on Docsity! 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 Handout 4-1 Web Design & Development CS-506 - 39 - 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 Handout 4-1 Web Design & Development CS-506 - 42 - 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 Handout 4-1 Web Design & Development CS-506 - 43 - 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 Handout 4-1 Web Design & Development CS-506 - 44 - 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. Handout 4-2 Web Design & Development CS-506 - 47 - // 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. Handout 4-2 Web Design & Development CS-506 - 48 - // 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 Handout 4-2 Web Design & Development CS-506 - 49 - 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.