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

UNIT II Oops

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 40

UNIT II INHERITANCE, PACKAGES 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.

1. Overloading Methods
1. Explain briefly about function overloading with a suitable example.
Nov/Dec 2021
2. Outline Method overriding with an example. Nov/Dec 2021

When two or more methods within the same class that have the same name, but their
parameter declarations are different. The methods are said to be overloaded, and the
process is referred to as method overloading. Method overloading is one of the ways that
Java supports polymorphism.

There are two ways to overload the method in java

1. By changing number of arguments

2. By changing the data type

Example:

// Demonstrate method overloading. class OverloadDemo {

void test() {

System.out.println("No parameters");

// Overload test for one integer parameter. void test(int a) {

System.out.println("a: " + a);

// Overload test for two integer parameters. void test(int a, int b) {

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

}
// Overload test for a double parameter double test(double a) { System.out.println("double
a: " + a); return a*a;
}

class Overload {

public static void main(String args[]) { OverloadDemo ob = new OverloadDemo(); double


result;

// call all versions of test()

ob.test(); ob.test(10); ob.test(10,

20); result = ob.test(123.25);

System.out.println("Result of ob.test(123.25): " + result);

Output: No

parameters

a: 10 a and b: 10

20 double a:

123.25

Result of ob.test(123.25): 15190.5625

Method Overriding

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 its 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:

// Method overriding. class A {

int i, j;
A(int a, int b) { i = a;

j = b;

// display i and j void show() {

System.out.println("i and j: " + i + " " + j);

class B extends A { int k; B(int a,

int b, int c) { super(a, b); k = c;

// display k – this overrides show() in A void show() {

System.out.println("k: " + k);

class Override {

public static void main(String args[]) { B subOb = new B(1, 2, 3); subOb.show(); // this calls
show() in B

Output:

k: 3
When show( ) is invoked on an object of type B, the version of show( ) defined within B is
used. That is, the version of show( ) inside B overrides the version declared in A. If you
wish to access the superclass version of an overridden method, you can do so by using
super. For example, in this version of B, the superclass version of show( ) is invoked within
the subclass’ version. This allows all instance variables to be displayed. class B extends A
{ int k;
B(int a, int b, int c) { super(a,

b); k = c;

void show() { super.show(); // this calls A's show()

System.out.println("k: " + k);

If you substitute this version of A into the previous program, you will see the following

Output:

i and j: 1 2

k: 3

Here, super.show( ) calls the superclass version of show( ).

1.1 Objects as Parameters – Returning Objects

Java does this interesting thing that’s sort of a hybrid between pass-by-value and pass-
byreference. Basically, a parameter cannot be changed by the function, but the function can
ask the parameter to change itself via calling some method within it.
• While creating a variable of a class type, we only create a reference to an object. Thus, when
we 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 act as if they are passed to methods by use of callby-
reference.
• Changes to the object inside the method do reflect the object used as an argument.

Illustration: Let us suppose three objects ‘ob1’ , ‘ob2’ and ‘ob3’ are created:

ObjectPassDemo ob1 = new ObjectPassDemo(100, 22);


ObjectPassDemo ob2 = new ObjectPassDemo(100, 22);
ObjectPassDemo ob3 = new ObjectPassDemo(-1, -1);
From the method side, a reference of type Foo with a name a is declared and it’s initially
assigned to null. boolean equalTo(ObjectPassDemo o);

As we call the method equalTo, the reference ‘o’ will be assigned to the object which is
passed as an argument, i.e. ‘o’ will refer to ‘ob2’ as the following statement execute.
System.out.println("ob1 == ob2: " + ob1.equalTo(ob2));

Now as we can see, equalTo method is called on ‘ob1’ , and ‘o’ is referring to ‘ob2’. Since
values of ‘a’ and ‘b’ are same for both the references, so if(condition) is true, so boolean
true will be return. if(o.a == a && o.b == b)
Again ‘o’ will reassign to ‘ob3’ as the following statement execute.
System.out.println("ob1 == ob3: " + ob1.equalTo(ob3));

• Now as we can see, the equalTo method is called on ‘ob1’, and ‘o’ is referring to ‘ob3’.
Since values of ‘a’ and ‘b’ are not the same for both the references, so if (condition) is
false, so else block will execute, and false will be returned.

Example

// Java Program to Demonstrate Returning of Objects

// Class 1
class ObjectReturnDemo {
int a;

// Constructor
ObjectReturnDemo(int i)
{ a = i; }

// Method returns an object


ObjectReturnDemo incrByTen()
{
ObjectReturnDemo temp = new ObjectReturnDemo(a + 10);
return temp;
}
}

// Class 2 //
Main class
public class GFG {
// Main driver method
public static void main(String args[])
{

// Creating object of class1 inside main() method


ObjectReturnDemo ob1 = new ObjectReturnDemo(2);
ObjectReturnDemo ob2;

ob2 = ob1.incrByTen();

System.out.println("ob1.a: " + ob1.a);


System.out.println("ob2.a: " + ob2.a);
}
}

Output ob1.a:
2 ob2.a: 12

1.2 Static, Nested and Inner Classes

Inner class means one class which is a member of another class. There are
basically four types of inner classes in java.
1)Static nested classes
2)Nested Inner class
3)Method Local inner classes
4)Anonymous inner classes

1) Static nested classes

Static nested classes are not technically an inner class. They are like a static member of
outer class.
Example: class Outer { private static void outerMethod()
{ System.out.println("inside outerMethod");
}
// A static inner class static class Inner {
public static void main(String[] args)
{
System.out.println("inside inner class Method"); outerMethod();
}
}
}
Output:
inside inner class Method inside outerMethod

2) Nested Inner class

Nested Inner class can access any private instance variable of outer class. Like
any other instance variable, we can have access modifier private, protected, public
and default modifier. Like class, interface can also be nested and can have access
specifiers. Example:
class Outer {
// Simple
nested
inner class
class
Inner { public void
show() {
System.out.println("In a nested class method");
}
}
}
class Main {
public static void
main(String[] args)
{ Outer.Inner in = new
Outer().new Inner();
in.show();
}
}
Output:
In a nested class method

3) Method Local inner classes


Inner class can be declared within a method of an outer class. In the following example,
Inner is an inner class in outerMethod().
Example:
class Outer {
void outerMethod()
{
System.out.println("inside
outerMethod"); // Inner class is local to
outerMethod() class Inner {
void innerMethod()
{
System.out.println("inside innerMethod");
}
}
Inner y = new Inner(); y.innerMethod();
}
}
class MethodDemo { public static void main(String[] args) { Outer x = new
Outer(); x.outerMethod();
}
}
Output:
Inside outerMethod Inside innerMethod

4) Anonymous inner classes


Anonymous inner classes are declared without any name at all. They are created in two
ways.

a) As subclass of specified type


class Demo
{
void show() {
System.out.println("i am in show method of super class");
}
}
class Flavor1Demo {
// An anonymous class with Demo as base class static Demo d = new Demo() { void
show() { super.show();
System.out.println("i am in Flavor1Demo class");
} };
public static void main(String[] args){ d.show();
}
}
Output: i am in show method of super class i am in
Flavor1Demo class
In the above code, we have two class Demo and Flavor1Demo. Here demo act as
super class and anonymous class acts as a subclass, both classes have a method
show(). In anonymous class show () method is overridden.

b) As implementer of the specified interface Example:


class Flavor2Demo {
// An anonymous class that implements Hello interface static Hello h = new Hello()
{ public void show() {
System.out.println("i am in anonymous class");
} };
public static void main(String[] args) { h.show();
}
}
interface Hello { void
show(); } Output: i am in
anonymous class
In above code we create an object of anonymous inner class but this anonymous inner
class is an implementer of the interface Hello. Any anonymous inner class can
implement only one interface at one time. It can either extend a class or implement
interface at a time.

2.INHERITANCE

1.Explain in detail about various types of inheritance in java with neat diagram?
(NOV/DEC 2019)

2. Exemplify the use of super keyword. (NOV/DEC 2020)

3. Write a Java program to calculate electricity bill using inheritance. The program
should get the inputs of watts per hour and unit rate. Check your program for the
following case : Assume a consumer consumes 5000 watts per hour daily for one
month. Calculate the total energy bill of that consumer if per unit rate is 7 [1 unit =
1k Wh]. (NOV/DEC 2020)

4. Outline the use of extends keyword in Java with syntax. (NOV/DEC 2021)

5. When a class hierarchy is created, in what order are the constructors for the
classes that make up the hierarchy called? Outline with an example(NOV/DEC
2021)
6. Outline method overriding with an example. (NOV/DEC 2021)

Inheritance can be defined as the procedure or mechanism of acquiring all the


properties and behaviors of one class to another, i.e., acquiring the properties and
behavior of child class from the parent class.
When one object acquires all the properties and behaviours of another object, it is
known as inheritance. Inheritance represents the IS-A relationship, also known as
parent-child relationship.
Uses of inheritance in java
• For Method Overriding (so runtime polymorphism can be achieved).
• For Code Reusability.
Types of inheritance in java: single, multilevel and hierarchical inheritance. Multiple and
hybrid inheritance is supported through interface only.
Syntax:
class subClass extends superClass
{
//methods and fields
}

Terms used in Inheritence

• Class: A class is a group of objects which have common properties. It is a


template or blueprint from which objects are created.
• Sub Class/Child Class: Subclass is a class which inherits the other class. It is
also called a derived class, extended class, or child class.
• Super Class/Parent Class: Superclass is the class from where a subclass
inherits the features. It is also called a base class or a parent class.
• Reusability: As the name specifies, reusability is a mechanism which facilitates
you to reuse the fields and methods of the existing class when you create a new
class. You can use the same fields and methods already defined in previous
class.
SINGLE INHERITANCE

In Single Inheritance one class extends another class (one class only).
Example:
public class ClassA
{
public void dispA()
{
System.out.println("disp() method of ClassA");
}
}
public class ClassB extends ClassA
{
public void dispB()
{
System.out.println("disp() method of ClassB");
}
public static void main(String args[])
{
//Assigning ClassB object
to ClassB reference ClassB b
= new ClassB(); //call
dispA() method of
ClassA
b.dispA();
//call dispB() method
of
ClassB
b.dispB();
}
}
Output :
disp() method of ClassA
disp() method of ClassB

MULTILEVEL INHERITANCE

In Multilevel Inheritance, one class can inherit from a derived class. Hence, the derived
class becomes the base class for the new class.
Example:
public class ClassA
{
public void dispA()
{
System.out.println("disp() method of ClassA");
}
}
public class ClassB extends ClassA
{
public void dispB()
{
System.out.println("disp() method of ClassB");
}
}
public class ClassC extends ClassB
{
public void dispC()
{
System.out.println("disp() method of ClassC");
}
public static void main(String args[])
{
//Assigning ClassC object to ClassC reference ClassC c = new ClassC();
//call dispA() method of ClassA c.dispA();
//call dispB() method of ClassB c.dispB();
//call dispC() method of ClassC c.dispC();
}
}
Output :
disp() method of ClassA disp() method of ClassB disp() method of ClassC

HIERARCHICAL INHERITANCE

In Hierarchical Inheritance, one class is inherited by many sub classes.

Example:
public class ClassA
{
public void dispA()
{
System.out.println("disp() method of ClassA");
}
}
public class ClassB extends ClassA
{
public void dispB()
{
System.out.println("disp() method of ClassB");
}
}
public class ClassC extends ClassA
{
public void dispC()
{
System.out.println("disp() method of ClassC");
}
}
public class ClassD extends ClassA
{
public void dispD()
{
System.out.println("disp() method of ClassD");
}
}
public class HierarchicalInheritanceTest
{
public static void main(String args[])
{
//Assigning ClassB object to ClassB reference
ClassB b = new ClassB();
//call dispB() method of ClassB b.dispB();
//call dispA() method of ClassA b.dispA();
//Assigning ClassC object to ClassC reference ClassC c = new ClassC();
//call dispC() method of ClassC c.dispC();
//call dispA() method of ClassA c.dispA();

//Assigning ClassD object to ClassD reference ClassD d = new ClassD();


//call dispD() method of ClassD d.dispD();
//call dispA() method of ClassA d.dispA();
}
}
Output : disp() method of ClassB disp() method of ClassA disp() method of ClassC
disp() method of ClassA disp() method of ClassD disp() method of ClassA

Hybrid Inheritance is the combination of both Single and Multiple Inheritance. Again
Hybrid inheritance is also not directly supported in Java only through interface we can
achieve this. Flow diagram of the Hybrid inheritance will look like below. As you can
ClassA will be acting as the Parent class for ClassB & ClassC and ClassB & ClassC will be
acting as Parent for ClassD.

Multiple Inheritance is nothing but one class extending more than oneclass.Multiple
Inheritance is basically not supported by many Object Oriented Programming languages
such as Java, Small Talk, C# etc.. (C++SupportsMultiple Inheritance). As the Child class
has to manage the dependency of more than one Parent class. But you can achieve
multiple inheritance in Java using Interfaces.

2.1 “super” KEYWORD

Usage of super keyword


1. super() invokes the constructor of the parent class.
2. super.variable_name refers to the variable in the parent class.
3. super.method_name refers to the method of the parent class.

1. super() invokes the constructor of the parent class super() will invoke the
constructor of the parent class. Even when you don’t add super() keyword the
compiler will add one and will invoke the Parent Class constructor.
Example:
class ParentClass
{
ParentClass()
{
System.out.println("Parent Class default Constructor");
}
}
public class SubClass extends ParentClass
{
SubClass()
{
System.out.println("Child Class default Constructor");
}
public static void main(String args[])
{
SubClass s = new SubClass();
}
}
Output:
Parent Class default Constructor Child Class default Constructor

Even when we add explicitly also it behaves the same way as it did before. class
ParentClass
{
public ParentClass()
{
System.out.println("Parent Class default Constructor");
}
}
public class SubClass extends ParentClass
{
SubClass()
{
super();
System.out.println("Child Class default Constructor");
}
public static void main(String args[])
{
SubClass s = new SubClass();
}
}
Output:
Parent Class default Constructor
Child Class default Constructor
You can also call the parameterized constructor of the Parent Class. For example,
super(10) will call parameterized constructor of the Parent class.
class ParentClass
{
ParentClass()
{
System.out.println("Parent Class default Constructor called");
}
ParentClass(int val)
{
System.out.println("Parent Class parameterized Constructor, value: "+val);
}
}
public class SubClass extends ParentClass
{
SubClass()
{
super();//Has to be the first statement in the constructor System.out.println("Child Class
default Constructor called");
}
SubClass(int val)
{
super(10);
System.out.println("Child Class parameterized Constructor, value: "+val);
}
public static void main(String args[])
{
}
}
Output

//Calling default constructor SubClass s = new SubClass();


//Calling parameterized constructor SubClass s1 = new SubClass(10);

Parent Class default Constructor called Child Class default Constructor called Parent
Class parameterized Constructor, value: 10
Child Class parameterized Constructor, value: 10

2. super.variable_name refers to the variable in the parent class


When we have the same variable in both parent and subclass class ParentClass
{
int val=999;
}
public class SubClass extends ParentClass
{
int val=123;

void disp()
{
System.out.println("Value is : "+val);
}

public static void main(String args[])


{

}
}
Output

SubClass s = new SubClass(); s.disp();

Value is : 123
This will call only the val of the sub class only. Without super keyword, you cannot call
the val
which is present in the Parent Class. class ParentClass
{
int val=999;
}
public class SubClass extends ParentClass
{
int val=123;

void disp()
{
System.out.println("Value is : "+super.val);
}

public static void main(String args[])


{
SubClass s = new SubClass(); s.disp();
}
}
Output
Value is : 999

3. super.method_nae refers to the method of the parent class


When you override the Parent Class method in the Child Class without super keywords
support you will not be able to call the Parent Class method. Let’s look into the below
example class ParentClass
{
void disp()
{
System.out.println("Parent Class method");
}
}
public class SubClass extends ParentClass
{

void disp()
{
System.out.println("Child Class method");
}

void show()
{ disp();
}
public static void main(String args[])
{

}
}
Output:

SubClass s = new SubClass(); s.show();

Child Class method


Here we have overridden the Parent Class disp() method in the SubClass and hence
SubClass disp() method is called. If we want to call the Parent Class disp() method also
means then we have to use the super keyword for it. class ParentClass
{
void disp()
{
System.out.println("Parent Class method");
}
}
public class SubClass extends ParentClass
{
void disp()
{
System.out.println("Child Class method");
}

void show()
{
//Calling SubClass disp() method disp();
//Calling ParentClass disp() method super.disp();
}
public static void main(String args[])
{

}
}
Output

SubClass s = new SubClass(); s.show();

Child Class method Parent Class method

When there is no method overriding then by default Parent Class disp() method will be
called. class ParentClass
{
public void disp()
{
System.out.println("Parent Class method");
}
}
public class SubClass extends ParentClass
{
public void show()
{ disp();
}
public static void main(String args[])
{
SubClass s = new SubClass(); s.show(); }}
Output:
Parent Class method
2.2 Method Overriding

1. Outline method overriding with an example. (NOV/DEC 2021)

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 its 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:
// Method overriding. class A { int
i, j;
A(int a, int b) { i = a;
j = b;
}
// display i and j void show() {
System.out.println("i and j: " + i + " " + j);
}
}
class B extends A { int k; B(int a,
int b, int c) { super(a, b); k = c;
}
// display k – this overrides show() in A void show() {
System.out.println("k: " + k);
}
}
class Override {
public static void main(String args[]) { B subOb = new B(1, 2, 3); subOb.show(); // this
calls show() in B
}
}
Output: k:
3
When show( ) is invoked on an object of type B, the version of show( ) defined within B is
used. That is, the version of show( ) inside B overrides the version declared in A. If you
wish to access the superclass version of an overridden method, you can do so by using
super. For example, in this version of B, the superclass version of show( ) is invoked
within the subclass’ version. This allows all instance variables to be displayed. class B
extends A {
int k;
B(int a, int b, int c) {

super(a, b); k = c;
}
void show() {
super.show(); // this calls A's show() System.out.println("k: " + k);
}
}
If you substitute this version of A into the previous program, you will see the following
Output:
i and j: 1 2
k: 3
Here, super.show( ) calls the superclass version of show( ).

2.3 Dynamic Method Dispatch

Dynamic method dispatch is the mechanism by which a call to an overridden method is


resolved at run time, rather than compile time.

When an overridden method is called through a superclass reference, Java determines


which version(superclass/subclasses) of that method is to be executed based upon the
type of the object being referred to at the time the call occurs. Thus, this determination is
made at run time.
At run-time, it depends on the type of the object being referred to (not the type of the
reference variable) that determines which version of an overridden method will be
executed
A superclass reference variable can refer to a subclass object. This is also known as
upcasting. Java uses this fact to resolve calls to overridden methods at run time.
Therefore, if a superclass contains a method that is overridden by a subclass, then when
different types of objects are referred to through a superclass reference variable, different
versions of the method are executed. Here is an example that illustrates dynamic method
dispatch:

// A Java program to illustrate Dynamic Method


// Dispatch using hierarchical inheritance class
A
{
void m1()
{
System.out.println("Inside A's m1 method");
}
}

class B extends A
{
// overriding m1()
void m1()
{
System.out.println("Inside B's m1 method");
}
}

class C extends A
{
// overriding m1()
void m1()
{
System.out.println("Inside C's m1 method");
}
}

// Driver class
class Dispatch
{
public static void main(String args[])
{
// object of type A
A a = new A();

// object of type B
B b = new B();

// object of type C
C c = new C();

// obtain a reference of type A


A ref;

// ref refers to an A object


ref = a;

// calling A's version of m1()


ref.m1();

// now ref refers to a B object


ref = b;

// calling B's version of m1()


ref.m1();

// now ref refers to a C object


ref = c;

// calling C's version of m1()


ref.m1();
}
}

Output:
Inside A's m1 method Inside
B's m1 method
Inside C's m1 method
Explanation:
The above program creates one superclass called A and it’s two subclasses B and C. These
subclasses overrides m1( ) method.
1. Inside the main() method in Dispatch class, initially objects of type A, B, and C are declared.
2. A a = new A(); // object of type A
3. B b = new B(); // object of type B
4. C c = new C(); // object of type C

5. Now a reference of type A, called ref, is also declared, initially it will point to null. 6. A ref; //
obtain a reference of type A

7. Now we are assigning a reference to each type of object (either A’s or B’s or C’s) to ref, one-
by-one, and uses that reference to invoke m1( ). As the output shows, the version of m1( )
executed is determined by the type of object being referred to at the time of the call.
8. ref = a; // r refers to an A object
9. ref.m1(); // calling A's version of m1()
ref = b; // now r refers to a B object ref.m1(); // calling B's version of m1()

ref = c; // now r refers to a C object ref.m1(); // calling C's version of m1()


2.4 ABSTRACT CLASS

1. What is an abstract class? Illustrate with an example to demonstrate abstract


class? (NOV/DEC 2019)
2. When a class must be declared as abstract? (NOV/DEC 2021)

A class that is declared with abstract keyword, is known as abstract class in java. It can
have abstract and non-abstract methods (method with body).Abstraction is a process of
hiding the implementation details and showing only functionality to the user.
Abstraction lets you focus on what the object does instead of how it does it. It needs to be
extended and its method implemented. It cannot be instantiated.
Example abstract class:
abstract class A{}
abstract method:

A method that is declared as abstract and does not have implementation is known as
abstract method.
abstract void printStatus();//no body and abstract

In this example, Shape is the abstract class, its implementation is provided by the
Rectangle and Circle classes.
If you create the instance of Rectangle class, draw() method of Rectangle class will be
invoked. Example1:
File: TestAbstraction1.java abstract class Shape{ abstract void draw();
}
//In real scenario, implementation is provided by others i.e. unknown by end user class
Rectangle extends Shape{
void draw(){System.out.println("drawing rectangle");}
}
class Circle1 extends Shape{
void draw(){System.out.println("drawing circle");}
}
//In real scenario, method is called by programmer or user class
TestAbstraction1{ public static void main(String args[]){
Shape s=new Circle1();//In real scenario, object is provided through method e.g.
getShape() met hod s.draw();
}
}
Output:
drawing circle
Abstract class having constructor, data member, methods
An abstract class can have data member, abstract method, method body, constructor and
even main() method.
Example2:
File: TestAbstraction2.java
//example of abstract class that have method body abstract class Bike{
Bike(){System.out.println("bike is created");} abstract void run(); void
changeGear(){System.out.println("gear changed");}
}
class Honda extends Bike{
void run(){System.out.println("running safely..");}
}

class TestAbstraction2{
public static void main(String args[]){ Bike obj = new Honda(); obj.run();
obj.changeGear();
}
}
Output:
bike is created running safely.. gear changed

The abstract class can also be used to provide some implementation of the interface. In
such case, the end user may not be forced to override all the methods of the interface.
Example3:
interface A{ void a();
void b(); void c();
void d();
}
abstract class B implements A{
public void c(){System.out.println("I am c");}
}
class M extends B{
public void a(){System.out.println("I am a");} public void b(){System.out.println("I am
b");} public void d(){System.out.println("I am d");}
}
class Test5{
public static void main(String args[]){ A a=new M(); a.a();
a.b();
a.c();
a.d(); }}
Output:
I am a I am b I am c I am d

2.5 Final with Inheritance


FINAL KEYWORD

Final keyword can be used along with variables, methods and classes.
1) final variable
2) final method
3) final class
1. Java final variable
A final variable is a variable whose value cannot be changed at anytime once assigned, it
remains as a constant forever.
Example:
public class Travel
{
final int SPEED=60; void
increaseSpeed(){
SPEED=70;
}
public static void main(String args[])
{
Travel t=new Travel(); t.increaseSpeed();
}
}
Output :
Exception in thread "main" java.lang.Error: Unresolved compilation problem: The
final field Travel.SPEED cannot be assigned
The above code will give you Compile time error, as we are trying to change the value of
a final variable ‘SPEED’.

2. Java final method


When you declare a method as final, then it is called as final method. A final method
cannot be overridden.
package com.javainterviewpoint;

class Parent
{
public final void disp()
{
System.out.println("disp() method of parent class");
}
}
public class Child extends Parent
{
public void disp()
{
System.out.println("disp() method of child class");
}
public static void main(String args[])
{
Child c = new Child(); c.disp();
}
}
Output : We will get the below error as we are overriding the disp() method of the Parent
class. Exception in thread "main" java.lang.VerifyError: class
com.javainterviewpoint.Child overrides final method disp.() at
java.lang.ClassLoader.defineClass1(Native Method) at
java.lang.ClassLoader.defineClass(Unknown Source)
at java.security.SecureClassLoader.defineClass(Unknown Source) at
java.net.URLClassLoader.defineClass(Unknown Source) at
java.net.URLClassLoader.access$100(Unknown Source) at
java.net.URLClassLoader$1.run(Unknown Source) at
java.net.URLClassLoader$1.run(Unknown Source)
3. Java final class
A final class cannot be extended(cannot be subclassed), lets take a look into the below
example package com.javainterviewpoint;

final class Parent


{
}
public class Child extends Parent
{
public static void main(String args[])
{
Child c = new Child();
}
}
Output :
We will get the compile time error like “The type Child cannot subclass the final class
Parent”
Exception in thread "main" java.lang.Error: Unresolved compilation problem

3.PACKAGES AND INTERFACES


1. Describe the uses of interfaces in java?(NOV/DEC 2019)

2. What are the differences between classes and interfaces ? (NOV/DEC 2020)

3. What is interface ? With an example explain how to define and implement


interface. (NOV/DEC 2020)
4. Write a note on interfaces and present the syntax for defining an interface.
(NOV/DEC 2021)

5. Outline how interfaces are implemented in java with an example? (NOV/DEC 2021)

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.

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.

Defining a Package

To create a package 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 package
statement is omitted, the class names are put into the default package, which has no
name. Syntax: package <fully qualified package name>;
package pkg;
Here, pkg is the name of the package. For example, the following statement creates a
package called MyPackage.
package MyPackage;
Java uses file system directories to store packages. For example, the .class files for any
classes you declare to be part of MyPackage must be stored in a directory called
MyPackage.

It is possible to create a hierarchy of packages. 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 package java.awt.image; needs to be
stored in java\awt\image in a Windows environment. We cannot rename a package
without renaming the directory in which the classes are stored.

Finding Packages and CLASSPATH


First, by default, the Java run-time system uses the current working directory as its
starting point. Thus, if your package is in a subdirectory of the current directory, it will
be found. Second, you can specify a directory path or paths by setting the CLASSPATH
environmental variable. Third, you can use the - classpath option with java and javac to
specify the path to your classes.

consider the following package specification:


package MyPack
In order for a program to find MyPack, one of three things must be true. Either the
program can be executed from a directory immediately above MyPack, or the
CLASSPATH must be set to include the path to MyPack, or the -classpath option must
specify the path to MyPack when the program is run via java.

When the second two options are used, the class path must not include MyPack,
itself. It must simply specify the path to MyPack. For example, in a Windows
environment, if the path to MyPack is C:\MyPrograms\Java\MyPack then the class path
to MyPack is C:\MyPrograms\Java

Example:
// A simple package package MyPack; class Balance { String name; double bal;
Balance(String n, double b) { name = n; bal
= b;
}
void show() { if(bal<0)
System.out.print("--> "); System.out.println(name + ": $" + bal);
}
}
class AccountBalance {
public static void main(String args[]) { Balance current[] = new Balance[3];
current[0] = new Balance("K. J. Fielding", 123.23); current[1] = new Balance("Will Tell",
157.02); current[2] = new Balance("Tom Jackson", -12.33); for(int i=0; i<3; i++)
current[i].show();
}
}
Call this file AccountBalance.java and put it in a directory called MyPack. Next,
compile the file. Make sure that the resulting .class file is also in the MyPack directory.
Then, try executing the AccountBalance class, using the following command line:
java MyPack.AccountBalance
Remember, you will need to be in the directory above MyPack when you execute this
command. (Alternatively, you can use one of the other two options described in the
preceding section to specify the path MyPack.)
As explained, AccountBalance is now part of the package MyPack. This means that it
cannot be executed by itself. That is, you cannot use this command line:
java AccountBalance
AccountBalance must be qualified with its package name.

Example: package pck1; class Student


{
private int rollno; private String name; private String address; public
Student(int rno, String sname, String sadd)
{
rollno = rno; name = sname; address = sadd;
}
public void showDetails()
{
System.out.println("Roll No :: " + rollno); System.out.println("Name :: " + name);
System.out.println("Address :: " + address);
}
}
public class DemoPackage
{
public static void main(String ar[])
{
Student st[]=new Student[2];
st[0] = new Student (1001,"Alice", "New York"); st[1] = new
Student(1002,"BOb","Washington"); st[0].showDetails();
st[1].showDetails();
}
}
There are two ways to create package directory as follows:
1. Create the folder or directory at your choice location with the same name as package
name. After compilation of copy .class (byte code file) file into this folder.
2. Compile the file with following syntax.
javac -d <target location of package> sourceFile.java

The above syntax will create the package given in the sourceFile at the <target location of
pacakge> if it is not yet created. If package already exist then only the .class (byte code
file) will be stored to the package given in sourceFile.

Steps to compile the given example code:

Compile the code with the command on the command prompt. javac -d
DemoPackage.java
1. The command will create the package at the current location with the name pck1,
and contains the file DemoPackage.class and Student.class
2. To run write the command given below java pckl.DemoPackage

Note: The DemoPackate.class is now stored in pck1 package. So that we've to use fully
qualified type name to run or access it.

Output:
Roll No :: 1001
Name :: Alice
Address :: New York
Roll No :: 1002
Name :: Bob
Address :: Washington

3.1Interfaces

An interface in java is a blueprint of a class. It has static constants and abstract


methods.The interface in java is a mechanism to achieve abstraction and multiple
inheritance.
Interface is declared by using interface keyword. It provides total abstraction; means all
the methods in interface are declared with empty body and are public and all fields are
public, static and final by default. A class that implement interface must implement all the
methods declared in the interface.

Syntax: interface
<interface_name>
{

// declare constant fields //


declare methods that
abstract // by default.
}

Relationship between classes and interfaces


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

Example: 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");}
}
class TestInterface1{ public static
void main(String args[]){
Drawable d=new Circle();//In real scenario, object is provided by method e.g.
getDrawable() d.draw();
}
}
Output:
drawing circle

Multiple inheritance in Java by interface


If a class implements multiple interfaces, or an interface extends multiple interfaces i.e.
known as multiple inheritance.

Example: interface Printable{ void print();


}
interface Showable{ void show();
}
class A7 implements Printable,Showable{ public void print()
{System.out.println("Hello");}

public void show(){System.out.println("Welcome");} public static void main(String


args[]){
A7 obj = new A7(); obj.print();
obj.show();
}
}
Output:
Hello Welcome

Interface inheritance

A class implements interface but one interface extends another interface . Example:
interface Printable{ void print();
}
interface Showable extends Printable{ void show();
}
class TestInterface4 implements Showable{ public void print()
{System.out.println("Hello");}
public void show(){System.out.println("Welcome");} public static void main(String
args[]){ TestInterface4 obj = new TestInterface4(); obj.print(); obj.show();
}}
Output:
Hello Welcome
Nested Interface in Java

An interface can have another interface i.e. known as nested interface. interface
printable{ void print();
interface MessagePrintable{ void msg();
}
}

Key points to remember about interfaces:


1) We can’t instantiate an interface in java. That means we cannot create the object of
an interface
2) Interface provides full abstraction as none of its methods have body. On the other
hand abstract class provides partial abstraction as it can have abstract and
concrete(methods with body) methods both.
3) “implements” keyword is used by classes to implement an interface.
4) While providing implementation in class of any method of an interface, it needs to
be mentioned as public.
5) Class that implements any interface must implement all the methods of that
interface, else the class should be declared abstract.
6) Interface cannot be declared as private, protected or transient.
7) All the interface methods are by default abstract and public.
8) Variables declared in interface are public, static and final by default. interface Try
{
int a=10; public int a=10;
public static final int a=10; final int a=10; static
int a=0;
}
All of the above statements are identical.
9) Interface variables must be initialized at the time of declaration otherwise compiler
will throw an error.
interface Try
{
int x;//Compile-time error
}
Above code will throw a compile time error as the value of the variable x is not initialized
at the time of declaration.
10) Inside any implementation class, you cannot change the variables declared in
interface because by default, they are public, static and final. Here we are
implementing the interface
“Try” which has a variable x. When we tried to set the value for variable x we got
compilation error as the variable x is public static final by default and final variables can
not be re-initialized. class Sample implements Try
{
public static void main(String args[])
{
x=20; //compile time error
}
}
11) An interface can extend any interface but cannot implement it. Class implements
interface and interface extends interface.
12) A class can implement any number of interfaces.
13) If there are two or more same methods in two interfaces and a class implements
both interfaces, implementation of the method once is enough. interface A
{
public void aaa();
}
interface B
{
public void aaa();
}
class Central implements A,B
{
public void aaa()
{
//Any Code here
}
public static void main(String args[])
{
//Statements
}
}
14) A class cannot implement two interfaces that have methods with same name but
different return type. interface A
{
public void aaa();
}
interface B
{
public int aaa();
}
class Central implements A,B
{
public void aaa() // error
{
}
public int aaa() // error
{
}
public static void main(String args[])
{
}
}
15) Variable names conflicts can be resolved by interface name.
interface A
{
int x=10;
}
interface B
{
int x=100;
}
class Hello implements A,B
{
public static void Main(String args[])
{
System.out.println(x);
System.out.println(A.x);
System.out.println(B.x);
}
}

Advantages of interface in java:

• Without bothering about the implementation part, we can achieve the security of
implementation
• In java, multiple inheritance is not allowed, however you can use interface to make
use

of it as you can implement more than one interface.

You might also like