6 Classes in Java — Java Programming
6.1 Introduction
6.2 A class
A class is a template for an object. Classes gather methods that provide functionality for objects. An object is an instance of the class. The data or variables defined within a class are called members of the class. The class usage and definition of class is similar to its definition in C++.
6.2.1 A simple class
A class definition with three variables is given below.
class student{ //class name int rollno; //class member float marks1, marks2; //class members }
6.2.2 The constructor
To create a student object named student_1, call the constructor student().
student student_1=new student(); //new creates, student() constructs
An object like student_1 is a class variable.
A constructor is a special member function for automatically creating an instance of a class. The function has the same name as class. To use an object in Java, we should first create the object and make a variable refer to the object. The new command is used to create objects. In addition, we should construct the object we are creating. A constructor is a method used to create new objects that initializes the values of the object. For example, Assume we have a class of objects Sample_date representing dates, with corresponding year, month and day. Hence, the constructor needs three values as shown below.
Sample_date date=new Sample_date(1999,12,1);
The parameters are given within the brackets. We should refer to the class documentation or the class definition if information about parameters become necessary. A few constructors like student() as given above may have no parameters at all.
Program 6.1 Program to define student and calculate the student’s total marks.
//studClass.java //Click here for code class student { int rollno; float marks1, marks2; } class studClass{ public static void main(String args[]) { student student1=new student(); student student2=new student(); float total; student1.marks1=82; student2.marks2=79; total=student1.marks1+student2.marks2; System.out.println("total marks="+total); } } //Output: total marks=161.0
A constructor defines the action to be done when an object of a class is created. If no explicit constructor is specified then Java will automatically supply a default constructor. This is the case with student class. Runtime Exception occurs if new is unable to allocate memory. The difference between class and object is that a class creates a new data type that can be used to create objects. That is, a class creates a logical framework that defines the relationship between its members. When we declare an object of a class, we are creating an instance of that class. Thus, a class is a logical constant. An object has physical reality (object occupies space in memory).
student student1=new student(); //create student1 object using a constructor student student2 student1; // create a student2 object using variable declaration student1=null; // we make the object refer to null.
In the above code fragment student1 is null but student2 still holds the information about student1 object’s previous values. When we assign one object reference to another object variable, we are not creating a copy of the object we are only making the copy of reference.
6.2.3 Methods
A method is a function. Consider the following code.
static int xyz(int a) { return; }
Here static is a modifier, int is a return type, xyz is method name, a is of type int and is an argument.
Program 6.2 Implementing Stack.
//stackDemo.java //click here for code import java.io.*; public class stackDemo { int a[]=new int[20]; int top; public stackDemo() { top=0;} public void push(int x) { if(top==20) { System.out.println("Stack overflow"); System.exit(1); } else { top++; a[top]=x; } } public int pop() { int x=0; if(top==0) { System.out.println("Stack empty"); System.exit(1); } else { x=a[top]; top--; } return x; } public boolean isempty() { if(top==0) return true; else return false; } public int stacktop() { if(top==0) System.out.println("Stack empty"); return (a[top]); } public static void main(String args[]) { stackDemo s; int n,p; s=new stackDemo(); try { DataInputStream in; in=new DataInputStream(System.in); System.out.println("enter the number of elements to be inserted(<20)"); String k=in.readLine(); n=Integer.parseInt(k); System.out.println("enter the elements of stack"); for(int i=0;i<n;i++) { k=in.readLine(); p=Integer.parseInt(k); s.push(p); } } catch(Exception e) { System.out.println("I/O error"+e); System.exit(1); } while(!s.isempty()) { System.out.println("popping the element from stack"); System.out.println(s.pop()); } } }
/* Output: enter the number of elements to be inserted(<20) 5 enter the elements of stack 1 2 3 4 5 popping the element from stack 5 popping the element from stack 4 popping the element from stack 3 popping the element from stack 2 popping the element from stack 1
*/
6.3 Modifiers
The modifiers in Java are
a. public
b. protected
c. private
d. static
e. final
public: The variables and methods declared public can be accessed by any class in any package. Methods declared public are accessible to all.
protected: protected variables or methods can be accessed by any class in the same package as the declaring class or any subclass of the declaring class even if it is in a different package. Package is a collection of classes grouped together.
private: These variables or methods of a class can be accessed only by the methods declared in that class.
static: If variables or methods are to be constant we define them to be static. Static methods cannot be overloaded. Only static methods can access static variables.
final: Variables or methods cannot be overloaded or changed. These are actually constants.
Program 6.3 Program to demonstrate creating objects and using of member functions.
//studCreate.java //Click here for code class student{ int rollno; float marks1,marks2; float total() { return(marks1+marks2); } } class studentCreate{ public static void main(String args[]) { float totalmarks; //one student with rollno=25, marks=81, marks2=85 is created student student1=new student(); student1.rollno=25; student1.marks1=81; student1.marks2=85; //second student with rollno=26, marks=80. marks2=95 is created student student2=new student(); student2.rollno=26; student2.marks1=80; student2.marks2=95; //calculate marks of student1 by calling total() of student class totalmarks=student1.total(); System.out.println("total marks="+ totalmarks); //claculate marks of student2 by calling total() of student class totalmarks=student2.total(); System.out.println("total marks="+totalmarks); } } /*Output: total marks=166.0 total marks=175.0 */
Program 6.4 Program to experiment reading input and sorting list of students based on marks
//Program to create 'n' students, read their marks and calculate percentages and print them in descending order of their marks percentage. //student.java import java.io.*; public class student { String name; int regdno, s1, s2; float totalper; public student() { name=""; regdno=0; s1=0; s2=0; totalper=0; } public void copy(student ob) { name =ob.name; regdno=ob.regdno; s1=ob.s1; s2=ob.s2; totalper=ob.totalper; } public void getdata() { try { DataInputStream in; in=new DataInputStream(System.in); String s; System.out.println("Enter the student name:"); name=in.readLine(); System.out.println("Enter the student regdno:"); s=in.readLine(); regdno=Integer.parseInt(s); System.out.println("Enter the student marks(m1,m2) out of 100:"); s=in.readLine(); s1=Integer.parseInt(s); s=in.readLine(); s2=Integer.parseInt(s); totalper=((s1+s2)/2); } catch(Exception e) { System.out.println("I/O error"+e); System.exit(1); } } public static void main(String args[]) { student st[]=new student[10]; int n=0; try { DataInputStream in; in=new DataInputStream(System.in); System.out.println("Enter the number of students:"); String s = in.readLine(); n=Integer.parseInt(s); } catch(Exception e) { System.out.println("I/O error"+e); System.exit(1); } for(int i=0;i<n;i++) { st[i]=new student(); st[i].getdata(); } student t=new student(); for(int i=1;i<n;i++) for(int j=0;j<n-i;j++) if(st[j].totalper<st[j+1].totalper) { t=st[j]; st[j]=st[j+1]; st[j+1]=t; } for(int i=0;i<n;i++) { System.out.println(st[i].name+","+st[i].regdno+","+st[i].totalper); } } } /* Output Enter the number of students: 3 Enter the student name: Valli Enter the student regdno: 1001 Enter the student marks(m1,m2) out of 100: 85 78 Enter the student name: Siva Enter the student regdno: 1002 Enter the student marks(m1,m2) out of 100: 89 87 Enter the student name: Phani Enter the student regdno: 1003 Enter the student marks(m1,m2) out of 100: 98 88 Phani,1003,93.0 Siva,1002,88.0 Valli,1001,81.0 */
6.4 this keyword
The keyword this can be used inside any method to refer to the current object.
public class example{ int i; public myexample() { i=10; this.i=2; } }
If an object of class example is created, this.i refers to variable i of current object.
6.5 Garbage collector
We allocated memory to objects using new operator. In other language we de-allocate memory using delete operator or equivalent, but Java handles de-allocate automatically. This technique is known as Garbage collection. The essential thing is that the programmer doesn’t have to worry about as Java runtime system has got its own ways of accomplishing it.
6.6 finalize()
Sometimes an object before getting destroyed should perform some action. This is done using finalize() method. Simply add finalize() method to the necessary classes and write your code in this method. Note that finalize() is approximately similar to destructor function of C++.
6.7 static methods
If we are sure that we need object independent method, Java permits us to create static methods (class methods). Such methods are associated with particular classes, but do not require the creation of objects to use them.
For example, all the main methods we have been creating so far are static methods. Java’s main is static, so we do not create new object in order to run it. We execute the class and we actually tell Java virtual machine to call this main method of a class
6.8 Summary
You were introduced with classes, modifiers, garbage collection, method functions, and data members and clean up function in this chapter.