R23 Ii-I Java - Ii Unit
R23 Ii-I Java - Ii Unit
UNIT II: Classes and Objects: Introduction, Class Declaration and Modifiers, Class Members, Declaration of
Class Objects, Assigning One Object to Another, Access Control for Class Members, Accessing Private Members
of Class, Constructor Methods for Class, Overloaded Constructor Methods, Nested Classes, Final Class and
Methods, Passing Arguments by Value and by Reference, Keyword this.
Methods: Introduction, Defining Methods, Overloaded Methods, Overloaded Constructor Methods, Class Objects
as Parameters in Methods, Access Control, Recursive Methods, Nesting of Methods, Overriding Methods,
Attributes Final and Static.
     Introduction:
  Java is a true and pure object-oriented programming language; therefore all Java
     programs must be encapsulated in classes.
  Objects are created through classes.
  Classes provide a mechanism for packing both data items and functions.
  In java, the data items are called fields and the “functions” are called “methods”.
    A class is a collection of related objects that share common properties and actions.
    Properties are represented by variables and actions are represented by methods.
    Classes are used to pack a group of data items and functions.
    In java, the data items are called fields and functions are called methods.
Defining a class:
    Once a class is defined, we can create any number of objects belonging to that class.
    In Java, Classes are defined by using the keyword “class”.                  Class Declaration in Java
                                                                              access_modifier class <class_name>
     Syntax :                                                                {
        class classname                                                           data member;
        {                                                                         method;
                                                                                  constructor;
               Member variable (or) Fields declaration;
                                                                                  nested class;
               Methods declaration;                                               interface;
        }                                                                    }
Fields Declaration:
    The variables which are declared inside a class are called fields. These variables are
also called instance variables, because they are created whenever an object of the class
is instantiated.
     Syntax: datatype var1,var2,………,var-n;
     Ex:     class Rectangle
                {
                        int length;
                        int width;
                }
        The class Rectangle contains two integer type instance variables. No memory space
     is reserved for these instance variables.
                                                                                       35 | P a g e
Example:-
// Java Program for class example
class Student                                                  Output :-
{ // data member (also instance variable)
  int id;
  String name;                                                 0
  public static void main(String args[])
  {                                                            null
    // creating an object s1 for Student class
       Student s1 = new Student();
       System.out.println(s1.id);
       System.out.println(s1.name);
    }
}
Creating Objects:
  An object is a block of memory that contains space to store instance variables.
       The process of creating objects to a class is known as Instantiation.
       In java objects are created by using a special operator called new.
       The new operator creates an object of the specified class and returns a reference to
        that object.
        Syntax 1:
                 Classname objname;  Reference creation
                 objname = new Classname( ); Memory Allocation
        Syntax 2:
Classname objname = new Classname ( );  Reference creation & Memory Allocation
Accessing Class Members:
        We cannot access the instance variables and methods directly from outside the
class. To access them from outside the class, we must use the concerned object and the
dot (.) operator.
Syntax:          Objectname.variablename;
                 Objectname.methodname();
//Example for Class and Object
import java.io.*;
import java.lang.String;
import java.lang.*;
class ClassandObjEx
{         String name="VENU";
          int sno=10;
          public static void main(String args[])
          {      ClassandObjEx s1=new ClassandObjEx();//Here S1 is Object
                 System.out.println("Student Name:"+s1.name);
                 System.out.println("Student Number:"+s1.sno);
                                                                       Output:
          }                                                            Student Name:VENU
                                                                       Student Number:10
}
                                                                                36 | P a g e
                             Java Nested Classes / Java Inner Classes
            In Java, a class within another class, such classes are known as nested classes. They
enable you to logically group classes that are only used in one place, thus this increases
the use of encapsulation and creates more readable and maintainable code.
1. Inner Class:- To access the inner class, create an object of the outer class, and then
create an object of the inner class
Ex:-
class OuterClass
{
    int x = 10;
    class InnerClass
    {
        int y = 5;
        }
}
public class Main
{
    public static void main(String[] args)
    {
        OuterClass myOuter = new OuterClass();
        OuterClass.InnerClass myInner = myOuter.new InnerClass();
        System.out.println(myInner.y + myOuter.x);
        }
}
Output:- 15
                                                                                37 | P a g e
2. Static nested class: Nested classes that are declared static are called static nested
classes.
// Java program to demonstrate accessing a static nested class
Ex:-
class OuterClass // outer class
{
           static int outer_x = 10; //Static Varible
           int outer_y = 20;    // Instance Varible
           private static int outer_private = 30; // Private Static Varible
Output:-
C:\>javac StaticNestedClassDemo.java
C:\>java StaticNestedClassDemo
outer_x = 10
outer_private = 30
outer_y = 20
                                                                                  38 | P a g e
   An access specifier is a keyword that specifies how to access the members of a
class or class itself. We can use access specifiers before a class and its members.
There are 4 access specifiers available in java:
 Private: ‘private’ members of a class are not accessible any where outside the
  class. They are accessible only within the class by the methods of that class.
EX:-
class A                                            Ex:- public class MyClass
{                                                          {
  private int data=40;                                    private void display() // Private method
  private void msg()                                      {
  {                                                          System.out.println("This is a private method.");
                                                           }
    System.out.println("Hello java");
                                                           public static void main(String[] args)
  }                                                        {
}                                                             MyClass obj = new MyClass();
                                                              obj.display(); // Accessible within the same class
public class Simple                                        }
{                                                        }
  public static void main(String args[])           public class AnotherClass // Another class
  {                                                {
                                                     public static void main(String[] args)
    A obj=new A();
                                                     {
    System.out.println(obj.data);                      MyClass obj = new MyClass();
    //Compile Time Error                               obj.display(); // Compilation error: 'display()' has private access
    obj.msg();                                                            in 'MyClass'
    //Compile Time Error                               }
  }                                                }
}
   Public: ‘public’ members of a class are accessible every where outside the class.
    So any other program can read them and use them.
    Ex:-
             public class MyClass // Public class
             {
                public void display() // Public method
                {
                   System.out.println("Hello, World!");
                }
              }
             // Another class in the same or different package
             public class AnotherClass
             {
                public static void main(String[] args)
                {
                  MyClass obj = new MyClass();
                  obj.display(); // Accessible due to public modifier
                }
             }
                                                                                                            39 | P a g e
     Protected: ‘protected’ members of class are accessible outside the class, but
      generally, within the same package.
  Default: If no access specifier is written by the programmer, then the java compiler
   uses a ‘default’ access specifier. ‘default’ members are accessible outside the
   class, but within the same package.
Ex:-
// Default access class
class MyClass
{
   // Default access method
   void display()
   {
       System.out.println("This is a default access method.");
   }
}
// Another class in the same package
public class AnotherClass
{
   public static void main(String[] args)
     {
       MyClass obj = new MyClass();
       obj.display(); // Accessible due to default access within the same package
       }
}
// If AnotherClass is in a different package, the above method call would result in
a compilation error.
    Modifier    Same Class      Same Package          Subclass (Different Package)          Other Packages
public               Yes               Yes                          Yes                            Yes
protected            Yes               Yes                          Yes                            No
Default              Yes               Yes                           No                            No
private              Yes               No                            No                            No
                                                                                         40 | P a g e
E.g.: //Difference between public and private
class Test
{
       int a; //default access
       public int b; //public access
       private int c; //private access
       //methods to access to c
       void setc(int i)
       {
               c=i;
       }
       int getc()
       {
               return c;
       }
}
class AccessTest
{
       public static void main(String args[])
       {
               Test ob=new Test();
              //These are ok, a and b may be accessed directly
               ob.a=10;
               ob.b=20;
               //this is not ok and will cause an error
               //ob.c=100; //error
               //you must access c through its methods
               ob.setc(100); //ok
               System.out.println("a, b, and c:"+ob.a+" "+ob.b+" "+ob.getc());
       }
}
O/P: J:\>javac AccessTest.java
      J:\>java AccessTest
      a, b, and c:10 20 100
                                                                      41 | P a g e
       A method represents a group of statements that performs a task. Here 'task'
represents a calculation or processing of data or generating a report etc.
   1. Predefined (Or) Build in Methods :- Which are already loaded in java, For example,
       take sqrt( ) method. It calculates square root value and returns that value.
   2. User defined Methods:- Which are created by user with own specifications, the
       user defined method has two parts:
            a.    Method header or Method prototype
            b. Method body
a. Method Header or Method Prototype:
       It contains method name, method parameters and method return data type. Method
prototype is written in the form:
                 returntype methodname (Parameter – list)
       Here, method name represents the name given to the method. After the method name,
we write some variables in the simple braces. These variables are called parameters. Method
parameters are useful to receive data from outside into the method. Return data          type is
written before the method name to represent what type of result the method is Returning.
For example:
       double sqrt(double num) : Here, sqrt is the method name. num is method
parameter that represents that this method accepts a double type value. This method
calculates square root value of num and returns that result which is again double type.
We can call this method like
       double result = obj.sqrt(25.6)
b. Method Body:
       Below the method header, we should write the method body. Method body consists
of group of statements which contains logic to perform the task. Method body can be
written in the following format:
Syntax:
         returntype MethodName (Parameter – list)
              {
                     Method Body;
              }
       For example, we want to write a method that calculates sum of two numbers. it may
contain the method body as shown here:
int sum( int a,int b,int c)
{
  double c = a+b;
  System.out.println("sum of two = "+c);
}
       If a method returns some value, then a return statement should be written in the
body of this method as
return x; //return x value
return (x+y); //return sum of x and y value
return -1; //return -1
return obj; //return object obj
return arr; //return array arr
                                                                          42 | P a g e
Ex:- //Method with Parameters and Return type
import java.io.*;
import java.lang.*;
public class AddTwoNumbers
  {
    // Method to add two numbers and return the result
    public static int add(int num1, int num2) //Method Header and Called Method
         {                           //Method Body
       int sum = num1 + num2;
       return sum;                                          Output:
         }                                                  Sum of 5 and 10 is: 15
    public static void main(String[] args)
         {
       // Input numbers
       int number1 = 5;
       int number2 = 10;
       // Call the add method and store the result in a variable
       int result = add(number1, number2); //Method Calling
       // Display the result
       System.out.println("Sum of " + number1 + " and " + number2 + " is: " + result);
    }
}
/*The above example: We define a method called add that takes two integer parameters (num1 and
num2) and returns their sum. In the main method, we declare two integer variables number1 and
number2, which represent the numbers you want to add. We then call the add method with
number1 and number2 as arguments, and the result is stored in the result variable. Finally, we print
the result using System.out.println.*/
Ex 2:-
//Method with parameters without return
import java.io.*;
import java.lang.*;
    Output:
    The sum is: 30
                                                                                 43 | P a g e
                                         Recursion
        A method calling itself is known as ‘recursive method’, and that phenomenon is
called ‘recursion’. It is possible to write recursive methods in java.
E.g.: //factorial using recursion
class Recursion
{
static long factorial(int num)
{
long result;
if(num==1)
return 1;
result=factorial(num-1)*num;
return result;
}                                                    O/P: J:\>javac recursion.java
public static void main(String args[])                     J:\>java Recursion
{                                                          Factorial of 5=120
System.out.println("Factorial of 5=");
System.out.println(Recursion.factorial(5));
}
}
                                   Parameter Passing
Passing primitive data types to methods: Primitive data types or fundamental data
types represent single values. For example, char, byte, short, long, int, float, double and
boolean are called primitive data types, because they store single values. They are passed
to methods by value. This means when we pass primitive data types to methods, a copy of
those will be passed to methods. Therefore, any changes made to them inside the method
will not affect them outside the method. This is also called pass by value or call by value.
E.g.:
//Parameter passing technic
import java.io.*;
import java.lang.*;
public class SwapNumbers
{
   // Method to swap two numbers
   public static void swap(int num1, int num2)
       {
      System.out.println("Before swapping: num1 = " + num1 + ", num2 = " + num2);
                                                                          44 | P a g e
                          Passing objects to methods:
We can also pass class objects methods, and return objects from the methods.
Example:-       Employee mymethod(Employee obj)
                {
                       Statements;
                       return obj;
                }
        Here, mymethod() is a method that accepts Employee class object. So reference of
Employee class declared as parameter in mymethod(). After doing some processing on the
object, if it returns the same object.
Even the objects are also passed to methods by value. This means, when we send an object to
a method, its bit by bit copy will be sent to method. Any modifications to the object inside
the method will not affect the original copy outside the method. So when we come out of
the method, we find the original value unchanged. This is the effect of pass by value. E.g.:
//objects are passed to methods by value
class Employee
{
//instance variable
int id;
Employee(int id)
{
this.id=id;
}
}
class Check
{
//to interchange Employee class objects
void swap(Employee e1,Employee e2)
{
Employee temp;//take a temporary reference
temp=e1;
e1=e2;
e2=temp;
}
}
class PassObjects
{
public static void main(String args[])
{
//take 2 Employee class objects
Employee e1=new Employee(10);
Employee e2=new Employee(20);
//create Check class object
Check c=new Check();
//display data before calling
System.out.println(e1.id+"\t"+e2.id);
//call swap and pass Employee class objects
c.swap(e1,e2);
//display data after calling
System.out.println(e1.id+"\t"+e2.id);
}
}
O/P: J:\>javac objects.java
        J:\>java PassObjects
        10       20
        10       20
                                                                          45 | P a g e
                               Passing arrays to methods
       Just like the objects are passed to method, it is also possible to pass arrays to methods
and return arrays from method. In this case, an array name should be understood as an
object reference. For example,
                      int[] myMethod(int arr[])
       This is the way, we can pass an one dimensional array ‘arr’ to myMethod(). We can
also return a one dimensional array of int type as shown in the preceding statement.
                      int[][] myMethod(int arr[][])
Here, we are passing and returning a two dimensional array of int type.
E.g.:
//Passing Arrays to Methods
import java.io.*;
import java.lang.*;
public class ArrayExample
{
  // Method to modify an array
  public static void modifyArray(int[] arr)
       {
     for (int i = 0; i < arr.length; i++)
               {
               arr[i] *= 2; // Double each element of the array
       }
       }
  public static void main(String[] args)
       {
     int[] myArray = {1, 2, 3, 4, 5};
     // Call the modifyArray method and pass myArray
     modifyArray(myArray);
     // The changes made inside the method are reflected in the original array
     for (int num : myArray) {
         System.out.print(num + " "); // Output: 2 4 6 8 10
     }
  }
}
                                       Output: 2 4 6 8 10
                                                                              46 | P a g e
         A class has multiple methods having same name but different in parameters,
it is known as Method Overloading
         Creating methods that have the same name, but different parameters lists and
definitions is called Method overloading. Method overloading is used when objects are
required to perform similar tasks but using different input parameters.
         When we call a method in an object, java matches the method name first and then
the number and type of parameters to decide which one of the definitions to execute.
This process is also known as polymorphism.
         To create an overloaded method in a class, provide several method definitions with
same name but with different parameters list. The different may be either in the number, type
or order.
Example Program:
//Method Overloading
import java.io.*;
import java.lang.*;
public class Calculator
{
  // Method to add two integers
  public int add(int a, int b)
       {
     return a + b;
       }
                                                                              47 | P a g e
Example 2: // Method Overloading
import java.lang.String;
import java.lang.System;
class A
{
 int add(int x, int y)
 {
   return x+y;
 }
int add(int x, int y, int z)
 {
   return x+y+z;
 }
int add(int x, int y, int z, int k)
 {
   return x+y+z+k;
 }
double add(int x, double y)
 {
   return x+y;
 }
double add(double x, double y)
 {
   return x+y;
 }
}
Class B
{
 public static void main(String args[])
 {
   A obj=new A();
   System.out.println(obj.add(4,5));
   System.out.println(obj.add(6,7.8));
   System.out.println(obj.add(4,5,6,7));
   System.out.println(obj.add(7.8,6.4));
   System.out.println(obj.add(4,3,2));
 }
}
 Output:
 9
 13.8
 22
 14.2
 9
                                           48 | P a g e
                                            METHOD OVERRIDING.
       If subclass (child class) has the same method as declared in the parent class, it is
known as method overriding in Java.
       In other words, If a subclass provides the specific implementation of the method
that has been declared by one of its parent class, it is known as method overriding.
         When a method in a subclass has the same name, the same parameters or
signature, and the same return type(or sub-type) as a method in its super-class, then the
method in the subclass is said to override the method in the super-class.
Ex 1:-
class Bike
        {             void run( )
                      {
                          System.out.println("running");
                      }
            }
    class Splender extends Bike
{
                void run( )
                 {
                 System.out.println("running safely with 60km");
                  }
            public static void main(String args[])
            {
                Bike b = new Splender();//upcasting
                b.run();
        }
    }
Output:Compile by: javac Splender.java
Run by: java Splender
running safely with 60km
                                                                           49 | P a g e
Example 2:- /*Method Overriding*/
class Person // Base Class
{
          public void display()
          {
          System.out.println("\n PERSON");
          }
}
class Doctor extends Person // Inherited class
    {
          // This method overrides display() of Parent@Override
        public void display()
          {
                  System.out.println("\n DOCTOR");
          }
}
class Methodoverride // Driver class
{
          public static void main(String[] args)
          {
          Person p=new Person();
          Doctor d=new Doctor();
          p.display();
                                                                  50 | P a g e
The final keyword in java is used to restrict the user. The java final keyword can be used
in many context. Final can be:
   1. variable
   2. method
   3. class
Final Variable
If you make any variable as final, you cannot change the value of final variable(It will be
constant).
    1. class Bike9{
    2. final int speedlimit=90;//final variable
    3. void run(){
    4. speedlimit=400;
    5. }
    6. public static void main(String args[]){
    7. Bike9 obj=new Bike9();
    8. obj.run();
    9. }
    10. }//end of class
Final Class
When a class is declared with the final keyword in Java, it is called a final class. A final
class cannot be extended(inherited).
Example of final class
    1. final class Bike{}
    2.
    3. class Honda1 extends Bike{
    4. void run(){System.out.println("running safely with 100kmph");}
    5.
    6. public static void main(String args[]){
    7. Honda1 honda= new Honda1();
    8. honda.run();
    9. }
    10.}
Output:Compile Time Error
Final Method
When a method is declared with final keyword, it is called a final method in Java. A
final method cannot be overridden.
Example of final method
    1. class Bike{
    2. final void run(){System.out.println("running");}
    3. }
    4.
    5. class Honda extends Bike{
    6.   void run(){System.out.println("running safely with 100kmph");}
    7.
    8.   public static void main(String args[]){
    9.   Honda honda= new Honda();
    10. honda.run();
    11. }
    12.}
Output:Compile Time Error
                                                                           51 | P a g e
       Constructors are special kind of methods, that are invoked whenever the object is
instantiated. Constructors are mainly used to initialize default values of instance
variables. The Constructors are used to initialized the objects
Rules:- 1.Constructor name is must be equal to class name
       2. Constructor doesn’t have any return type.
Types of Constructors: There are two types of Constructors.
   1. Default Constructor
   2. Parameterized Constructor
1. Default Constructor: A Constructor with no arguments (parameters) is known as
   Default Constructor.
Syntax:      ConstructorName ( )
Constructor body
Ex : Rectangle ( )
length =0;
width =0;
                                                                         52 | P a g e
    //Example of Constructor Overloading, Default and Parameterized Constructors
import java.io.*;
import java.lang.System;
class Rectangle // Hear Rectangle is Class 1
{
    int length, width;
    Rectangle() // Default constructor
    {
        length=10;
        width=20;
    }
    Rectangle(int x, int y) // Parameterized Constructor
    {
        length=x;
        width=y;
    }
    int area()
    {
        return length*width;
    }
}
class RectArea               //Here RectArea is Class 2
{
        public static void main(String args[])
        {
            Rectangle obj=new Rectangle();
            Rectangle obj1=new Rectangle(50,20);
            System.out.println("Area="+obj.area());
            System.out.println("Area="+obj1.area());
        }
}
                                        C:\javac RectArea.java
                                        C:\java RectArea
                                        Output:
                                        Area=200
                                        Area=1000
                                                                   53 | P a g e
      An interesting feature of the constructor is that a class can have “multiple
constructors” is called constructor over loading. All the constructors have the same name
as corresponding to its class name. But they defer only in terms of their signature. As
number of arguments (or) data types (or) order.
 Ex:
      public class Student
      {
             int id;                   //instance variables of the class
             String name;
             Student()           //default constructor
             {
                       System.out.println("this a default constructor");
             }
             Student(int i, String n) //Parameterized constructor
             {
                       id = i;
                       name = n;
             }
             public static void main(String[] args)
             {         //object creation
             Student s = new Student();
             System.out.println("\nDefault Constructor values: \n");
             System.out.println("Student Id : "+s.id + "\nStudent Name : "+s.name);
Output:-
this a default constructor
Default Constructor values:
Student Id : 0
Student Name : null
      In the above example, the Student class constructor is overloaded with two different
constructors, I.e., default and parameterized.
                                                                           54 | P a g e
Constructors “this” Keyword reference:
       ‘this’ is a keyword that refers to the object of the class where it is used. In
other words, ‘this’ refers to the object of the present class. Generally we write
instance variables, constructors and methods in a class. All the members are
referenced by ‘this’. When an object is created to a class, a default reference is also
created internally to the object. This default reference is nothing but ‘this’. So, ‘this’
can refer to all the things of the present object.
Ex.:
//this - refers to all the member of present class
class Sample
{
//x is instance variable
private int x;
//default consructor
Sample()
{
this(55); //call present class parameterized constructor & send 55
this.access(); //call present class method
}
//parameterized constructor
Sample(int x)
{
this.x=x; //refer present class instance variable
}
//method
void access()                            This Key word :-This represents Instance Varibles and
{                                        & current objects
System.out.println("x="+x);              Ex:- 2
}                                                           //Using This Key word
}                                        class A
class ThisDemo                           {
{                                         int a=20; //Instance variable
public static void main(String args[])    void print() //It is a Method with out returntype
{                                          {
Sample s= new Sample();                     int a=100; //Local Varible
}                                           System.out.println("Local Varible="+a);
}                                           System.out.println("Instance Varible="+this.a);
O/P: J:\>javac this.java                   }
      J:\>java ThisDemo                  public static void main(String args[])
      x=55                               {
                                          A s=new A(); //Object Created i.e s
                                          s.print();
                                         }
                                         }
                                         /*Output :
                                         javac A.java
                                         java A
                                         Local Varible=100
                                         Instance Varible=20*/
                                                                         55 | P a g e
                          Java Garbage Collection
 In java, garbage means unreferenced objects.
 Garbage Collection is process of reclaiming the runtime unused memory
automatically. In other words, it is a way to destroy the unused objects.
To do so, we were using free() function in C language and delete() in C++. But, in
java it is performed automatically. So, java provides better memory management
Advantage of Garbage Collection
   o It makes java memory efficient because garbage collector removes the
       unreferenced objects from heap memory.
   o It is automatically done by the garbage collector(a part of JVM) so we don't
       need to make extra efforts.
How can an object be unreferenced?
   o By nulling the reference
   o By assigning a reference to another
   o By anonymous object etc.
1) By nulling a reference:
   1. Employee e=new Employee();
   2. e=null;
2) By assigning a reference to another:
   1. Employee e1=new Employee();
   2. Employee e2=new Employee();
   3. e1=e2;//now the first object referred by e1 is available for garbagecollectio
3) By anonymous object:
   1. new Employee();
finalize() method
The finalize() method is invoked each time before the object is garbage collected.
This method can be used to perform cleanup processing. This method is defined in
Object class as:
                            protected void finalize(){}
gc() method
The gc() method is used to invoke the garbage collector to perform cleanup
processing. The gc() is found in System and Runtime classes.
                             public static void gc(){}
                 Simple Example of garbage collection in java
public class TestGarbage1
{
      public void finalize()
      {
      System.out.println("object is garbage collected");
      }
      public static void main(String args[])
      {
      TestGarbage1 s1=new TestGarbage1();
      TestGarbage1 s2=new TestGarbage1();
      s1=null;
      s2=null;
      System.gc();
      }
}
56 | P a g e