OOP in java (Defining and using class)
- Java is fundamentally Object-Oriented
- Every line of code you write in Java must be inside a Class (not counting import directives)
- Clear use of
- Variables
- Methods
- Re-use through “packages”
- Modularity, Encapsulation, Inheritance, Polymorphism etc.
OOP Vocabulary Review
- Classes
- Definition or a blueprint of a userdefined datatype
- Prototypes for objects
- Objects
- Nouns, things in the world
- Constructor
- Given a Class, the way to create an Object (that is, an Instance of the Class) and initialize it
- Attributes
- Properties an object has
- Methods
- Actions that an object can do.
The Structure of Classes
class name {
declarations constructor definitions
method definitions } |
|
instance variables and symbolic constants | |
how to create and initialize objects | |
how to manipulate those objects (may or may not include its own “driver”, i.e., main( )) |
Defining a Class Comparison with C++
- Java gives you the ability to write classes or user-defined data types similar to the way C++ does, with a few differences
- Points to consider when defining a class
- There are no global variables or functions. Everything resides inside a class. Remember we wrote our main method inside a class
- Specify access modifiers (public, private or protected ) for each member method or data members at every line.
- No semicolon (;) at the end of class
- All methods (functions) are written inline. There are no separate header and implementation files.
- Points to consider when defining a class (cont)
- Access Modifiers
- public : Accessible anywhere by anyone
- Private : Only accessible within this class
- Protected : Accessible only to the class itself and to it’s subclasses or other classes in the same “package”
- Package : Default access if no access modifier is provided.
The Point Class
class Point {
private int x; private int y; public Point (……) {……} public void Display (……) { ………. } } |
|
instance variables and symbolic constants | |
how to create and initialize objects | |
how to manipulate those objects (may or may not include its own “driver”, i.e., main( )) |
Defining a Class Example
- Create a class for Student
- should be able to store the following characteristics of student
- Roll No
- Name
- should be able to store the following characteristics of student
- Provide default, parameterized and copy constructors
- Provide standard getters/setters 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:
- class Student requires.
- Attributes: Roll NO, NameMethods: constructors, getters/setters, print
Types of constructors
A constructor in Java is similar to a method that is invoked when an object of the class is created.
Unlike Java methods, a constructor has the same name as that of the class and does not have any return type. For example,
class Test {
Test()
{
// constructor body
}
}
Here, Test() is a constructor. It has the same name as that of the class and doesn’t have a return type.
Java No-Arg Constructors
Similar to methods, a Java constructor may or may not have any parameters (arguments). If a constructor does not accept any parameters, it is known as a no-argument constructor.
Java private no-arg constructor
Once a constructor is declared private, it cannot be accessed from outside the class. So, creating objects from outside the class is prohibited using the private constructor.
Here, we are creating the object inside the same class. Hence, the program is able to access the constructor. To learn more, visit Java Implement Private Constructor.
However, if we want to create objects outside the class, then we need to declare the constructor as public.
Java Parameterized Constructor
A Java constructor can also accept one or more parameters. Such constructors are known as parameterized constructors (constructor with parameters).
Java Default Constructor
If we do not create any constructor, the Java compiler automatically create a no-arg constructor during the execution of the program. This constructor is called default constructor.
Student Implementation Code
// Student.java
/* Demonstrates the most basic features of a class. A student is defined by their name and rollNo. There are standard get/set accessors 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;
// 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;
}
// Constructor that uses a default value instead of taking an argument.
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;
}
Task – Using Student Class
- Create objects of Student class by calling default, parameterized and copy constructors.
- Call Students class various methods on objects
public class Test{
public static void main (String args[]){
// Make two students
Student s1 = new Student(“ali”, 15);
Student s2 = new Student(); //call to default constructor
s1.print();
s2.print();
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 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
Static
- A class can have static
- Variables
- Methods
- Static variables and methods
- Are associated with the class itself!!
- Not associated with the object
- Therefore Statics can be accessed without instantiating an object!
- Generally accessed by class name
- Cannot refer to a non-static instance variable in a static method
- No this reference
Static Variable & Methods
- Occurs as a single copy in the class
- For example;
- System.out is a static variable
- JOptionPane.showInputDialog(String)
Garbage collection and 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 the object is destroyed, it might be necessary for the object to perform some actions.
- For example closing an open 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.
- protected void finalize()
- {
- // code
- }
- A garbage collector reclaims objects in any order or never reclaim them.
- System.gc()
- Request the JVM to run the garbage collector
- Not necessary it will run
Memory Management
public class Test{
public static void main|(String args[]){
Student s1 = new Student(“ali”);
Student s2 = new Student(“raza”);
s1= s2;
}
}
No Memory leakage in Java, Automatic Garbage Collection will take care of such scenarios
Modify Student Class
public class Student {
private static int countStudents = 0;
public static int getCountStudents() {
return countStudents;
}
// Constructor that uses a default value instead of taking an argument.
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;
}
// 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
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);
System.out.println(“Student:” +s2); //implicit call to toString()
numObjs = Student.getCountStudents();
System.out.println(“Students Objects:”+numObjs);
s1 = null;
System.gc(); // request the JVM to run the garbage collector But
// there is no gaurantee that garbage collector will run
numObjs = Student.getCountStudents();
System.out.println(“Students Objects:”+numObjs);
} //end of main
} //end of class
Learn More:
For solution, online support and query email us at .