KEMBAR78
Unit II Notes OOP | PDF | Class (Computer Programming) | Programming
0% found this document useful (0 votes)
20 views44 pages

Unit II Notes OOP

The document covers key concepts in Java programming, focusing on inheritance, constructors, and packages. It explains the use of constructors for object initialization, including default and parameterized constructors, as well as method overloading and argument passing techniques. Additionally, it discusses the organization of classes into packages, the benefits of inheritance, and the use of the 'this' keyword and garbage collection in Java.

Uploaded by

Selva Kumar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views44 pages

Unit II Notes OOP

The document covers key concepts in Java programming, focusing on inheritance, constructors, and packages. It explains the use of constructors for object initialization, including default and parameterized constructors, as well as method overloading and argument passing techniques. Additionally, it discusses the organization of classes into packages, the benefits of inheritance, and the use of the 'this' keyword and garbage collection in Java.

Uploaded by

Selva Kumar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 44

1

UNIT II
INHERITANCE AND INTERFACES

Constructors in java - Packages - Inheritance – Super classes- Sub classes –Protected members –
Constructors in sub classes- the Object class – Abstract classes and methods- Final methods and
classes – Interfaces – Defining an interface, Implementing interface, Differences between classes
and interfaces and extending interfaces

CONSTRUCTORS

Java allows objects to initialize themselves when they are created. This automatic
initialization is performed through the use of a constructor.

 A constructor initializes an object immediately upon creation.


 It has the same name as the class in which it resides and is syntactically similar to a
method.
 Once defined, the constructor is automatically called immediately after the object is
created, before the new operator completes.
 Constructors look a little strange because they have no return type, not even void. This is
because the implicit return type of a class’ constructor is the class type itself.
 It is the constructor’s job to initialize the internal state of an object so that the code
creating an instance will have a fully initialized, usable object immediately.

Default Constructors

A default constructor is a constructor with no parameters. This default constructor sets all the
instance fields to their default values. So, all numeric data contained in the instance fields would
be 0, all boolean values would be false, and all object variables would be set to null.

General Form:

public ClassName()
{
}
Syntax to create object:
class name class-var = new classname( );
Parameterized Constructors:

A paramaterized constructor is a constructor with parameters. This parameterized


constructor sets all the instance fields to specific values.

public class Sum


{
1
2

int a,b,c;
public Sum()
{
a=0;
b=0;
}
public Sum(int x,int y)
{
a=x;
b=y;
}
void operation()
{
c=a+b;
}
void print()
{
System.out.println("Sum of "+a+" and "+b+" is "+c);
}
}
public class Test {
public static void main(String[] args) {
int x,y;
Scanner s=new Scanner(System.in);
System.out.println("Enter x");
x=s.nextInt();
System.out.println("Enter y");
y=s.nextInt();
Sum s1=new Sum(x,y);
s1.operation();
s1.print();
}
}
Sample output:
Enter x
2
Enter y
3
Sum of 2 and 3 is 5

OVERLOADING CONSTRUCTORS

In addition to overloading normal methods, we can also overload constructor methods.

Example:
2
3

public class Student {


String name;
int rollno;
Student()
{
name="";
rollno=0;
}
Student(String a,int b)
{
name=a;
rollno=b;
}
void print()
{
System.out.println("Name is: "+name);
System.out.println("Rollno is: "+rollno);
}
}
public class Example {
public static void main(String[] args) {
Student s1=new Student();
s1.print();
Student s2=new Student("Maria",19);
s2.print();
}
}
Output:
Name is:
Rollno is: 0
Name is: Maria
Rollno is: 19

USING OBJECTS AS PARAMETERS

It is possible to pass objects as parameters to methods. Also a method can return any type
of data, including class types that you create.

EXAMPLE:

public class complex {


3
4

int x,y;
public complex()
{
x=0;
y=0;
}
public complex(int a,int b)
{
x=a;
y=b;
}
complex add(complex c1,complex c2)
{
complex t=new complex();
t.x=c1.x+c2.x;
t.y=c1.y+c2.y;
return t;
}
void print()
{
System.out.println("a is: "+x);
System.out.println("b is: "+y);
}
}
public class Example {
public static void main(String[] args) {
complex c1=new complex(2,2);
complex c2=new complex(3,3);
complex c3=new complex();
c3=c3.add(c1, c2);
System.out.println("c1:");
c1.print();
System.out.println("c2:");
c2.print();
System.out.println("c3:");
c3.print();
}
}
Output:
c1:
4
5

a is: 2
b is: 2
c2:
a is: 3
b is: 3
c3:
a is: 5
b is: 5

ARGUMENT PASSING METHODS

In general, there are two ways that a computer language can pass an argument to a
subroutine.

 Call by value
This approach copies the value of an argument into the formal parameter of the
subroutine. Therefore, changes made to the parameter of the subroutine have no
effect on the argument.
 Call by Reference
In this approach, a reference to an argument (not the value of the argument) is
passed to the parameter. Inside the subroutine, this reference is used to access the
actual argument specified in the call. This means that changes made to the
parameter will affect the argument used to call the subroutine.

Java uses both approaches, depending upon what is passed.

In Java, when you pass a primitive type to a method, it is passed by value. Thus, what occurs to
the parameter that receives the argument has no effect outside the method.

Example:

public class Test {


void add(int a,int b)
{
a=a+5;
b=b+5;
}
}
public class Example {
public static void main(String[] args) {
Test t1=new Test();
int x=5,y=10;
5
6

System.out.println("Before method call");


System.out.println("x="+x);
System.out.println("y="+y);
t1.add(x,y);
System.out.println("After method call");
System.out.println("x="+x);
System.out.println("y="+y);
}
}
Output:
Before method call
x=5
y=10
After method call
x=5
y=10
When you pass an object to a method, it is passed by call-by-reference. Keep in mind that
when you create a variable of a class type, you are only creating a reference to an object. Thus,
when you pass this reference to a method, the parameter that receives it will refer to the same
object as that referred to by the argument. This effectively means that objects are passed to
methods by use of call-by-reference. Changes to the object inside the method affects the object
used as an argument.

Example:
public class Test {
int a,b;
Test(int x,int y)
{
a=x;
b=y;
}
void add(Test t)
{
t.a=t.a+5;
t.b=t.b+5;
}
}
public class Example {
public static void main(String[] args) {
Test t1=new Test(2,3);

6
7

System.out.println("Before method call");


System.out.println("a="+t1.a);
System.out.println("b="+t1.b);
t1.add(t1);
System.out.println("After method call");
System.out.println("a="+t1.a);
System.out.println("b="+t1.b);
}
}
Output:
Before method call
a=2
b=3
After method call
a=7
b=8

The this Keyword

Sometimes a method will need to refer to the object that invoked it. To allow this, Java
defines the this keyword. this can be used inside any method to refer to the current object. That
is, this is always a reference to the object on which the method was invoked.

public Sum(int x,int y)


{
this.a=x;
this.b=y;
}
Program:

import java.util.*;
class Sum
{
int a,b,c;
public Sum()
{
this.a=0;
this.b=0;
}
public Sum(int x,int y)
{
7
8

this.a=x;
this.b=y;
}
void operation()
{
c=a+b;
}
void print()
{
System.out.println("Sum of "+a+" and "+b+" is "+c);
}
}
public class Test {
public static void main(String[] args) {
int x,y;
Scanner s=new Scanner(System.in);
System.out.println("Enter x");
x=s.nextInt();
System.out.println("Enter y");
y=s.nextInt();
Sum s1=new Sum(x,y);
s1.operation();
s1.print();
}
}
output:
Enter x
4
Enter y
6
Sum of 4 and 6 is 10

Instance Variable Hiding

It is illegal in Java to declare two local variables with the same name inside the same or
enclosing scopes. But we can have local variables, including formal parameters to methods,
which overlap with the names of the class’ instance variables. However, when a local variable
has the same name as an instance variable, the local variable hides the instance variable.

Example:

8
9

public Sum(int a,int b)


{
this.a=a;
this.b=b;
}
Garbage Collection

In Java,objects are dynamically allocated by using the new operator. In some languages,
such as C++, dynamically allocated objects must be manually released by use of a delete
operator. Java takes a different approach; it handles de-allocation automatically. The technique
that accomplishes this is called garbage collection.

When no references to an object exist, that object is assumed to be no longer needed, and
the memory occupied by the object can be reclaimed. Garbage collection only occurs
periodically (if at all) during the execution of your program.

The finalize( ) Method

Sometimes an object will need to perform some action when it is destroyed. For example,
if an object is holding some non-Java resource such as a file handle, then you might want to
make sure these resources are freed before an object is destroyed. To handle such situations, Java
provides a mechanism called finalization.

To add a finalizer to a class, you simply define the finalize( ) method. The Java run time
calls that method whenever it is about to recycle an object of that class. Inside the finalize( )
method, you will specify those actions that must be performed before an object is destroyed. The
garbage collector runs periodically, checking for objects that are no longer referenced by any
running state or indirectly through other referenced objects. Right before an asset is freed, the
Java run time calls the finalize( ) method on the object.

The finalize( ) method has this general form:

protected void finalize( )

// finalization code here

Here, the keyword protected is a specifier that prevents access to finalize( ) by code defined

outside its class.

9
10

PACKAGES

Java allows you to group classes in a collection called a package. Packages are
convenient for organizing your work and for separating your work from code libraries provided
by others.

The standard Java library is distributed over a number of packages, including java.lang,
java.util, java.net, and so on. The standard Java packages are examples of hierarchical packages.
Just as you have nested subdirectories on your hard disk, you can organize packages by using
levels of nesting. All standard Java packages are inside the java and javax package hierarchies.

The main reason for using packages is

 To guarantee the uniqueness of class names.


The package can then be further subdivided into subpackages.

Defining a package:

To create a package is quite easy: simply include a package command as the first
statement in a Java source file. Any classes declared within that file will belong to the specified
package.

The package statement defines a name space in which classes are stored. If you omit the
package statement, the class names are put into the default package, which has no name.

This is the general form of the package statement:

package pkg;

Here, pkg is the name of the package.

Java uses file system directories to store packages. More than one file can include the same
package statement. The package statement simply specifies to which package the classes defined
in a file belong. It does not exclude other classes in other files from being part of that same
package.

You can create a hierarchy of packages. To do so, simply separate each package name

from the one above it by use of a period. The general form of a multileveled package statement

is shown here:

package pkg1[.pkg2[.pkg3]];

A package hierarchy must be reflected in the file system of your Java development system. For
example, a package declared as
10
11

package java.awt.image;

needs to be stored in java\awt\image in a Windows environment

For example, the file Employee.java in

package p1;

public class Employee

...

If you don’t put a package statement in the source file, then the classes in that source file belong
to the default package. The default package has no package name.

Place source files into a subdirectory that matches the full package name. For example, all source
files in the package p1 package should be in a subdirectory p1 on Windows). The compiler
places the class files into the same directory structure.

package p1.p2;

public class Employee

{
...
}
All source files in the package p1 package should be in a subdirectory p1/p2 on Windows.

To compile this program, simply change to the base directory and run the command

javac PackageTest.java

The compiler automatically finds the file p1/Employee.java and compiles it.

Class Importation

A class can use all classes from its own package and all public classes from other
packages. You can access the public classes in another package in two ways.

1. Simply to add the full package name in front of every class name

For example:

11
12

java.util.Date today = new java.util.Date();

This is obviously tedious.

2. Use the import statement

Once you use import, you no longer have to give the classes their full names. You
can import a specific class or the whole package. You place import statements at the top
of your source files (but below any package statements). For example, you can import all
classes in the java.util package with the statement

import java.util.*;

Then you can use

Date today = new Date();

without a package prefix.

You can also import a specific class inside a package:

import java.util.Date;

Example:

package p1;
public class Sum
{
int a,b;
public Sum()
{
a=0;b=0;
}
public Sum(int x,int y)
{
a=x;
b=y;
}
public void add()
{
System.out.println("sum="+(a+b));
}
}
//Main Program
12
13

import p1.*;
class Test
{
public static void main(String[] args)
{
Sum a1=new Sum(3,5);
a1.add();
}
}
Output:
sum=8

Example of program with subpackages:

package p1.p2;
public class Sum
{
int a,b;
public Sum()
{
a=0;b=0;
}
public Sum(int x,int y)
{
a=x;
b=y;
}
public void add()
{
System.out.println("sum="+(a+b));
}
}
//Main Program
import p1.p2.*;
class Test
{
public static void main(String[] args)
{
Sum a1=new Sum(3,5);
a1.add();
13
14

}
}
Output:
sum=8

INHERITANCE
Inheritance is the process of creating a class by reusing the properties of an existing
class.
The idea behind inheritance is that you can create new classes that are built on existing
classes. When you inherit from an existing class, you reuse (or inherit) its methods and you can
add new methods and fields to adapt your new class to new situations.
Advantage of Inheritance:
Code Reusability
Classes, Superclasses, and Subclasses:
Use the Java keyword extends to denote inheritance.
Syntax:
class subclassname extends superclassname
{
added methods and fields
}
Example:
Suppose you work for a company at which managers are treated differently from other
employees. Managers are, of course, just like employees in many respects. Both employees and
managers are paid a salary. However, managers get bonuses if they actually achieve what they
are supposed to do. This is the kind of situation needs inheritance.
You need to define a new class, Manager, and add functionality. But you can retain some
of what you have already programmed in the Employee class, and all the fields of the original
class can be preserved. More abstractly, there is an obvious “is–a” relationship between Manager
and Employee. Every manager is an employee: This “is–a” relationship is the hallmark of
inheritance.
Here is how you define a Manager class that inherits from the Employee class.
class Employee
{
methods and fields
}
class Manager extends Employee
{
added methods and fields
}

14
15

The keyword extends indicates that you are making a new class that derives from an
existing class. The existing class is called the superclass, base class, or parent class. The new
class is called the subclass, derived class, or child class.
In our example, the Employee class is a superclass and Manager is the subclass.
Subclasses have more functionality than their super classes.
When designing classes, you place the most general methods into the superclass and
more specialized methods in its subclasses.

Types of Inheritance
1. SINGLE INHERITANCE:
When a class extends another one class only then we call it a single inheritance.

EXAMPLE:
//Employee class
import java.util.*;
public class Employee {
private String name;
private double salary;
void read()
{
System.out.println("enter the name");
Scanner s=new Scanner(System.in);
name=s.next();
System.out.println("enter the salary");
salary=s.nextDouble();
}
public void print()
{
System.out.println("Name: "+name);
System.out.println("Salary: "+salary);
}
public void raiseSalary(double byPercent)
{
double raise = salary * byPercent / 100;
salary += raise;
15
16

}
}
//Manager class
import java.util.*;
public class Manager extends Employee
{
private double bonus;
void readManager()
{
Scanner s=new Scanner(System.in);
System.out.println("enter the bonus");
bonus=s.nextDouble();
}
public void printManager()
{
System.out.println("bonus :"+bonus);
}
}
//Main class
public class Test {
public static void main(String[] args) {
Employee e=new Employee();
e.read();
e.raiseSalary(5);
e.print();
Manager m=new Manager();
m.read();
m.readManager();
m.print();
m.printManager();
}
}
Output:
enter the name
aaaa
enter the salary
20000
Name: aaaa
Salary: 21000.0
enter the name
16
17

bbbb
enter the salary
50000
enter the bonus
5000
Name: bbbb
Salary: 50000.0
bonus :5000.0

2. HIERARCHICAL INHERITANCE:
If one class is inherited by many sub classes, then we call it as Hierarchical inheritance.

Example:
import java.util.*;
public class Shape
{
double height; // To hold height.
double width; //To hold width or base
public void read()
{
Scanner s=new Scanner(System.in);
System.out.println("Enter height ");
height=s.nextInt();
System.out.println("Enter width");
width=s.nextInt();
}}
public class Rectangle extends Shape
{
public double getArea()
{
return height * width;
}
}
public class Triangle extends Shape
17
18

{
public double getArea()
{
return height * width / 2;
}
}
public class Test
{
public static void main(String[] args)
{
Rectangle r = new Rectangle();
r.read();
Triangle t=new Triangle();
t.read();
System.out.println("Area of rectangle : " + r.getArea());
System.out.println("Area of triangle : " + t.getArea());
}}
Enter height
3
Enter width
3
Enter height
3
Enter width
3
Area of rectangle : 9.0
Area of triangle : 4.5

3. MULTILEVEL INHERITANCE:
If one class is inherited from another derived class, then we call it as Multilevel
inheritance.

Example:
public class PERSON {
private String name;
18
19

private int age;


public void read1()
{
Scanner s=new Scanner(System.in);
System.out.println("Enter name");
name=s.next();
System.out.println("Enter age");
age=s.nextInt();

}
public void print1()
{
System.out.println("Name:"+name);
System.out.println("Age:"+age);
}
}
public class student extends PERSON{
private int rollno;
private double cgpa;
public void read2()
{
Scanner s=new Scanner(System.in);
System.out.println("Enter rollno");
rollno=s.nextInt();
System.out.println("Enter cgpa");
cgpa=s.nextDouble();
}
public void print2()
{
System.out.println("Rollno"+rollno);
System.out.println("Cgpa"+cgpa);
}
}
public class Employee extends student{
private int empno;
private int salary;
public void read3()
{
Scanner s=new Scanner(System.in);
System.out.println("Enter empno");
19
20

empno=s.nextInt();
System.out.println("Enter salary");
salary=s.nextInt();

}
public void print3()
{
System.out.println("Emp.No"+empno);
System.out.println("Salary"+salary);
} }
public class Test{
public static void main(String[] args) {
Employee e=new Employee();
e.read1();
e.read2();
e.read3();
e.print1();
e.print2();
e.print3();
}
}

MULTIPLE INHERITANCE
If one class is derived from more than one base class, then it is multiple inheritance.
Note: Java does not support Multiple inheritance.

PROTECTED MEMBERS:
The private members of a class cannot be directly accessed outside the class. Only
methods of that class can access the private members directly. Sometimes it may be necessary
for a subclass to access a private member of a superclass. If you make a private member public,
then anyone can access that member. So, if a member of a superclass needs to be (directly)
accessed in a subclass and yet still prevent its direct access outside the class, you must declare
that member protected.
20
21

Modifier Class Subclass World


public Y Y Y
protected Y Y N
private Y N N

Example:
import java.util.*;
public class Shape
{
protected double height; // To hold height.
protected double width; //To hold width or base
public void read()
{
Scanner s=new Scanner(System.in);
System.out.println("Enter height ");
height=s.nextInt();
System.out.println("Enter width");
width=s.nextInt();
}}
public class Rectangle extends Shape
{
public double getArea()
{
return height * width; //accessing protected members
}
}
public class Test
{
public static void main(String[] args)
{
Rectangle rectangle = new Rectangle();
rectangle.read();
System.out.println("Area of rectangle : " + rectangle.getArea());
}}
Output:
Enter height
3
Enter width
3
Area of rectangle : 9.0
21
22

METHOD OVERRIDING
In a class hierarchy, when a method in a subclass has the same name and type signature
as a method in its superclass, then the method in the subclass is said to override the method in the
superclass. When an overridden method is called from within a subclass, it will always refer to
the version of that method defined by the subclass. The version of the method defined by the
superclass will be hidden.
Example:
public class Base {
public void print()
{
System.out.println("Base class");
}
}
public class Derived extends Base
{
public void print()
{
System.out.println("Derived class");
}
}
public class Test{
public static void main(String[] args) {
Base b=new Base();
Derived d=new Derived();
b.print();
d.print();
}
}
output:
Base class
Derived class

CONSTRUCTORS IN SUBCLASSES:
A subclass can have its own private data members, so a subclass can also have its own
constructors. The constructors of the subclass can initialize only the instance variables of the
subclass. Thus, when a subclass object is instantiated the subclass object must also automatically
execute one of the constructors of the superclass.
In Java, default constructor of base class gets automatically called when an object of
the derived class is created.

22
23

In general, when a derived class object is created, first the default constructor of the base
class is called implicitly, and then the corresponding (default or parameterized) constructor of the
derived class is executed.
But, if we want to call parameterized constructor of base class, then we can call it
using super keyword.
Default Constructors in subclasses:
public class Base {
Base()
{
System.out.println("Base class");
}
}
public class Derived extends Base{
Derived()
{
System.out.println("Derived class");
}
}
public class Test {
public static void main(String[] args) {

Base b=new Base();


Derived d=new Derived();
}
}
output:
Base class
Base class
Derived class
Parameterized constructors in subclasses:
public class Base {
int a,b;
Base()
{
System.out.println("Base class Default constructor");
a=0;
b=0;
}
Base(int x,int y)
{
23
24

System.out.println("Base class Parameterized constructor");


a=x;
b=y;
}
}
public class Derived extends Base{
int c,d;
Derived ()
{
System.out.println("Derived class Default constructor");
a=0;
b=0;
}
Derived (int x,int y)
{
System.out.println("Derived class Parameterized constructor");
c=x;
d=y;
}
}
public class JavaApplication3 {
public static void main(String[] args) {
Base b1=new Base();
Derived d1=new Derived();
Base b2=new Base(2,3);
Derived d2=new Derived(3,3);
}
}
output:
Base class Default constructor
Base class Default constructor
Derived class Default constructor
Base class Parameterized constructor
Base class Default constructor
Derived class Parameterized constructor

USE OF SUPER KEYWORD:


Whenever a subclass needs to refer to its immediate superclass, it can do so by use of the
keyword super.
super has two general forms.
24
25

 The first calls the superclass’ constructor.


 The second is used to access a member of the superclass that has been hidden by a
member of a subclass.
Using super to Call Superclass Constructors
A subclass can call a constructor defined by its superclass by use of the following form of
super:
super(arg-list);
Here, arg-list specifies any arguments needed by the constructor in the superclass. super( ) must
always be the first statement executed inside a subclass’ constructor.
Second Use for super
The second form of super acts somewhat like this, except that it always refers to the
superclass of the subclass in which it is used. This usage has the following general form:
super.member
Here, member can be either a method or an instance variable.
This second form of super is most applicable to situations in which member names of a subclass
hide members by the same name in the superclass.

Example 1:
public class Base {
int a,b;
Base()
{
System.out.println("Base class Default constructor");
a=0;
b=0;
}
Base(int x,int y)
{
System.out.println("Base class Parameterized constructor");
a=x;
b=y;
}
void print()
{
System.out.println("a="+a);
System.out.println("b="+b);
}
}
public class Derived extends Base{
int c,d;
25
26

Derived ()
{
System.out.println("Derived class Default constructor");
a=0;
b=0;
}
Derived (int a,int b,int x,int y)
{
super(a,b);
System.out.println("Derived class Parameterized constructor");
c=x;
d=y;
}
void print()
{
super.print();
System.out.println("c="+c);
System.out.println("d="+d);
}
}
public class JavaApplication3 {
public static void main(String[] args) {
Base b1=new Base();
b1.print();
Derived d1=new Derived();
d1.print();
Base b2=new Base(2,3);
b2.print();
Derived d2=new Derived(2,2,3,3);
d2.print();
} }
output:
Base class Default constructor
a=0
b=0
Base class Default constructor
Derived class Default constructor
a=0
b=0
c=0
26
27

d=0
Base class Parameterized constructor
a=2
b=3
Base class Parameterized constructor
Derived class Parameterized constructor
a=2
b=2
c=3
d=3

Example 2:
public class Base {
int a;
void read()
{
Scanner s=new Scanner(System.in);
System.out.println("Enter a");
a=s.nextInt();
}
void print()
{
System.out.println("a="+a);
}
}
public class Derived extends Base{
int a;
void read()
{ super.read();
Scanner s=new Scanner(System.in);
System.out.println("Enter a");
a=s.nextInt();
}
void calculate()
{
System.out.println("sum="+(a+super.a));
}
void print()
{ super.print();
System.out.println("a="+a);
27
28

}
}
public class Test{
public static void main(String[] args) {
Derived d=new Derived();
d.read();
d.calculate();
d.print();
}}
Output:
Enter a 2
Enter a 3
Sum=5
a=2
a=3
Inheritance Hierarchies:
The collection of all classes extending a common superclass is called an inheritance
hierarchy. The path from a particular class to its ancestors in the inheritance hierarchy is its
inheritance chain.

OBJECT: THE COSMIC SUPERCLASS


There is one special class, Object, defined by Java. All other classes are subclasses of
Object.
That is, Object is a superclass of all other classes. This means that a reference variable of
type Object can refer to an object of any other class. Also, since arrays are implemented as
classes, a variable of type Object can also refer to any array.

You can use a variable of type Object to refer to objects of any type:
Object obj = new Employee("Harry Hacker", 35000);
Of course, a variable of type Object is only useful as a generic holder for arbitrary values.
To do anything specific with the value, you need to have some knowledge about the original type
and apply a cast:
Employee e = (Employee) obj;
In Java, only the primitive types (numbers, characters, and boolean values) are not objects.
All array types, no matter whether they are arrays of objects or arrays of primitive types, are
class types that extend the Object class.
Employee[] staff = new Employee[10];
obj = staff; // OK
obj = new int[10]; // OK
Example:
28
29

public class Base {


int a;
public void read()
{ Scanner s=new Scanner(System.in);
System.out.println("Enter a");
a=s.nextInt(); }
public void print()
{
System.out.println("a="+a);
}}
public class Test {
public static void main(String[] args) {
Object o=new Base();
Base b=(Base)o;
b.read();
b.print();
}
}
Output:
Enter a 2
a=2

Object defines the following methods, which means that they are available in every object.

Example:
public class Number {
int a,b;
}
public class Test {
public static void main(String[] args) {
Number n1=new Number();
29
30

Number n2=new Number();


System.out.println("Equals method "+n1.equals(n2));
System.out.println("toString "+n1.toString());
System.out.println("hashcode "+n1.hashCode());
Class c = n1.getClass();
System.out.println("Class of Object obj is : "
+ c.getName());
}}
output:
Equals method false
toString Test.Number@659e0bfd
hashcode 1704856573
Class of Object obj is : Test.Number

PREVENTING INHERITANCE: FINAL CLASSES AND METHODS


Final Fields:
Fields can also be declared as final. A final field cannot be changed after the object has
been constructed.
public class Number {
final int a=5;
public void change()
{
System.out.println("a="+a);
}
}
public class JavaApplication3 {
public static void main(String[] args) {
Number n1=new Number();
n1.change();
}
}
output:
a=5
//if the statement in change() method is

public void change()


{
a++;
}
It leads to an error.
30
31

Final Methods:
It is possible to make a specific method in a class final. A final method cannot be
overridden. Which means even though a sub class can call the final method of parent class
without any issues but it cannot override it.
public class Base {
final void print()
{
System.out.println("Base class");
}
}
public class Derived extends Base{

void display()
{
super.print();
}
//This method definition will lead to error since print() is final in Base class
/*void print()
{
super.print();
}*/
}
public class JavaApplication3 {
public static void main(String[] args) {
Derived d=new Derived();
d.display();
}
}
output:
Base class
Final Classes:
Classes that cannot be extended are called final classes, and you use the final modifier in
the definition of the class to indicate this.
Simply declare the class using the final modifier, as follows:
Example:
final class Employee
{
.....
}
31
32

we can also make a subclass as final while creating it using final keyword.
Example:
final class Executive extends Manager
{. . .
}
Example:
final public class Base {
void print()
{
System.out.println("Base class");
}
}
//trying to create a subclass from a final class leads to error
public class Derived extends Base
{ }
Note:All methods in a final class are automatically final. However, if a class is declared
final, only the methods, not the fields, are automatically final.
Points to Remember:
1. A constructor cannot be declared as final.
2. All variables declared in an interface are by default final.
3. We cannot change the value of a final variable.
4. A final method cannot be overridden.
5. A final class not be inherited.

ABSTRACT CLASSES
There are situations in which you will want to define a superclass that declares the
structure of a given abstraction without providing a complete implementation of every method.
That is, sometimes you will want to create a superclass that only defines a generalized form that
will be shared by all of its subclasses, leaving it to each subclass to fill in the details. Such a class
determines the nature of the methods that the subclasses must implement.
An abstract class is a superclass that cannot be instantiated and is used to state or
define general characteristics. Abstract class is declared with abstract keyword. It can have
abstract and non-abstract methods (method with body).
Abstract Methods:
Abstract Method is a method without method body.
It is not uncommon for a method to have no meaningful definition in the context of its
superclass. To use such a method, declare it as an abstract method.
General form of an abstract method:
abstract type name(parameter-list);
As you can see, no method body is present.
32
33

To declare a class abstract, you simply use the abstract keyword in front of the class
keyword at the beginning of the class declaration.
General form of an abstract class:
abstract class classname
{
//instance variables and code
}
A class with one or more abstract methods must itself be declared abstract.
abstract class Person
{...
public abstract String getDescription();
}
In addition to abstract methods, abstract classes can have fields and concrete methods.
abstract class Person
{
private String name;
public abstract String getDescription();
public String getName()
{
return name;
}
}
Abstract methods act as placeholders for methods that are implemented in the subclasses.
When you extend an abstract class, you have two choices.
1. You can leave some or all of the abstract methods undefined; then you must tag the
subclass as abstract as well.
Example:
abstract Class Employee extends Person
{
//
}
Here the abstract method getDescription() is not redefined. So the class person must also be
defined abstract.
2. you can define all methods, and the subclass is no longer abstract.
For example, we will define a Student class that extends the abstract Person class and
implements the getDescription() method. None of the methods of the Student class are
abstract, so it does not need to be declared as an abstract class.
abstract Class Employee extends Person
{
public String getDescription()
33
34

{
//code
}
}
A class can even be declared as abstract even though it has no abstract methods.
Example:
abstract class Person
{
private String name;
public String getName()
{
return name;
}
}
Abstract classes cannot be instantiated. That is, if a class is declared as abstract, no
objects of that class can be created.
For example, the expression
new Person("Vince Vu") is an error.
However, you can create objects of concrete subclasses. Note that you can still create object
variables of an abstract class, but such a variable must refer to an object of a nonabstract
subclass. For example:
Person p = new Student("Vince Vu", "Economics");
Here p is a variable of the abstract type Person that refers to an instance of the nonabstract
subclass Student.
Example:
abstract public class Figure {
abstract void findArea();
}
public class Rectangle extends Figure {
double a,b;
public Rectangle()
{
a=0.0d;
b=0.0d;
}
public Rectangle(double x,double y)
{
a=x;
b=y;
}
34
35

void findArea()
{
System.out.println("Area of Rectangle="+a*b);
}
}

public class Triangle extends Figure{


double a,b;
public Triangle()
{
a=0.0d;
b=0.0d;
}
public Triangle(double x,double y)
{
a=x;
b=y;
}
void findArea()
{
System.out.println("Area of Triangle="+0.5*a*b);
}
}
public class Test {
public static void main(String[] args) {
Figure f;
Rectangle r=new Rectangle(2,3);
f=r;
f.findArea();
Triangle t=new Triangle(2,3);
f=t;
f.findArea();
}}
Output:
Area of Rectangle=6.0
Area of Triangle=3.0

35
36

INTERFACES
Interfaces are syntactically similar to classes, but they lack instance variables, and their
methods are declared without any body. Once it is defined, any number of classes can implement
an interface. Also, one class can implement any number of interfaces.
To implement an interface, a class must create the complete set of methods defined by
the interface. However, each class is free to determine the details of its own implementation. By
providing the interface keyword, Java allows you to fully utilize the “one interface, multiple
methods” aspect of polymorphism.
Defining an Interface
An interface is defined much like a class.
General form of an interface:
accessspecifier interface interface_name
{
return-type method-name1(parameter-list);
return-type method-name2(parameter-list);
type final-varname1 = value;
type final-varname2 = value;
// ...
return-type method-nameN(parameter-list);
type final-varnameN = value;
}
When no access specifier is included, then default access results, and the interface is only
available to other members of the package in which it is declared. When it is declared as public,
the interface can be used by any other code. In this case, the interface must be the only public
interface declared in the file, and the file must have the same name as the interface. name is the
name of the interface, and can be any valid identifier.
Notice that the methods that are declared have no bodies. They end with a semicolon
after the parameter list. They are, essentially, abstract methods; there can be no default
implementation of any method specified within an interface.
Each class that includes an interface must implement all of the methods. Variables can be
declared inside of interface declarations. They are implicitly final and static, meaning they
cannot be changed by the implementing class. They must also be initialized. All methods and
variables are implicitly public.
Example:
interface stack
{
int tos=-1;
void push(int x);
int pop();
}

Implementing Interfaces
Once an interface has been defined, one or more classes can implement that interface. To
implement an interface, include the implements clause in a class definition, and then create the
methods defined by the interface.
The general form of a class that includes the implements clause looks like this:
36
37

class classname [implements interface [,interface...]]


{
// class-body
}
Example:
class StackClass implements stack
{
void push(int x)
{
//code
}
int pop()
{
//code
}
}
If a class implements more than one interface, the interfaces are separated with a comma.
class classname implements interface1,interface2,…interfacen
{
//code
}
If a class implements two interfaces that declare the same method, then the same method
will be used by clients of either interface. The methods that implement an interface must be
declared public. Also, the type signature of the implementing method must match exactly the
type signature specified in the interface definition.
REMEMBER When you implement an interface method, it must be declared as public.
It is both permissible and common for classes that implement interfaces to define
additional members of their own.

Accessing Implementations Through Interface References


You can declare variables as object references that use an interface rather than a class
type. Any instance of any class that implements the declared interface can be referred to by such
a variable. When you call a method through one of these references, the correct version will be
called based on the actual instance of the interface being referred to. This is one of the key
features of interfaces. The method to be executed is looked up dynamically at run time, allowing
classes to be created later than the code which calls methods on them. The calling code can
dispatch through an interface without having to know anything about the “callee.” This process
is similar to using a superclass reference to access a subclass object.
Example:
stack s;
s=new StackClass();
s.push();
s.pop();

37
38

Partial Implementations
If a class includes an interface but does not fully implement the methods defined by that
interface, then that class must be declared as abstract.
Example:
abstract class StackClass implements stack
{
void push(int x)
{
//code
}
//pop() not defined
}

Nested Interfaces
An interface can be declared a member of a class or another interface. Such an interface
is called a member interface or a nested interface. A nested interface can be declared as public,
private, or protected. This differs from a top-level interface, which must either be declared as
public or use the default access level, as previously described. When a nested interface is used
outside of its enclosing scope, it must be qualified by the name of the class or interface of which
it is a member. Thus, outside of the class or interface in which a nested interface is declared, its
name must be fully qualified.

Applying Interfaces
public interface Intstack {
void push(int item); // store an item
int pop(); // retrieve an item
void Display();
}

public class FixedStack implements Intstack{


private int stck[];
private int tos;
// allocate and initialize stack
FixedStack(int size)
{
stck = new int[size];
tos = -1;
}
// Push an item onto the stack
public void push(int item) {
if(tos==stck.length-1) // use length member
System.out.println("Stack is full.");
else
stck[++tos] = item;
}
// Pop an item from the stack
38
39

public int pop() {


if(tos < 0) {
System.out.println("Stack underflow.");
return 0;
}
else
return stck[tos--];
}
public void Display()
{
for(int i=0;i<=tos;i++)
{
System.out.println(stck[i]);
}
}
}
public class Example {
public static void main(String[] args) {
int ch,choice,x;
Intstack s1;
FixedStack f=new FixedStack(5);
s1=f;
Scanner s=new Scanner(System.in);
do
{
System.out.println("1.push\n2.pop\n3.Display");
System.out.println("Enter choice");
choice=s.nextInt();
switch(choice)
{
case 1:
System.out.println("Enter element to be pushed");
x=s.nextInt();
s1.push(x);
break;
case 2:
System.out.println("The popped element is"+s1.pop());
break;
case 3:
System.out.println("Elements in the stack are:");
s1.Display();
}
System.out.println("Want to continue");
ch=s.nextInt();
}while(ch==1);
}
39
40

Output:
1.push
2.pop
3.Display
Enter choice
1
Enter element to be pushed
4
Want to continue
1
1.push
2.pop
3.Display
Enter choice
1
Enter element to be pushed
6
Want to continue
1
1.push
2.pop
3.Display
Enter choice
3
Elements in the stack are:
4
6

Variables in Interfaces
You can use interfaces to import shared constants into multiple classes by simply
declaring an interface that contains variables that are initialized to the desired values. When you
include that interface in a class (that is, when you “implement” the interface), all of those
variable names will be in scope as constants. If an interface contains no methods, then any class
that includes such an interface doesn’t actually implement anything.

Interfaces can be Extended


One interface can inherit another by use of the keyword extends. The syntax is the same
as for inheriting classes. When a class implements an interface that inherits another interface, it
must provide implementations for all methods defined within the interface inheritance chain.
Example:
interface interface1 extends interface2
{
//code
}
40
41

Example:
interface vehicleone{
int speed=90;
public void distance();
}
interface vehicletwo extends vehicleone{
int distance=100;
public void speed();
}
class Vehicle implements vehicleone,vehicletwo{
public void distance(){
int distance=speed*100;
System.out.println("distance travelled is "+distance);
}
public void speed(){
int speed=distance/100;
}
}
class Test{
public static void main(String args[]){
Vehicle obj=new Vehicle();
obj.distance();
obj.speed();
}
}
Output:
distance travelled is 9000
Example program using interfaces and class:
class student
{
int rollNumber;
void readNumber()
{
System.out.println("Enter Rollnumber");
Scanner s=new Scanner(System.in);
rollNumber=s.nextInt();
}
void printNumber()
{
System.out.println("Roll Number="+rollNumber);
41
42

}
}

class test extends student


{
float part1,part2;
void readMarks()
{
Scanner s=new Scanner(System.in);
System.out.println("Enter part1 marks");
part1=s.nextFloat();
System.out.println("Enter part2 marks");
part2=s.nextFloat();
}
void printMarks()
{
System.out.println("Marks Part1 "+part1);
System.out.println("Marks Part2 "+part2);
}
}
interface sports
{
float sportwt=6.0F;
void printSports();
}
class results extends test implements sports
{
float total;
public void printSports()
{
System.out.println("Sports Marks "+ sportwt);
}
void display()
{
total=part1+part2+sportwt;
System.out.println("Total marks of " +rollNumber+" is "+total);
}
}
class Test
{
42
43

public static void main(String srgs[])


{
results a=new results();
a.readNumber();
a.readMarks();
a.printNumber();
a.printMarks();
a.printSports();
a.display();
}
}
Output:
Enter Rollnumber
10
Enter part1 marks
50
Enter part2 marks
50
Roll Number=10
Marks Part1 50.0
Marks Part2 50.0
Sports Marks 6.0
Total marks of 10 is 106.0

Difference between abstract class and interface


Abstract class and interface both are used to achieve abstraction where we can declare the
abstract methods. Abstract class and interface both can't be instantiated.

But there are many differences between abstract class and interface that are given below.

Abstract class Interface

Interface can have only abstract methods. Since


1) Abstract class can have abstract and non-
Java 8, it can have default and static methods
abstract methods.
also.

2) Abstract class doesn't support multiple


Interface supports multiple inheritance.
inheritance.

3) Abstract class can have final, non-final, Interface has only static and final variables.

43
44

static and non-static variables.

4) Abstract class can provide the Interface can't provide the implementation of
implementation of interface. abstract class.

5) The abstract keyword is used to declare The interface keyword is used to declare
abstract class. interface.

6) An abstract class can extend another Java An interface can extend another Java interface
class and implement multiple Java interfaces. only.

7) An abstract class can be extended using An interface class can be implemented using
keyword extends. keyword implements

8) A Java abstract class can have class


Members of a Java interface are public by default.
members like private, protected, etc.

9)Example: Example:
public abstract class Shape{ public interface Drawable{
public abstract void draw(); void draw();
} }

Differences between classes and interfaces


Basis for
Class Interface
Comparison
An interface can never be instantiated as
A class is instantiated to create
Basic the methods are unable to perform any
objects.
action on invoking.
Keyword Class Interface
The members of a class can be The members of an interface are always
Access specifier
private, public or protected. public.
The methods of a class are
The methods in an interface are purely
Methods defined to perform a specific
abstract.
action.
A class can implement any An interface can extend multiple
Implement/Extend number of interface and can interfaces but cannot implement any
extend only one class. interface.
An interface can never have a
A class can have constructors to
Constructor constructor as there is hardly any
initialize the variables.
variable to initialize.

44

You might also like