You are on page 1of 35

UNIT II

Classes, Objects and Methods


Class − A class can be defined as a template/blueprint that describes the behavior/state that
the object of its type support.

Object - An entity that has state and behavior is known as an object e.g., chair, bike,
marker, pen, table, car, etc. It can be physical or logical (tangible and intangible). The
example of an intangible object is the banking system.

An object has three characteristics:

o State: represents the data (value) of an object.


o Behavior: represents the behavior (functionality) of an object such as deposit,
withdraw, etc.
o Identity: An object identity is typically implemented via a unique ID. The value
of the ID is not visible to the external user. However, it is used internally by the
JVM to identify each object uniquely.

Create a Class
To create a class, use the keyword class:

class classname

field declaration;

method declaration;

MyClass.java
Create a class named "MyClass" with a variable x:

class MyClass {

int x = 5;

Field Decaration

1 | D e p a r t m e n t o f C o m p u t e r A p p l i c a ti o n s , M E S G o l d e n
J u b i l e e C o l l e g e K o tt a y a m
 Data fields inside the class declaration
 Named as Instance variable because they are created whenever an object of the
class is instantiated
 These variables are only declared and therefore no storage space has been
created in the memory
 Also called member variable

class Rectangle {

int length; // instance variable

int width; // instance variable

Method Declaration

Methods are used to manipulate the data contained in the class

Declared inside the body of the classs immediately after the declaration of instance variable

Syntax

type methodname (parameter-list)

method body;

It has 4 basic parts

1. The name of the method (methodname) – a valid identifier


2. The type of the value the method returns (type) – any datatype
3. A list of parameters (parameter-list) – contains values we want to give to the method as
input, the variables in the list are separated by commas
4. The body of the method – describes the operations to be performed on the data
Eg:
class Rectangle
{
int length, width;
Return Type
Method name
void getdata (int x, int y) Parameter-list
{

2 | D e p a r t m e n t o f C o m p u t e r A p p l i c a ti o n s , M E S G o l d e n
J u b i l e e C o l l e g e K o tt a y a m
length=x;
width=y; body od method
}
}
Creating Objects [Instantiating Object]
The new operator creates an object of the specified class and returns a reference to that
object.

Rectangle rect1; // declares a variable to hold the object reference


Rect1= new Rectangle(); // assigns object reference to the variable

Both statement can be combined as

Rectangle rect1= new Rectangle();

The method Rectangle() is the default constructor of the class. We can create any number of
objects of Rectangle.
Action Statement Result

Declare Rectangle rect1; rect1


null

Instantiate rect1 = new Rectangle();


rect1

Fig: Instantiating Object

Rectangle
object

 Any changes to the variables of one object have no effect on the variables of another
 It is also possible to create two or more references to the same object as in the following
figure.

Rectangle R1=new Rectangle();


Rectangle R2=R1; //both R1 and R2 refer to the same object

3 | D e p a r t m e n t o f C o m p u t e r A p p l i c a ti o n s , M E S G o l d e n
J u b i l e e C o l l e g e K o tt a y a m
R1

Rectangle
Object

R2

Accessing Class Members [dot operator]

objectname.variablename=value;

objectname.methodname(parameter-list);

objectname – name of the object

variablename – name of the instance variable

methodname – method we wish to call

parameter-list - comma separated list of actual values (or expressions)

There are 3 ways to initialize object in Java. Initializing an object means storing data into
the object.

1. By reference variable
2. By method
3. By constructor

1) Object and Class Example: Initialization through reference


File: TestStudent2.java

class Student{  
 int id;  
 String name;  
}  
class TestStudent2{  
 public static void main(String args[]){  
  Student s1=new Student();  

4 | D e p a r t m e n t o f C o m p u t e r A p p l i c a ti o n s , M E S G o l d e n
J u b i l e e C o l l e g e K o tt a y a m
  s1.id=101;   // assigning value to instance variable id
  s1.name="Architha";  // assigning value to instance variable name
  System.out.println(s1.id+" "+s1.name);//printing members with a white space  
 }  
}  

Output:

101 Architha

 We can also create multiple objects and store information in it through reference
variable.

File: TestStudent3.java

class Student{  
 int id;  
 String name;  
}  
class TestStudent3{  
 public static void main(String args[]){  
  //Creating objects  
  Student s1=new Student();  // first object instantiated
  Student s2=new Student();  // second object instantiated
  //Initializing objects  
  s1.id=101;  // assigning value to instance variable id trough s1
  s1.name="Sonoo"; // assigning value to instance variable name trough s1 
  s2.id=102;  // assigning value to instance variable id trough s2
  s2.name="Amit";  // assigning value to instance variable name trough s2 
  //Printing data  
  System.out.println(s1.id+" "+s1.name);  
  System.out.println(s2.id+" "+s2.name);  
 }  

Output:

101 Sonoo
102 Amit

2) Object and Class Example: Initialization through method


In this example, we are creating the two objects of Student class and initializing the
value to these objects by invoking the insertRecord method. Here, we are displaying the
state (data) of the objects by invoking the displayInformation() method.

File: TestStudent4.java

5 | D e p a r t m e n t o f C o m p u t e r A p p l i c a ti o n s , M E S G o l d e n
J u b i l e e C o l l e g e K o tt a y a m
class Student{  
 int rollno;  
 String name;  
 void insertRecord(int r, String n){  
  rollno=r;  
  name=n;  
 }  
 void displayInformation(){System.out.println(rollno+" "+name);}  
}  
class TestStudent4{  
 public static void main(String args[]){  
  Student s1=new Student();  
  Student s2=new Student();  
  s1.insertRecord(111,"Karan");  
  s2.insertRecord(222,"Aryan");  
  s1.displayInformation();  
  s2.displayInformation();  
 }  
}  
111 Karan
222 Aryan

As you can see in the above figure, object gets the memory in heap memory area. The
reference variable refers to the object allocated in the heap memory area. Here, s1 and
s2 both are reference variables that refer to the objects allocated in memory.

3) Object and Class Example: Initialization through a


constructor
6 | D e p a r t m e n t o f C o m p u t e r A p p l i c a ti o n s , M E S G o l d e n
J u b i l e e C o l l e g e K o tt a y a m
A constructor in Java is a special method that is used to initialize objects.
The constructor is called when an object of a class is created. It can be used
to set initial values for object attributes.

Note: It is called constructor because it constructs the values at the time of object
creation. It is not necessary to write a constructor for a class. It is because java compiler
creates a default constructor if your class doesn't have any.

Rules for creating Java constructor


1. Constructor name must be the same as its class name
2. A Constructor must have no explicit return type
3. A Java constructor cannot be abstract, static, final, and synchronized

Note: We can use access modifiers while declaring a constructor. It controls the


object creation. In other words, we can have private, protected, public or default
constructor in Java.

Types of Java constructors


There are two types of constructors in Java:

1. Default constructor (no-arg constructor)


2. Parameterized constructor
Java Default Constructor
A constructor is called "Default Constructor" when it doesn't have any parameter.

The default constructor is used to provide the default values to the object like 0, null,
etc., depending on the type.

Syntax of default constructor:

<class_name>(){}  

Note: If there is no constructor in a class, compiler automatically creates a default


constructor.

class MyClass {

int x; // Create a class attribute

7 | D e p a r t m e n t o f C o m p u t e r A p p l i c a ti o n s , M E S G o l d e n
J u b i l e e C o l l e g e K o tt a y a m
// Create a class constructor for the MyClass class

MyClass() {

x = 0; // Set the initial value for the class attribute x

public static void main(String[] args) {

MyClass myObj = new MyClass(); // Create an object of class MyClass


(This will call the constructor)

System.out.println(myObj.x); // Print the value of x

// Output 0

Java Parameterized Constructor


A constructor which has a specific number of parameters is called a parameterized
constructor.

//Java Program to demonstrate the use of the parameterized constructor.  
class Student4{  
    int id;  
    String name;  
    //creating a parameterized constructor  
    Student4(int i,String n){  
    id = i;  
    name = n;  
    }  
    //method to display the values  
    void display(){System.out.println(id+" "+name);}  
   
    public static void main(String args[]){  
    //creating objects and passing values  
    Student4 s1 = new Student4(111,"Karan");  
    Student4 s2 = new Student4(222,"Aryan");  
    //calling method to display the values of object  
8 | D e p a r t m e n t o f C o m p u t e r A p p l i c a ti o n s , M E S G o l d e n
J u b i l e e C o l l e g e K o tt a y a m
    s1.display();  
    s2.display();  
   }  

Output:

111 Karan
222 Aryan

Constructor Overloading in Java


Constructor overloading in Java is a technique of having more than one constructor with
different parameter lists. They are arranged in a way that each constructor performs a
different task. They are differentiated by the compiler by the number of parameters in
the list and their types.

Example of Constructor Overloading


//Java program to overload constructors  
class Student5{  
int id;  
String name;  
int age;  
//creating two arg constructor  
Student5(int i,String n){  
id = i;  
name = n;  
}  
//creating three arg constructor  
Student5(int i,String n,int a){  
id = i;  
name = n;  
age=a;  
}  
void display(){System.out.println(id+" "+name+" "+age);}  

public static void main(String args[]){  
Student5 s1 = new Student5(111,"Karan");  
Student5 s2 = new Student5(222,"Aryan",25);  
s1.display();  
s2.display();  
}  
}  

Output:
9 | D e p a r t m e n t o f C o m p u t e r A p p l i c a ti o n s , M E S G o l d e n
J u b i l e e C o l l e g e K o tt a y a m
111 Karan 0
222 Aryan 25

Difference Between Java Constructor and Method

Java Constructor Java Method

A constructor is used to initialize the state of an object. A method is used to expose the
behavior of an object.

A constructor must not have a return type. A method must have a return type.

The constructor is invoked implicitly. The method is invoked explicitly.

The Java compiler provides a default constructor if you The method is not provided by the
don't have any constructor in a class. compiler in any case.

The constructor name must be same as the class name. The method name may or may not be
same as the class name.

Method Overloading in Java


 Used to achieve Polymorphism

 If a class has multiple methods having same name but different in parameters, it


is known as Method Overloading.

 When we call a method in an object, Java matches up the method name first and
then number and types of parameters to decide which one of the definitions to
execute.

 In java, method overloading is not possible by changing the return type of the
method only because of ambiguity.

 By method overloading, You can have any number of main methods in a class by
method overloading. But JVM calls main() method which receives string array as
arguments only.

// Java program to demonstrate working of method


// overloading in Java.
  
class Sum {
  
    // Overloaded sum().This sum takes two int parameters
     int sum(int x, int y)
    {
        return (x + y);
    }

10 | D e p a r t m e n t o f C o m p u t e r A p p l i c a ti o n s , M E S G o l d e n
J u b i l e e C o l l e g e K o tt a y a m
  
    // Overloaded sum(). This sum takes three int parameters
     int sum(int x, int y, int z)
    {
        return (x + y + z);
    }
  
    // Overloaded sum(). This sum takes two double parameters
    double sum(double x, double y)
    {
        return (x + y);
    }
  
    // Driver code
    public static void main(String args[])
    {
        Sum s = new Sum();
        System.out.println(s.sum(10, 20));
        System.out.println(s.sum(10, 20, 30));
        System.out.println(s.sum(10.5, 20.5));
    }
}
Output :
30
60
31.0

Java static keyword


 The static keyword in Java is used for memory management mainly. 

 To create a static member, precede its declaration with the keyword static.

 When a member is declared static, it can be accessed before any objects of


its class are created, and without reference to any object.

Eg:

static int count;

static int max(int x, int y);

 The members that are declared as static is called static members.

 Static members are associated with class itself rather than individual
objects so static variables and static methods are referred ad class
variables and class methods.

11 | D e p a r t m e n t o f C o m p u t e r A p p l i c a ti o n s , M E S G o l d e n
J u b i l e e C o l l e g e K o tt a y a m
1) Java static variable [Class Variable]
If you declare any variable as static, it is known as a static variable.

o The static variable can be used to refer to the common property of all objects
(which is not unique for each object), for example, the company name of
employees, college name of students, etc.
o The static variable gets memory only once in the class area at the time of class
loading.

//Java Program to demonstrate the use of static variable  
class Student{  
   int rollno;//instance variable  
   String name; //instance variable  
   static String college ="ITS";//static variable  
   //constructor  
   Student(int r, String n){  
   rollno = r;  
   name = n;  
   }  
   //method to display the values  
   void display (){System.out.println(rollno+" "+name+" "+college);}  
}  
//Test class to show the values of objects  
public class TestStaticVariable1{  
 public static void main(String args[]){  
 Student s1 = new Student(111,"Karan");  
 Student s2 = new Student(222,"Aryan");  
 //we can change the college of all objects by the single line of code  
 //Student.college="BBDIT";  
 s1.display();  
 s2.display();  
 }  
}  

Output:

111 Karan ITS


222 Aryan ITS

12 | D e p a r t m e n t o f C o m p u t e r A p p l i c a ti o n s , M E S G o l d e n
J u b i l e e C o l l e g e K o tt a y a m
Java static method [Class Method]
If you apply static keyword with any method, it is known as static method.

o A static method belongs to the class rather than the object of a class.
o A static method can be invoked without the need for creating an instance of a
class.

classname.classmethod();

o A static method can access static data member and can change the value of it.

Example of static method


//Java Program to demonstrate the use of a static method.  
class Student{  
     int rollno;  
     String name;  
     static String college = "ITS";  //static variable
     //static method to change the value of static variable  

13 | D e p a r t m e n t o f C o m p u t e r A p p l i c a ti o n s , M E S G o l d e n
J u b i l e e C o l l e g e K o tt a y a m
     static void change(){  
     college = "BBDIT";  
     }  
     //constructor to initialize the variable  
     Student(int r, String n){  
     rollno = r;  
     name = n;  
     }  
     //method to display values  
     void display(){System.out.println(rollno+" "+name+" "+college);}  
}  
//Test class to create and display the values of object  
public class TestStaticMethod{  
    public static void main(String args[]){  
    Student.change();//calling static method  without creating object
    //creating objects  
    Student s1 = new Student(111,"Karan");  
    Student s2 = new Student(222,"Aryan");  
    Student s3 = new Student(333,"Sonoo");  
    //calling display method  
    s1.display();  
    s2.display();  
    s3.display();  
    }  
}  
Output:111 Karan BBDIT
222 Aryan BBDIT
333 Sonoo BBDIT

Rules

1. The static method can not use non static data member or call non-static method
directly.
2. this and super cannot be used in static context.

Nesting of Methods

A method can be called by using only its name by another method of the same class.
This is known as nesting of methods.

import java.util.Scanner;
public class Nesting_Methods
{
int perimeter(int l, int b)
{
int pr = 12 * (l + b);

14 | D e p a r t m e n t o f C o m p u t e r A p p l i c a ti o n s , M E S G o l d e n
J u b i l e e C o l l e g e K o tt a y a m
return pr;
}
int area(int l, int b)
{
int pr = perimeter(l, b);
System.out.println("Perimeter:"+pr);
int ar = 6 * l * b;
return ar;
}
int volume(int l, int b, int h)
{
int ar = area(l, b);
System.out.println("Area:"+ar);
int vol ;
vol = l * b * h;
return vol;
}
public static void main(String[] args)
{
Scanner s = new Scanner(System.in);
System.out.print("Enter length of cuboid:");
int l = s.nextInt();
System.out.print("Enter breadth of cuboid:");
int b = s.nextInt();
System.out.print("Enter height of cuboid:");
int h = s.nextInt();
Nesting_Methods obj = new Nesting_Methods();
int vol = obj.volume(l, b, h);
System.out.println("Volume:"+vol);
}
}

return keyword in Java


 It is used to exit from a method, with or without a value.
return statement must be immediately followed by return value.

// Java program to illustrate usage

// of return keyword

  

class A {

  

    // Since return type of RR method is double

    // so this method should return double value

    double RR(double a, double b)

    {

        double sum = 0;

        sum = (a + b) / 2.0;

15 | D e p a r t m e n t o f C o m p u t e r A p p l i c a ti o n s , M E S G o l d e n
J u b i l e e C o l l e g e K o tt a y a m
        // return statement below:

        return sum;

    }

    public static void main(String[] args)

    {

A a=new A();

        System.out.println(a.RR(5.5, 6.5));

    }

Output:
6.0

Inheritance in Java
Inheritance in Java is a mechanism in which one object acquires all the properties and
behaviors of a parent object. It is an important part of OOPs (Object Oriented
programming system).

The idea behind inheritance in Java is that you can create new classes that are built
upon existing classes. When you inherit from an existing class, you can reuse methods
and fields of the parent class. Moreover, you can add new methods and fields in your
current class also.

Inheritance represents the IS-A relationship which is also known as a parent-


child relationship.

Why use inheritance in java


o For Method Overriding (so runtime polymorphism can be achieved).
o For Code Reusability.

Terms used in Inheritance


o Class: A class is a group of objects which have common properties. It is a
template or blueprint from which objects are created.
o Derived class/Sub Class/Child Class: Subclass is a class which inherits the
other class. It is also called a derived class, extended class, or child class.
o Super Class/Parent Class/base class: Superclass is the class from where a
subclass inherits the features. It is also called a base class or a parent class.
o Reusability: As the name specifies, reusability is a mechanism which facilitates
you to reuse the fields and methods of the existing class when you create a new

16 | D e p a r t m e n t o f C o m p u t e r A p p l i c a ti o n s , M E S G o l d e n
J u b i l e e C o l l e g e K o tt a y a m
class. You can use the same fields and methods already defined in the previous
class.

The syntax of Java Inheritance


class Subclass-name extends Superclass-name  
{  
   //methods and fields  
}  

The extends keyword indicates that you are making a new class that derives from an
existing class. The meaning of "extends" is to increase the functionality.

In the terminology of Java, a class which is inherited is called a parent or superclass, and
the new class is called child or subclass.

Java Inheritance Example


Programmer is the subclass and Employee is the superclass. The relationship between
the two classes is Programmer IS-A Employee. It means that Programmer is a type of
Employee.

1. class Employee{  
2.  float salary=40000;  
3. }  
4. class Programmer extends Employee{  
5.  int bonus=10000;  
6.  public static void main(String args[]){  
7.    Programmer p=new Programmer();  
8.    System.out.println("Programmer salary is:"+p.salary);  
9.    System.out.println("Bonus of Programmer is:"+p.bonus);  
10. }  
11. }  
Programmer salary is:40000.0
Bonus of programmer is:10000

In the above example, Programmer object can access the field of own class as well as of
Employee class i.e. code reusability.

Types of inheritance in java


On the basis of class, there can be three types of inheritance in java: single, multilevel
and hierarchical.

17 | D e p a r t m e n t o f C o m p u t e r A p p l i c a ti o n s , M E S G o l d e n
J u b i l e e C o l l e g e K o tt a y a m
In java programming, multiple and hybrid inheritance is supported through interface
only.

Note: Multiple inheritance is not supported in Java through class. It is done


through Interface

When one class inherits multiple classes, it is known as multiple inheritance. For
Example:

Single Inheritance Example


When a class inherits another class, it is known as a single inheritance. In the
example given below, Dog class inherits the Animal class, so there is the single
inheritance.

File: TestInheritance.java

1. class Animal{  
2. void eat(){System.out.println("eating...");}  
3. }  
4. class Dog extends Animal{  
5. void bark(){System.out.println("barking...");}  
6. }  

18 | D e p a r t m e n t o f C o m p u t e r A p p l i c a ti o n s , M E S G o l d e n
J u b i l e e C o l l e g e K o tt a y a m
7. class TestInheritance{  
8. public static void main(String args[]){  
9. Dog d=new Dog();  
10. d.bark();  
11. d.eat();  
12. }}  

Output:

barking...
eating...

Multilevel Inheritance Example


When there is a chain of inheritance, it is known as multilevel inheritance. As you
can see in the example given below, BabyDog class inherits the Dog class which again
inherits the Animal class, so there is a multilevel inheritance.

File: TestInheritance2.java

1. class Animal{  
2. void eat(){System.out.println("eating...");}  
3. }  
4. class Dog extends Animal{  
5. void bark(){System.out.println("barking...");}  
6. }  
7. class BabyDog extends Dog{  
8. void weep(){System.out.println("weeping...");}  
9. }  
10. class TestInheritance2{  
11. public static void main(String args[]){  
12. BabyDog d=new BabyDog();  
13. d.weep();  
14. d.bark();  
15. d.eat();  
16. }}  

Output:

weeping...
barking...
eating...

Hierarchical Inheritance Example

19 | D e p a r t m e n t o f C o m p u t e r A p p l i c a ti o n s , M E S G o l d e n
J u b i l e e C o l l e g e K o tt a y a m
When two or more classes inherits a single class, it is known as hierarchical
inheritance. In the example given below, Dog and Cat classes inherits the Animal
class, so there is hierarchical inheritance.

File: TestInheritance3.java

1. class Animal{  
2. void eat(){System.out.println("eating...");}  
3. }  
4. class Dog extends Animal{  
5. void bark(){System.out.println("barking...");}  
6. }  
7. class Cat extends Animal{  
8. void meow(){System.out.println("meowing...");}  
9. }  
10. class TestInheritance3{  
11. public static void main(String args[]){  
12. Cat c=new Cat();  
13. c.meow();  
14. c.eat();  
15. //c.bark();//C.T.Error  
16. }}  

Output:

meowing...
eating...

Q) Why multiple inheritance is not supported in java?


To reduce the complexity and simplify the language, multiple inheritance is not
supported in java.

Consider a scenario where A, B, and C are three classes. The C class inherits A and B
classes. If A and B classes have the same method and you call it from child class object,
there will be ambiguity to call the method of A or B class.

Since compile-time errors are better than runtime errors, Java renders compile-time
error if you inherit 2 classes. So whether you have same method or different, there will
be compile time error.

1. class A{  
2. void msg(){System.out.println("Hello");}  
3. }  
4. class B{  
5. void msg(){System.out.println("Welcome");}  

20 | D e p a r t m e n t o f C o m p u t e r A p p l i c a ti o n s , M E S G o l d e n
J u b i l e e C o l l e g e K o tt a y a m
6. }  
7. class C extends A,B{//suppose if it were  
8.    
9.  public static void main(String args[]){  
10.    C obj=new C();  
11.    obj.msg();//Now which msg() method would be invoked?  
12. }  
13. }  

Output

Compile Time Error

Super Keyword in Java


The super keyword in java is a reference variable that is used to refer parent class
objects.  The keyword “super” came into the picture with the concept of Inheritance.
It is majorly used in the following contexts:
1. Use of super with variables: This scenario occurs when a derived class and
base class has same data members. In that case there is a possibility of ambiguity
for the JVM.

/* Base class vehicle */

class Vehicle

    int maxSpeed = 120;

  

/* sub class Car extending vehicle */

class Car extends Vehicle

    int maxSpeed = 180;

  

    void display()

    {

        /* print maxSpeed of base class (vehicle) */

        System.out.println("Maximum Speed: " + super.maxSpeed);

    }

21 | D e p a r t m e n t o f C o m p u t e r A p p l i c a ti o n s , M E S G o l d e n
J u b i l e e C o l l e g e K o tt a y a m
  

class Test

    public static void main(String[] args)

    {

        Car small = new Car();

        small.display();

    }

Output:
Maximum Speed: 120
In the above example, both base class and subclass have a member maxSpeed. We
could access maxSpeed of base class in subclass using super keyword.
 

2. Use of super with methods: This is used when we want to call parent class
method. So whenever a parent and child class have same named methods then to
resolve ambiguity we use super keyword.

/* Base class Person */

class Person

    void message()

    {

        System.out.println("This is person class");

    }

  

/* Subclass Student */

class Student extends Person

    void message()

    {

        System.out.println("This is student class");

22 | D e p a r t m e n t o f C o m p u t e r A p p l i c a ti o n s , M E S G o l d e n
J u b i l e e C o l l e g e K o tt a y a m
    }

  

    // Note that display() is only in Student class

    void display()

    {

        // will invoke or call current class message() method

        message();

  

        // will invoke or call parent class message() method

        super.message();

    }

  

/* Driver program to test */

class Test

    public static void main(String args[])

    {

        Student s = new Student();

  

        // calling display() of Student

        s.display();

    }

Output:
This is student class
This is person class
In the above example, we have seen that if we only call method message() then, the
current class message() is invoked but with the use of super keyword, message() of
superclass could also be invoked.
 
3. Use of super with constructors: super keyword can also be used to access the
parent class constructor. One more important thing is that, ‘’super’ can call both
parametric as well as non parametric constructors depending upon the situation.

23 | D e p a r t m e n t o f C o m p u t e r A p p l i c a ti o n s , M E S G o l d e n
J u b i l e e C o l l e g e K o tt a y a m
Eg:

Here, Emp class inherits Person class so all the properties of Person will be inherited to
Emp by default. To initialize all the property, we are using parent class constructor from
child class. In such way, we are reusing the parent class constructor.

1. class Person{  
2. int id;  
3. String name;  
4. Person(int id,String name){  
5. this.id=id;  
6. this.name=name;  
7. }  
8. }  
9. class Emp extends Person{  
10. float salary;  
11. Emp(int id,String name,float salary){  
12. super(id,name);//reusing parent constructor  
13. this.salary=salary;  
14. }  
15. void display(){System.out.println(id+" "+name+" "+salary);}  
16. }  
17. class TestSuper5{  
18. public static void main(String[] args){  
19. Emp e1=new Emp(1,"ankit",45000f);  
20. e1.display();  
21. }}  

Output:

1 ankit 45000
Rules
1. super may only be used within a subclass constructor method
2. The call to superclass constructor must appear as the first statement
within the subclass constructor
3. The parameters in the super call must match the order and type of
instance variable declared in the super class

Method Overriding in Java


 If subclass (child class) has the same method as declared in the parent class, it is
known as method overriding in Java.

 Method overriding is used for runtime polymorphism

// A Simple Java program to demonstrate


// method overriding in java
  

24 | D e p a r t m e n t o f C o m p u t e r A p p l i c a ti o n s , M E S G o l d e n
J u b i l e e C o l l e g e K o tt a y a m
// Base Class
class Parent {
    void show()
    {
        System.out.println("Parent's show()");
    }
}
  
// Inherited class
class Child extends Parent {
    // This method overrides show() of Parent
    void show()
    {
        System.out.println("Child's show()");
    }
}
  
class Main {
    public static void main(String[] args)
    {
        
        Child obj = new Child();
        obj.show();
    }
}
Output:
Child's show()

Final Keyword In Java


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

1) Java final variable


If you make any variable as final, you cannot change the value of final variable(It will be
constant).

Example of final variable


There is a final variable speedlimit, we are going to change the value of this variable, but
It can't be changed because final variable once assigned a value can never be changed.

1. class Bike9{  
2.  final int speedlimit=90;//final variable  
3.  void run(){  
4.   speedlimit=400;  

25 | D e p a r t m e n t o f C o m p u t e r A p p l i c a ti o n s , M E S G o l d e n
J u b i l e e C o l l e g e K o tt a y a m
5.  }  
6.  public static void main(String args[]){  
7.  Bike9 obj=new  Bike9();  
8.  obj.run();  
9.  }  
10. }//end of class  

Output:Compile Time Error

2) Java final method


If you make any method as final, you cannot override it.

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

3) Java final class


If you make any class as final, you cannot extend it.

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.   }  

26 | D e p a r t m e n t o f C o m p u t e r A p p l i c a ti o n s , M E S G o l d e n
J u b i l e e C o l l e g e K o tt a y a m
10. }  
Output:Compile Time Error

Java Object finalize() Method


Finalize() is the method of Object class. This method is called just before an object is
garbage collected. finalize() method overrides to dispose system resources, perform
clean-up activities and minimize memory leaks.

Abstraction in Java
Abstraction is a process of hiding the implementation details and showing only
functionality to the user.

Ways to achieve Abstraction

There are two ways to achieve abstraction in java

1. Abstract class
2. Interface

Abstract class: is a restricted class that cannot be used to create objects


(to access it, it must be inherited from another class).

abstract class Shape


{
}

Abstract method: can only be used in an abstract class, and it does not


have a body. The body is provided by the subclass (inherited from).

abstract void show();

An abstract class can have both abstract and regular methods:

abstract class Shape{

abstract void draw();

From the example above, it is not possible to create an object of the Shape
class:

Shape myObj = new Shape(); // will generate an error

27 | D e p a r t m e n t o f C o m p u t e r A p p l i c a ti o n s , M E S G o l d e n
J u b i l e e C o l l e g e K o tt a y a m
To access the abstract class, it must be inherited from another class. 

// Abstract class

abstract class Shape {

// Abstract method (does not have a body)

abstract void draw();

// Subclass (inherit from Shape)

class Rectangle extends Shape {

public void draw() {

// The body of draw() is provided here

System.out.println("Drawing Rectangle");

class MyMainClass {

public static void main(String args[]) {

Rectangle rect = new Rectangle (); // Create a Rectangle object

rect.draw();

Rules

1. We cannot use abstract classes to instantiate objects directly

2. The abstract method of an abstract class must be defined in its subclass

3. We cannot declare abstract constructors or abstract static methods

Runtime Polymorphism in Java


28 | D e p a r t m e n t o f C o m p u t e r A p p l i c a ti o n s , M E S G o l d e n
J u b i l e e C o l l e g e K o tt a y a m
Runtime polymorphism or Dynamic Method Dispatch is a process in which a call to
an overridden method is resolved at runtime rather than compile-time.

In this process, an overridden method is called through the reference variable of a


superclass. The determination of the method to be called is based on the object being
referred to by the reference variable.

Upcasting

If the reference variable of Parent class refers to the object of Child class, it is known as
upcasting. For example:

class A{}  
class B extends A{}  
A a=new B();//upcasting  

Eg:
class Shape{  
void draw(){System.out.println("drawing...");}  
}  
class Rectangle extends Shape{  
void draw(){System.out.println("drawing rectangle...");}  
}  
class Circle extends Shape{  
void draw(){System.out.println("drawing circle...");}  
}  
class Triangle extends Shape{  
void draw(){System.out.println("drawing triangle...");}  
}  
class TestPolymorphism2{  
public static void main(String args[]){  
Shape s;  
s=new Rectangle();  
s.draw();  
s=new Circle();  
s.draw();  
29 | D e p a r t m e n t o f C o m p u t e r A p p l i c a ti o n s , M E S G o l d e n
J u b i l e e C o l l e g e K o tt a y a m
s=new Triangle();  
s.draw();  
}  
}  

Output:

drawing rectangle...
drawing circle...
drawing triangle...

Visibility control in java


ACCESS MODIFIERS
 Visibility modifiers also known as access modifiers can be applied to the instance variables
and methods within a class.
 Java provides the following access modifiers Public Friendly/Package (default) Private
Protected
1. PUBLIC ACCESS
 Any variable or method is visible to the entire class in which it is defined.
 If we want to make it visible to all classes outside the current class by simply declaring
the variable as ‘public
2. FRIENDLY ACCESS
 When no access modifier member defaults to a limited version of public accessibility
known as ‘friendly’ level of access. This is also known as package access.
 The difference between the public and the friendly access is that public modifier makes
the field visible in all classes regardless of their package while the friendly access make
them visible only within the current package and not within the other packages. 3.

3. PROTECTED ACCESS
 The visibility level of the protected field lies between the private and the package
access.
 That is the protected access makes the field visible not only to all classes and
subclasses in the same package but also to subclasses in other package
 Non subclasses in their packages cannot access the protected members

4. PRIVATE ACCESS
 Enjoys high degree of protection.
 They are accessible only within their own class
 They cannot be inherited by their subclass and hence not visible in it.
5. Private protected Access
Visibility lies between protected access and private access
It makes the fields visible in all subclasses regardless of what package they are in.
These fields are not accessible by other classes in the same package

30 | D e p a r t m e n t o f C o m p u t e r A p p l i c a ti o n s , M E S G o l d e n
J u b i l e e C o l l e g e K o tt a y a m
Interface in Java
An interface in Java is a blueprint of a class. It has static constants and abstract
methods.

The interface in Java is a mechanism to achieve  abstraction. There can be only
abstract methods in the Java interface, not method body. It is used to achieve
abstraction and multiple inheritance in Java.

Syntax

interface InterfaceName

variable declaration;

methods declaration;

 Interface – keyword
 IntefaceName – valid identifier
 Variables are declared as constants:

static final type VariableName = Value;

 Methods declaration will contain only list of methods without any body statements.

return-type methodName1(parameter-list);

o The class that implements interface must define the code for the method

The relationship between classes and interfaces


As shown in the figure given below, a class extends another class, an interface extends
another interface, but a class implements an interface.

31 | D e p a r t m e n t o f C o m p u t e r A p p l i c a ti o n s , M E S G o l d e n
J u b i l e e C o l l e g e K o tt a y a m
Implementing interface
Interfaces are used as “superclass” whose properties are inherited by classes. It is therefore
necessary to create a class that inherits the given interface.

class classname implements interfacename

body of classname

Java Interface Example


In this example, the Printable interface has only one method, and its implementation is
provided in the Sample class.

interface printable{  
void print();  
}  
class Sample implements printable{  
public void print()
{System.out.println("Hello");}  
  
public static void main(String args[]){  
Sample obj = new Sample();  
obj.print();  
 }  
}  

32 | D e p a r t m e n t o f C o m p u t e r A p p l i c a ti o n s , M E S G o l d e n
J u b i l e e C o l l e g e K o tt a y a m
Output:

Hello

Multiple inheritance in Java by interface


If a class implements multiple interfaces, or an interface extends multiple interfaces, it is
known as multiple inheritance.

interface Printable{  
void print();  
}  
interface Showable{  
void show();  
}  
class Sample implements Printable, Showable{  
public void print(){System.out.println("Hello");}  
public void show(){System.out.println("Welcome");}  
  
public static void main(String args[]){  
Sample obj = new Sample();  
obj.print();  
obj.show();  
 }  
}  
Output:Hello
Welcome

Q) Multiple inheritance is not supported through class in java,


but it is possible by an interface, why?
Multiple inheritance is not supported in the case of class because of ambiguity. However,
it is supported in case of an interface because there is no ambiguity. It is because its
implementation is provided by the implementation class. For example:
33 | D e p a r t m e n t o f C o m p u t e r A p p l i c a ti o n s , M E S G o l d e n
J u b i l e e C o l l e g e K o tt a y a m
interface Printable{  
void print();  
}  
interface Showable{  
void print();  
}  
  
class TestInterface implements Printable, Showable{  
public void print(){System.out.println("Hello");}  
public static void main(String args[]){  
TestInterface obj = new TestInterface();  
obj.print();  
 }  
}  

Output:

Hello

As you can see in the above example, Printable and Showable interface have same
methods but its implementation is provided by class TestTnterface, so there is no
ambiguity.

Interface inheritance
A class implements an interface, but one interface extends another interface.

interface Printable{  
void print();  
}  
interface Showable extends Printable{  
void show();  
}  
class TestInterface implements Showable{  
public void print(){System.out.println("Hello");}  
public void show(){System.out.println("Welcome");}  
  
public static void main(String args[]){  
TestInterface obj = new TestInterface();  
obj.print();  
obj.show();  
 }  
}  

34 | D e p a r t m e n t o f C o m p u t e r A p p l i c a ti o n s , M E S G o l d e n
J u b i l e e C o l l e g e K o tt a y a m
Output:
Hello
Welcome

Differenece between Class and Interface


Class Interface
The member of a class can be constant or The member of an interface are always
variable. declared as constant, ie. The values are final.
The class definition can contain code for each The methods in an interface are abstract in
of its methods. That is, the methods can be nature, ie., there is no code associated with
abstract or non-abstract. them. It is later defined by the class that
implements the interface.
It can be instantiated by declaring objects. It cannot be used to declare objects. It can only
be inherited by a class.
It can use various access specifiers like public, It can only use the public access specifier
private, or protected.

35 | D e p a r t m e n t o f C o m p u t e r A p p l i c a ti o n s , M E S G o l d e n
J u b i l e e C o l l e g e K o tt a y a m

You might also like