Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Unit 2 Oops

Download as pdf or txt
Download as pdf or txt
You are on page 1of 49

UNIT -2

INHERITANCE AND INTERFACES


Overloading Methods – Objects as Parameters – Returning Objects –Static, Nested and Inner
Classes. Inheritance: Basics– Types of Inheritance -Super keyword -Method Overriding – Dynamic
Method Dispatch –Abstract Classes – final with Inheritance. Packages and Interfaces: Packages –
Packages and Member Access –Importing Packages – Interfaces.

JAVA METHOD OVERLOADING


In Java, two or more methods may have the same name if they differ in parameters (different
number of parameters, different types of parameters, or both). These methods are called overloaded
methods and this feature is called method overloading.

For example:
void func() { ... }
void func(int a) { ... }
float func(double a) { ... }
float func(int a, float b) { ... }

Here, the func() method is overloaded. These methods have the same name but accept different
arguments.

Different ways to perform method overloading:


Overloading by changing the number of parameters
class MethodOverloading {
private static void display(int a){
System.out.println("Arguments: " + a);
}

private static void display(int a, int b){


System.out.println("Arguments: " + a + " and " + b);
}

public static void main(String[] args) {


display(1);
display(1, 4);
}
}

Output:
Arguments: 1
Arguments: 1 and 4

Method Overloading by changing the data type of parameters


class MethodOverloading {

// this method accepts int


private static void display(int a){
System.out.println("Got Integer data.");
}
// this method accepts String object
private static void display(String a){
System.out.println("Got String object.");
}

public static void main(String[] args) {


display(1);
display("Hello");
}
}
Output:
Got Integer data.
Got String object.

Here, both overloaded methods accept one argument. However, one accepts the argument of type
int whereas other accepts String object.

OBJECTS AS PARAMETERS
A method can take an objects as a parameter. For example, in the following program, the
method setData( ) takes three parameter. The first parameter is an Data object. If you pass an
object as an argument to a method, the mechanism that applies is called pass-by-
reference, because a copy of the reference contained in the variable is transferred to the
method, not a copy of the object itself.
Example
class Data
{
int data1;
int data2;
}

class SetData {

void setData(Data da,int d1,int d2)


{
da.data1 = d1;
da.data2 = d2;
}

void getData(Data da)


{
System.out.println("data1 : "+da.data1);
System.out.println("data2 : "+da.data2);
}
}

public class Javaapp {

public static void main(String[] args) {

Data da = new Data();


SetData sd = new SetData();
sd.setData(da,50,100);
sd.getData(da);
}
}

Output
Data1:50
Data 2:100
JAVA METHOD RETURNING OBJECTS

A method can return any type of data, including class types that you create.
For example, in the following program, the changeObject() method returns an object in which
the value of a is ten greater than it is in the invoking object.
// Returning an object.
class Test
int a;

Test(int i) {
a = i;
}

Test changeObject() {
Test temp = new Test(a+10);
return temp;
}
}

public class Main {


public static void main(String args[]) {
Test ob1 = new Test(2);
Test ob2;
ob2 = ob1.changeObject();
System.out.println("ob1.a: " + ob1.a);
System.out.println("ob2.a: " + ob2.a);

ob2 = ob2.changeObject();
System.out.println("ob2.a after second increase: "
+ ob2.a);
}
}
OUTPUT

INHERITANCE
Inheritance is the mechanism in java by which one class is allow to inherit the features
(fields and methods) of another class. It is process of deriving a new class from an existing
class. A class that is inherited is called a superclass and the class that does the inheriting is
lationship. The keyword used for inheritance is extends.
Syntax:
class Subclass-name extends Superclass-name
{
//methods and fields
}
Here, the extends keyword indicates that we are creating a new class that derives from an
existing class.
Note: The constructors of the superclass are never inherited by the subclass
Advantages of Inheritance:
 Code reusability - public methods of base class can be reused in derived classes
 Data hiding – private data of base class cannot be altered by derived class
 Overriding--With inheritance, we will be able to override the methods of the base
class in the derived class
Example:
// Create a superclass.
class BaseClass{
int a=10,b=20;
public void add(){
System.out.println(“Sum:”+(a+b));
// Create a subclass by extending class BaseClass.
public class Main extends BaseClass
{
public void sub(){
System.out.println(“Difference:”+(a-b));
}
public static void main(String[] args) {
Main obj=new Main();
/*The subclass has access to all public members of its superclass*/
obj.add();
obj.sub();
}
}
Sample Output:
Sum:30
Difference:-10
In this example, Main is the subclass and BaseClass is the superclass. Main object can
access the field of own class as well as of BaseClass class i.e. code reusability.
Types of inheritance
Single Inheritance :
In single inheritance, a subclass inherit the features of one superclass.
Example:
class Shape{
int a=10,b=20;
}
class Rectangle extends Shape{
public void rectArea(){
System.out.println(“Rectangle Area:”+(a*b));
public class Main
{
public static void main(String[] args) {
Rectangle obj=new Rectangle();
obj.rectArea();
}
}

ROHINI

Multilevel Inheritance:
In Multilevel Inheritance, a derived class will be inheriting a base class and as well as the
derived class also act as the base class to other class i.e. a derived class in turn acts as a base
class for another class.

Example:
class Numbers{
int a=10,b=20;
}
class Add2 extends Numbers{
int c=30;
public void sum2(){
System.out.println(“Sum of 2 nos.:”+(a+b));
}
}
class Add3 extends Add2{
public void sum3(){
System.out.println(“Sum of 3 nos.:”+(a+b+c));
}
}
public class Main
{
public static void main(String[] args) {
Add3 obj=new Add3();
obj.sum2();
obj.sum3();
}
}
Sample Output:
Sum of 2 nos.:30
Sum of 3 nos.:60
Hierarchical Inheritance:
In Hierarchical Inheritance, one class serves as a superclass (base class) for more than
one sub class.

Example:
class Shape{
int a=10,b=20;
}
class Rectangle extends Shape{
public void rectArea(){
System.out.println(“Rectangle Area:”+(a*b));
}
}
class Triangle extends Shape{
public void triArea(){
System.out.println(“Triangle Area:”+(0.5*a*b));
}
}
public class Main
{
public static void main(String[] args) {
Rectangle obj=new Rectangle();
obj.rectArea();
Triangle obj1=new Triangle();
obj1.triArea();
}
}
Sample Output:
Rectangle Area:200
Triangle Area:100.0
Multiple inheritance
Java does not allow multiple inheritance:
 To reduce the complexity and simplify the language
 To avoid the ambiguity caused by multiple inheritance

For example, Consider a class C derived from two base classes A and B. Class C inherits
A and B features. If A and B have a method with same signature, there will be ambiguity to
call method of A or B class. It will result in compile time error.
class A{
void msg(){System.out.println(“Class A”);}
}
class B{
void msg(){System.out.println(“Class B “);}
}
class C extends A,B{//suppose if it were
Public Static void main(String args[]){
C obj=new C();
obj.msg();//Now which msg() method would be invoked?
}
}
Sample Output:
Compile time error
Direct implementation of multiple inheritance is not allowed in Java. But it is achievable
using Interfaces. The concept about interface is discussed in chapter.2.7.
Access Control in Inheritance
The following rules for inherited methods are enforced −
 Variables declared public or protected in a superclass are inheritable in subclasses.
 Variables or Methods declared private in a superclass are not inherited at all.
 Methods declared public in a superclass also must be public in all subclasses.
 Methods declared protected in a superclass must either be protected or public in
subclasses; they cannot be private.
Example:
// Create a superclass
class A{
int x; // default specifier
private int y; // private to A

public void set_xy(int a,int b){


x=a;
y=b;
}
}
// A’s y is not accessible here.
class B extends A{
public void add(){
System.out.println(“Sum:”+(x+y)); //Error: y has private access in A – not inheritable
}
}
class Main{
public static void main(String args[]){
B obj=new B();
obj.set_xy(10,20);
obj.add();
}
}
In this example since y is declared as private, it is only accessible by its own class mem-
bers. Subclasses have no access to it.
USING SUPER
The super keyword refers to immediate parent class object. Whenever you create the in-
stance of subclass, an instance of parent class is created implicitly which is referred by super
reference variable.
 It an be used to refer immediate parent class instance variable when both parent and
child class have member with same name
 It can be used to invoke immediate parent class method when child class has overridden
that method.
 super() can be used to invoke immediate parent class constructor.
Use of super with variables:
When both parent and child class have member with same name, we can use super key-
word to access mamber of parent class.

Example:
class SuperCls
{
int x = 20;
}
/* sub class SubCls extending SuperCls */
class SubCls extends SuperCls
{
int x = 80;
void display()
{
System.out.println(“Super Class x: “ + super.x); //print x of super class
System.out.println(“Sub Class x: “ + x); //print x of subclass
}
}
/* Driver program to test */
class Main
{
public static void main(String[] args)
{
SubCls obj = new SubCls();
obj.display();
}
}
Sample Output:
Super Class x: 20
Sub Class x: 80
In the above example, both base class and subclass have a member x. We could access x
of base class in sublcass using super keyword.
Use of super with methods:
The super keyword can also be used to invoke parent class method. It should be used if
subclass contains the same method as parent class (Method Overriding).
class SuperCls
{
int x = 20;
void display(){ //display() in super class
System.out.println(“Super Class x: “ + x);
}
}
/* sub class SubCls extending SuperCls */
class SubCls extends SuperCls
{
int x = 80;
void display() //display() redefined in sub class – method overriding
{
System.out.println(“Sub Class x: “ + x);
super.display(); // invoke super class display()
}
}
/* Driver program to test */
class Main
{
public static void main(String[] args)
{
SubCls obj = new SubCls();
obj.display();
}
}
Sample Output:
Sub Class x: 80
Super Class x: 20
In the above example, if we only call method display() then, the display() of sub class gets
invoked. But with the use of super keyword, display() of superclass could also be invoked.
Use of super with constructors:
The super keyword can also be used to invoke the parent class constructor.
Syntax:
super();

 super() if present, must always be the first statement executed inside a subclass
constructor.
 When we invoke a super() statement from within a subclass constructor, we are
invoking the immediate super class constructor
Example:
class SuperCls
{
SuperCls(){
System.out.println(“In Super Constructor”);
}
}
/* sub class SubCls extending SuperCls */
class SubCls extends SuperCls
{
SubCls(){
super();
System.out.println(“In Sub Constructor”);
}
}
/* Driver program to test */
class Main
{
public static void main(String[] args)
{
SubCls obj = new SubCls();
}
}
Sample Output:
In Super Constructor
In Sub Constructor
ORDER OF CONSTRUCTOR INVOCATION
 Constructors are invoked in the order of their derivation
 If a subclass constructor does not explicitly invoke a superclass constructor using
super() in the first line, the Java compiler automatically inserts a call to the no-
argument constructor of the superclass. If the superclass does not have a no-argument
constructor, it will generate a compile-time error.
Example:
class A
{
A(){
System.out.println(“A’s Constructor”);
}
}
/* sub class B extending A */
class B extends A
{
B(){
super();
System.out.println(“B’s Constructor”);
}
}
/* sub class C extending B */
class C extends B{
C(){
super();
System.out.println(“C’s Constructor”);
}
}
/* Driver program to test */
class Main
{
public static void main(String[] args)
{
C obj = new C();
}
}
Sample Output:
A’s Constructor
B’s Constructor
C’s Constructor
Invoking Superclass Parameterized Constructor
To call parameterized constructor of superclass, we must use the super keyword as shown
below.
Syntax:
super(value);
Example:
class SuperCls{
int x;
SuperCls(int x){
this.x=x; // this refers to current invoking object
}
}
class SubCls extends SuperCls{
int y;
SubCls(int x,int y){
super(x); // invoking parameterized constructor of superclass
this.y=y;
}
public void display(){
System.out.println(“x: “+x+” y: “+y);
}
}
public class Main
{
public static void main(String[] args) {
SubCls obj=new SubCls(10,20);
obj.display();
}
}
Sample Output:
x: 10 y: 20
The program contains a superclass and a subclass, where the superclass contains a param-
eterized constructor which accepts a integer value, and we used the super keyword to invoke
the parameterized constructor of the superclass.

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.

In other words, If a subclass provides the specific implementation of the method that has been
declared by one of its parent class, it is known as method overriding.

Usage of Java Method Overriding


o Method overriding is used to provide the specific implementation of a method which is
already provided by its superclass.
o Method overriding is used for runtime polymorphism

Rules for Java Method Overriding


1. The method must have the same name as in the parent class
2. The method must have the same parameter as in the parent class.
3. There must be an IS-A relationship (inheritance).
Example of method overriding

In this example, we have defined the run method in the subclass as defined in the parent class
but it has some specific implementation. The name and parameter of the method are the same,
and there is IS-A relationship between the classes, so there is method overriding.

1. //Java Program to illustrate the use of Java Method Overriding


2. //Creating a parent class.
3. class Vehicle{
4. //defining a method
5. void run(){System.out.println("Vehicle is running");}
6. }
7. //Creating a child class
8. class Bike2 extends Vehicle{
9. //defining the same method as in the parent class
10. void run(){System.out.println("Bike is running safely");}
11.
12. public static void main(String args[]){
13. Bike2 obj = new Bike2();//creating object
14. obj.run();//calling method
15. }
16. }
17.
Output:

Bike is running Safely

Difference between method overloading and method overriding in java

There are many differences between method overloading and method overriding in java. A list
of differences between method overloading and method overriding are given below:

No. Method Overloading Method Overriding

1) Method overloading is used to increase the Method overriding is used to provide


readability of the program. the specific implementation of the
method that is already provided by its
super class.

2) Method overloading is performed within class. Method overriding occurs in two


classes that have IS-A (inheritance)
relationship.

3) In case of method overloading, parameter must be In case of method


different. overriding, parameter must be same.

4) Method overloading is the example of compile time Method overriding is the example
polymorphism. of run time polymorphism.
5) In java, method overloading can't be performed by Return type must be same or
changing return type of the method only. Return covariant in method overriding.
type can be same or different in method
overloading. But you must have to change the
parameter.

DYNAMIC METHOD DISPATCH IN JAVA


 Dynamic method dispatch is also known as run time polymorphism.
 It is the process through which a call to an overridden method is resolved at runtime.
 This technique is used to resolve a call to an overridden method at runtime rather than
compile time.
 To properly understand Dynamic method dispatch in Java, it is important to understand the
concept of upcasting because dynamic method dispatch is based on upcasting.

Upcasting :

 It is a technique in which a superclass reference variable refers to the object of the subclass.

Example :
Class Animal{ ]
Class Dog extends Animal{ }
Animal a=new Dog(); //upcasting

In the above example, we've created two classes, named Animal(superclass) &
Dog(subclass). While creating the object 'a', we've taken the reference variable of the
parent class(Animal), and the object created is of child class(Dog).

Example to demonstrate the use of Dynamic method dispatch :

In the below code, we've created two classes: Phone & SmartPhone.

The Phone is the parent class and the SmartPhone is the child class.

The method on() of the parent class is overridden inside the child class.

Inside the main() method, we've created an object obj of the Smartphone() class by taking the
reference of the Phone() class.

When obj.on() will be executed, it will call the on() method of the SmartPhone() class
because the reference variable obj is pointing towards the object of class SmartPhone().

Program

class Phone{
public void showTime(){
System.out.println("Time is 8 am");
}
public void on(){
System.out.println("Turning on Phone...");
}
}

class SmartPhone extends Phone{


public void music(){
System.out.println("Playing music...");
}
public void on(){
System.out.println("Turning on SmartPhone...");
}
}
public class CWH {
public static void main(String[] args) {

Phone obj = new SmartPhone(); // Yes it is allowed


// SmartPhone obj2 = new Phone(); // Not allowed

obj.showTime();
obj.on();
// obj.music(); Not Allowed

}
}
Output :

Time is 8 am

Turning on SmartPhone...

ABSTRACT CLASSES AND METHODS


Abstract class
A class that is declared as abstract is known as abstract class. It can have abstract and
non-abstract methods (method with body). It needs to be extended and its method imple-
mented. It cannot be instantiated.
Syntax:
abstract class classname
{
}
Abstract method
A method that is declared as abstract and does not have implementation is known as ab-
stract method. The method body will be defined by its subclass.
Abstract method can never be final and static. Any class that extends an abstract class
must implement all the abstract methods declared by the super class.
Note:
A normal class (non-abstract class) cannot have abstract methods.
Syntax:
abstract returntype functionname (); //No definition
Syntax for abstract class and method:
modifier abstract class className
{
//declare fields
//declare methods

abstract dataType methodName();


}
modifier class childClass extends className
{
dataType methodName()
{
}
}
Why do we need an abstract class?
Consider a class Animal that has a method sound() and the subclasses of it like Dog Lion,
Horse Cat etc. Since the animal sound differs from one animal to another, there is no point to
implement this method in parent class. This is because every child class must override this
method to give its own implementation details, like Lion class will say “Roar” in this method
and Horse class will say “Neigh”.
So when we know that all the animal child classes will and should override this method,
then there is no point to implement this method in parent class. Thus, making this method
abstract would be the good choice. This makes this method abstract and all the subclasses
to implement this method. We need not give any implementation to this method in parent
class.
Since the Animal class has an abstract method, it must be declared as abstract.
Now each animal must have a sound, by making this method abstract we made it compul-
sory to the child class to give implementation details to this method. This way we ensure that
every animal has a sound.
Rules
1. Abstract classes are not Interfaces.
2. An abstract class may have concrete (complete) methods.
3. An abstract class may or may not have an abstract method. But if any class has one or
more abstract methods, it must be compulsorily labeled abstract.
4. Abstract classes can have Constructors, Member variables and Normal methods.
5. Abstract classes are never instantiated.
6. For design purpose, a class can be declared abstract even if it does not contain any
abstract methods.
7. Reference of an abstract class can point to objects of its sub-classes thereby achieving
run-time polymorphism Ex: Shape obj = new Rectangle();

8. A class derived from the abstract class must implement all those methods that are
declared as abstract in the parent class.
9. If a child does not implement all the abstract methods of abstract parent class, then the
child class must need to be declared abstract as well.
Example 1
//abstract parent class
abstract class Animal
{
//abstract method
public abstract void sound();
}
//Lion class extends Animal class
public class Lion extends Animal
{
public void sound()
{
System.out.println(“Roars”);
}
public static void main(String args[])
{
Animal obj = new Lion();
obj.sound();
}
}

Output:
Roars
In the above code, Animal is an abstract class and Lion is a concrete class.
Example 2
abstract class Bank
{
abstract int getRateOfInterest();
}
class SBI extends Bank
{
int getRateOfInterest()
{
return 7;
}
}
class PNB extends Bank
{
int getRateOfInterest()
{
return 8;
}
}
public class TestBank
{
public static void main(String args[])
{
Bank b=new SBI();//if object is PNB, method of PNB will be invoked
int interest=b.getRateOfInterest();
System.out.println(“Rate of Interest is: “+interest+” %”);
b=new PNB();
System.out.println(“Rate of Interest is: “+b.getRateOfInterest()+” %”);
}
}
Inheritance and Interfaces  2.19

Output:
Rate of Interest is: 7 %
Rate of Interest is: 8 %
Abstract class with concrete (normal) method
Abstract classes can also have normal methods with definitions, along with abstract
methods.
Sample Code:
abstract class A
{
abstract void callme();
public void normal()
{
System.out.println(“this is a normal (concrete) method.”);
}
}
public class B extends A
{
void callme()
{
System.out.println(“this is an callme (abstract) method.”);
}
public static void main(String[] args)
{
B b = new B();
b.callme();
b.normal();
}
}
Output:
this is an callme (abstract) method.
this is a normal (concrete) method.
Observations about abstract classes in Java
1. An instance of an abstract class cannot be created; But, we can have references
of abstract class type though.
Sample Code:
abstract class Base
{
abstract void fun();
}
class Derived extends Base
{
void fun()
{
System.out.println(“Derived fun() called”);
}
}
public class Main
{
public static void main(String args[])
{
// Base b = new Base(); Will lead to error
// We can have references of Base type.
Base b = new Derived();
b.fun();
}
}
Output:
Derived fun() called
2. An abstract class can contain constructors in Java. And a constructor of ab-
stract class is called when an instance of a inherited class is created.
Sample Code:
abstract class Base
{
Base()
{
System.out.println(“Within Base Constructor”);
}
abstract void fun();
}
class Derived extends Base
{
Derived()
{
System.out.println(“Within Derived Constructor”);
}
void fun()
{
System.out.println(“ Within Derived fun()”);
}
}
public class Main
{
public static void main(String args[])
{
Derived d = new Derived();
}
}
Output:
Within Base Constructor
Within Derived Constructor
3. We can have an abstract class without any abstract method. This allows us to create
classes that cannot be instantiated, but can only be inherited.
Sample Code:
abstract class Base
{
void fun()
{
System.out.println(“Within Base fun()”);
}
}
class Derived extends Base
{
}
public class Main
{
public static void main(String args[])
{
Derived d = new Derived();
d.fun();
}
}
Output:
Within Base fun()
4. Abstract classes can also have final methods (methods that cannot be
overridden).
Sample Code:
abstract class Base
{
final void fun()
{
System.out.println(“Within Derived fun()”);
}
}
class Derived extends Base
{
}
public class Main
{
public static void main(String args[])
{
Base b = new Derived();
b.fun();
}
}
Output:
Within Derived fun()
FINAL METHODS AND CLASSES
The final keyword in java is used to restrict the user. The java final keyword can be ap-
plied to:
 variable
 method
 class
Java final variable - To prevent constant variables
Java final method - To prevent method overriding
Java final class - To prevent inheritance
Figure: Uses of final in java

Java final variable


The final keyword can be applied with the variables, a final variable that have no value
it is called blank final variable or uninitialized final variable. It can be initialized in the con-
structor only. The blank final variable can be static also which will be initialized in the static
block only.
Sample Code:
A final variable speedlimit is defined within a class Vehicle. When we try to change the
value of this variable, we get an error. This is due to the fact that the value of final variable
cannot be changed, once a value is assigned to it.
public class Vehicle
{
final int speedlimit=60;//final variable
void run()
{
speedlimit=400;
}
public static void main(String args[])
{
Vehicle obj=new Vehicle();
obj.run();
}
}
Output:
/Vehicle.java:6: error: cannot assign a value to final variable speedlimit
speedlimit=400;
^
1 error
Blank final variable
A final variable that is not initialized at the time of declaration is known as blank final
variable. We must initialize the blank final variable in constructor of the class otherwise it will
throw a compilation error.
Sample Code:
public class Vehicle
{
final int speedlimit; //blank final variable
void run()
{
}
public static void main(String args[])
{
Vehicle obj=new Vehicle();
obj.run();
}
}
Output:
/Vehicle.java:3: error: variable speedlimit not initialized in the default constructor
final int speedlimit; //blank final variable
^
1 error
Java Final Method
A Java method with the final keyword is called a final method and it cannot be overridden
in the subclass.
In general, final methods are faster than non-final methods because they are not required
to be resolved during run-time and they are bonded at compile time.
Sample Code:
class XYZ
{
final void demo()
{
System.out.println(“XYZ Class Method”);
}
}
public class ABC extends XYZ
{
void demo()
{
System.out.println(“ABC Class Method”);
}
public static void main(String args[])
{
ABC obj= new ABC();
obj.demo();
}
}
Output:
/ABC.java:11: error: demo() in ABC cannot override demo() in XYZ
void demo()
^
overridden method is final
1 error
The following code will run fine as the final method demo() is not overridden. This shows
that final methods are inherited but they cannot be overridden.
Sample Code:
class XYZ
{
final void demo()
{
System.out.println(“XYZ Class Method”);
}
}
public class ABC extends XYZ
{
public static void main(String args[])
{
ABC obj= new ABC();
obj.demo();
}
}
Output:
XYZ Class Method
Points to be remembered while using final methods:
 Private methods of the superclass are automatically considered to be final.
 Since the compiler knows that final methods cannot be overridden by a subclass, so
these methods can sometimes provide performance enhancement by removing calls
to final methods and replacing them with the expanded code of their declarations at
each method call location.
 Methods made inline should be small and contain only few lines of code. If it grows
in size, the execution time benefits become a very costly affair.
 A final’s method declaration can never change, so all subclasses use the same method
implementation and call to one can be resolved at compile time. This is known
as static binding.
Java Final Class
 Final class is a class that cannot be extended i.e. it cannot be inherited.
 A final class can be a subclass but not a superclass.
 Declaring a class as final implicitly declares all of its methods as final.
 It is illegal to declare a class as both abstract and final since an abstract class is incomplete
by itself and relies upon its subclasses to provide complete implementations.
 Several classes in Java are final e.g. String, Integer, and other wrapper classes.
 The final keyword can be placed either before or after the access specifier.
Syntax:
final public class A public final class A

{ {
OR
//code //code

} }
Sample Code:
final class XYZ
{
}

public class ABC extends XYZ


{
void demo()
{
System.out.println(“My Method”);
}
public static void main(String args[])
{
ABC obj= new ABC();
obj.demo();
}
}
Output:
/ABC.java:5: error: cannot inherit from final XYZ
public class ABC extends XYZ
^
1 error
Important points on final in Java
 Final keyword can be applied to a member variable, local variable, method or class
in Java.
 Final member variable must be initialized at the time of declaration or inside the
constructor, failure to do so will result in compilation error.
 We cannot reassign value to a final variable in Java.
 The local final variable must be initialized during declaration.
 A final method cannot be overridden in Java.
 A final class cannot be inheritable in Java.
 Final is a different than finally keyword which is used to Exception handling in
Java.
 Final should not be confused with finalize() method which is declared in Object class
and called before an object is a garbage collected by JVM.
 All variable declared inside Java interface are implicitly final.
 Final and abstract are two opposite keyword and a final class cannot be abstract in
Java.
 Final methods are bonded during compile time also called static binding.
 Final variables which are not initialized during declaration are called blank final
variable and must be initialized in all constructor either explicitly or by calling
this(). Failure to do so compiler will complain as “final variable (name) might not be
initialized”.
 Making a class, method or variable final in Java helps to improve performance because
JVM gets an opportunity to make assumption and optimization.
INTERFACES
An interface is a reference type in Java. It is similar to class. It is a collection of abstract
methods. Along with abstract methods, an interface may also contain constants, default meth-
ods, static methods, and nested types. Method bodies exist only for default methods and static
methods.
An interface is similar to a class in the following ways:
 An interface can contain any number of methods.
 An interface is written in a file with a .java extension, with the name of the interface
matching the name of the file.
 The byte code of an interface appears in a .class file.
 Interfaces appear in packages, and their corresponding bytecode file must be in a
directory structure that matches the package name.
Uses of interface:
 Since java does not support multiple inheritance in case of class, it can be achieved
by using interface.
 It is also used to achieve loose coupling.
 Interfaces are used to implement abstraction.
Defining an Interface
An interface is defined much like a class.
Syntax:
accessspecifier interface interfacename
{
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 pub-
lic, the interface can be used by any other code.
 The java file must have the same name as the interface.
 The methods that are declared have no bodies. They end with a semicolon after the
parameter list. They are 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.
Sample Code:
The following code declares a simple interface Animal that contains two methods called
eat() and travel() that take no parameter.
/* File name : Animal.java */
interface Animal {
public void eat();
public void travel();
}
Implementing an Interface
Once an interface has been defined, one or more classes can implement that interface. To
implement an interface, the ‘implements’ clause is included in a class definition and then the
methods defined by the interface are created.
Syntax:
class classname [extends superclass] [implements interface [,interface...]]
{
// class-body
}
Properties of java interface
 If a class implements more than one interface, the interfaces are separated with a
 comma.
 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.
 The type signature of the implementing method must match exactly the type signature
 specified in the interface definition.
Rules
 A class can implement more than one interface at a time.
 A class can extend only one class, but can implement many interfaces.
 An interface can extend another interface, in a similar way as a class can extend
another class.
Sample Code 1:
The following code implements an interface Animal shown earlier.
/* File name : MammalInt.java */
public class Mammal implements Animal
{
public void eat()
{
System.out.println(“Mammal eats”);
}
public void travel()
{
System.out.println(“Mammal travels”);
}
public int noOfLegs()
{
return 0;
}
public static void main(String args[])
{
Mammal m = new Mammal();
m.eat();
m.travel();
}
}
Output:
Mammal eats
Mammal travels
It is both permissible and common for classes that implement interfaces to define ad-
ditional members of their own. In the above code, Mammal class defines additional method
called noOfLegs().
Sample Code 2:
The following code initially defines an interface ‘Sample’ with two members. This inter-
face is implemented by a class named ‘testClass’.
import java.io.*;
// A simple interface
interface Sample
{
final String name = “Shree”;
void display();
}
// A class that implements interface.
public class testClass implements Sample
{
public void display()
{
System.out.println(“Welcome”);
}
public static void main (String[] args)
{
testClass t = new testClass();
t.display();
System.out.println(name);
}
}
Output:
Welcome
Shree
Sample Code 3:
In this example, Drawable interface has only one method. Its implementation is provided
by Rectangle and Circle classes.
interface Drawable
{
void draw();
}
class Rectangle implements Drawable
{
public void draw()
{
System.out.println(“Drawing rectangle”);
}
}
class Circle implements Drawable
{
public void draw()
{
System.out.println(“Drawing circle”);
}
}
public class TestInterface
{
public static void main(String args[])
{
Drawable d=new Circle();
d.draw();
}
}
Output:
Drawing circle
Nested Interface
An interface can be declared as a member of a class or another interface. Such an inter-
face is called a member interface or a nested interface. A nested interface can be declared as
public, private, or protected.
Sample Code:
interface MyInterfaceA
{
void display();
interface MyInterfaceB
{
void myMethod();
}
}
public class NestedInterfaceDemo1 implements MyInterfaceA.MyInterfaceB
{
public void myMethod()
{
System.out.println(“Nested interface method”);
}
public static void main(String args[])
{
MyInterfaceA.MyInterfaceB obj= new NestedInterfaceDemo1();
obj.myMethod();
}
}
Output:
Nested interface method
Differences between classes and interfaces
Both classes and Interfaces are used to create new reference types. A class is a collection
of fields and methods that operate on fields. A class creates reference types and these refer-
ence types are used to create objects. A class has a signature and a body. The syntax of class
declaration is shown below:
class class_Name extends superclass implements interface_1,….interface_n
// class signature
{
//body of class.
}
Signature of a class has class’s name and information that tells whether the class has in-
herited another class. The body of a class has fields and methods that operate on those fields.
A Class is created using a keyword class.
When a class is instantiated, each object created contains a copy of fields and methods
with them. The fields and members declared inside a class can be static or nonstatic. Static
members value is constant for each object whereas, the non-static members are initialized by
each object differently according to its requirement.
Members of a class have access specifiers that decide the visibility and accessibility of
the members to the user or to the subclasses. The access specifiers are public, private and pro-
tected. A class can be inherited by another class using the access specifier which will decide
the visibility of members of a superclass (inherited class) in a subclass (inheriting class).
An interface has fully abstract methods (methods with nobody). An interface is syntacti-
cally similar to the class but there is a major difference between class and interface that is a
class can be instantiated, but an interface can never be instantiated.
An interface is used to create the reference types. The importance of an interface in Java
is that, a class can inherit only a single class. To circumvent this restriction, the designers of
Java introduced a concept of interface. An interface declaration is syntactically similar to a
class, but there is no field declaration in interface and the methods inside an interface do not
have any implementation. An interface is declared using a keyword interface.
Aspect for
Class Interface
comparison
An interface can never be instanti-
A class is instantiated to create
Basic ated as the methods are unable to
objects.
perform any action on invoking.
Keyword class Interface
Access The members of a class can be The members of an interface are
specifier private, public or protected. always public.
The methods of a class are defined The methods in an interface are
Methods
to perform a specific action. purely abstract.
A class can implement any num- An interface can extend multiple
inheritance ber of interfaces and can extend interfaces but cannot implement
only one class. any interface.
Inheritance
extends implements
keyword
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.
class class_Name Interface interface_Name
{ {
//fields Type var_name=value;
Declaration
//Methods Type method1(parameter-list);
Syntax
} Type method2(parameter-list);
..
}
The following example shows that a class that implements one interface:
public interface interface_example
{
public void method1();
public string method2();
}
public class class_name implements interface_example
{
public void method1()
{
..
}
public string method2()
{

}
}
Inheritance between concrete (non-abstract) and abstract classes use extends keyword.
It is possible to extend only one class to another. Java does not support multiple inheri-
tance. However, multilevel inheritance i.e., any number of classes in a ladder is possible. For
example, in the following code class C extends the class B, where the class B extends class
A.
class A {}
class B extends A { }
class C extends B { }
Inheritance between classes (including abstract classes) and interfaces, use implements
keyword.
To support multiple inheritance, it uses interfaces. So after implements keyword, there
can be any number of interfaces. For example, in the following code, class B extends only
one class A and two interfaces I1 and I2.
interface I1 {}
interface I2 {}
class A
class B extends A implements I1, I2
{
}
Inheritance between two interfaces, is possible with the use of extends keyword only.
For example, in the following code, interface I2 extends the interface I1.
interface I1 { }
interface I2 extends I1{ }

NESTED CLASSES
In Java, a class can have another class as its member. The class written within another
class is called the nested class, and the class that holds the inner class is called the outer
class.
Java inner class is defined inside the body of another class. Java inner class can be de-
clared private, public, protected, or with default access whereas an outer class can have only
public or default access. The syntax of nested class is shown below:
class Outer_Demo {
class Nested_Demo {
}
}
Types of Nested classes
There are two types of nested classes in java. They are non-static and static nested classes.
The non-static nested classes are also known as inner classes.
 Non-static nested class (inner class)
○ Member inner class
○ Method Local inner class
○ Anonymous inner class
 Static nested class
Type Description
Member Inner Class A class created within class and outside method.
Anonymous Inner Class A class created for implementing interface or extending class.
Its name is decided by the java compiler.
Method Local Inner Class A class created within method.
Static Nested Class A static class created within class.
Nested Interface An interface created within class or interface.

INNER CLASSES (NON-STATIC NESTED CLASSES)


Inner classes can be used as the security mechanism in Java. Normally, a class cannot be
related with the access specifier private. However if a class is defined as a member of other
class, then the inner class can be made private. This class can have access to the private mem-
bers of a class.

.The three types of inner classes are


 Member Inner Class
 Method-local Inner Class
 Anonymous Inner Class
Member Inner Class
The Member inner class is a class written within another class. Unlike a class, an inner
class can be private and once you declare an inner class private, it cannot be accessed from
an object outside the class.
The following program is an example for member inner class.
class Outer_class {
int n=20;
private class Inner_class {
public void display() {
System.out.println(“This is an inner class”);
System.out.println(“n:”+n);
}
}
void print_inner() {
Inner_class inn = new Inner_class();
inn.display();
}
}
public class Myclass {
public static void main(String args[]) {
Outer_class out= new Outer_class();
out.print_inner();
}
}
Output:
This is an inner class
Method-local Inner Class
In Java, a class can be written within a method. Like local variables of the method, the
scope of the inner class is restricted within the method. A method-local inner class can be
instantiated only within the method where the inner class is defined. The following program
shows how to use a method-local inner class. The following program is an example for Meth-
od-local Inner Class
public class Outer_class {
void Method1() {
int n = 100;
class MethodInner_class {
public void display() {
System.out.println(“This is method inner class “);
System.out.println(“n:”+n);
}
}
MethodInner_class inn= new MethodInner_class();
inn.display();
}
public static void main(String args[]) {
Outer_class out = new Outer_class();
out.Method1();
}
}
Output:
This is method inner class
n: 100
Anonymous Inner Class
An inner class declared without a class name is known as an anonymous inner class. The
anonymous inner classes can be created and instantiated at the same time. Generally, they are
used whenever you need to override the method of a class or an interface. The syntax of an
anonymous inner class is as follows –
abstract class Anonymous_Inner {
public abstract void Method1();
}
The following program is an example for anonymous inner class.
public class Outer_class {
public static void main(String args[]) {
Anonymous_Inner inn = new Anonymous_Inner() {
public void Method1() {
System.out.println(“This is the anonymous inner class”);
}
};
inn.Method1();
}
}
Output:
This is the anonymous inner class
Static Nested Class
A static inner class is a nested class which is a static member of the outer class. It can
be accessed without instantiating the outer class, using other static members. Just like static
members, a static nested class does not have access to the instance variables and methods of
the outer class. Instantiating a static nested class is different from instantiating an inner class.
The following program shows how to use a static nested class.
public class Outer_class {
static class inner_class{
public void Method1() {
System.out.println(“This is the nested class”);
}
}
public static void main(String args[]) {
Outer_class.inner_class obj = new Outer_class.inner_class();
obj.Method1();
}
}
Output:
This is the nested class
Advantage of java inner classes:
There are basically three advantages of inner classes in java. They are as follows:
 Nested classes represent a special type of relationship that is it can access all the
members of outer class including private.
 Nested classes are used to develop more readable and maintainable code because it
logically group classes and interfaces in one place only.
 It provides code optimization. That is it requires less code to write.

JAVA PACKAGE

A java package is a group of similar types of classes, interfaces and sub-packages.

Package in java can be categorized in two form, built-in package and user-defined package.

There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc.

Here, we will have the detailed learning of creating and using user-defined packages.

Advantage of Java Package

1) Java package is used to categorize the classes and interfaces so that they can be easily
maintained.

2) Java package provides access protection.

3) Java package removes naming collision.


Simple example of java package

The package keyword is used to create a package in java.

1. //save as Simple.java
2. package mypack;
3. public class Simple{
4. public static void main(String args[]){
5. System.out.println("Welcome to package");
6. }
7. }
How to compile java package

If you are not using any IDE, you need to follow the syntax given below:

1. javac -d directory javafilename

For example

1. javac -d . Simple.java

The -d switch specifies the destination where to put the generated class file. You can use any
directory name like /home (in case of Linux), d:/abc (in case of windows) etc. If you want to
keep the package within the same directory, you can use . (dot).

How to run java package program

You need to use fully qualified name e.g. mypack.Simple etc to run the class.

To Compile: javac -d . Simple.java


To Run: java mypack.Simple
OUTPUT:Welcome to Package
OThe -d is a switch that tells the compiler where to put the class file i.e. it represents
destination. The . represents the current folder.

How to access package from another package

There are three ways to access the package from outside the package.

1. import package.*;
2. import package.classname;
3. fully qualified name.

1) Using packagename.*

If you use package.* then all the classes and interfaces of this package will be accessible but
not subpackages.

The import keyword is used to make the classes and interface of another package accessible to
the current package.
Example of package that import the packagename.*
1. //save by A.java
2. package pack;
3. public class A{
4. public void msg(){System.out.println("Hello");}
5. }

//save by B.java
1. package mypack;
2. import pack.*;
3.
4. class B{
5. public static void main(String args[]){
6. A obj = new A();
7. obj.msg();
8. }
9. }
OUTPUT:Hello

2) Using packagename.classname

If you import package.classname then only declared class of this package will be accessible.

Example of package by import package.classname

1. //save by A.java
2.
3. package pack;
4. public class A{
5. public void msg(){System.out.println("Hello");}
6. }

//save by B.java
1. package mypack;
2. import pack.A;
3.
4. class B{
5. public static void main(String args[]){
6. A obj = new A();
7. obj.msg();
8. }
9. }
OUTPUT:Hello

3) Using fully qualified name

If you use fully qualified name then only declared class of this package will be accessible.
Now there is no need to import. But you need to use fully qualified name every time when you
are accessing the class or interface.
It is generally used when two packages have same class name e.g. java.util and java.sql
packages contain Date class.

Example of package by import fully qualified name


1. //save by A.java
2. package pack;
3. public class A{
4. public void msg(){System.out.println("Hello");}
5. }
1. //save by B.java
2. package mypack;
3. class B{
4. public static void main(String args[]){
5. pack.A obj = new pack.A();//using fully qualified name
6. obj.msg();
7. }
8. }
OUTPUT:Hello

Note: Sequence of the program must be package then import then class.

Subpackage in java

Package inside the package is called the subpackage. It should be created to categorize the
package further.

Example of Subpackage
1. package com.javatpoint.core;
2. class Simple{
3. public static void main(String args[]){
4. System.out.println("Hello subpackage");
5. }
6. }
To Compile: javac -d . Simple.java
To Run: java com.javatpoint.core.Simple
OUTPUT:Hello subpackage

You might also like