Unit II Notes OOP
Unit II Notes OOP
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.
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:
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
Example:
2
3
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:
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
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.
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:
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
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.
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
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
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.
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.
Here, the keyword protected is a specifier that prevents access to finalize( ) by code defined
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.
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.
package pkg;
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;
package p1;
...
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;
{
...
}
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
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.*;
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
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
}
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
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) {
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.
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
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
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);
}
}
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
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();
}
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.
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
}
}
But there are many differences between abstract class and interface that are given below.
3) Abstract class can have final, non-final, Interface has only static and final variables.
43
44
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
9)Example: Example:
public abstract class Shape{ public interface Drawable{
public abstract void draw(); void draw();
} }
44