Unit No.3-JPR
Unit No.3-JPR
Unit No.3
Inheritance, Interface and Package
3.1 Inheritance:
Concept of Inheritance
Inheritance in java is a mechanism in which one object acquires all the properties and
behaviors of parent object.
The idea behind inheritance in java is that you can create new classes that are built upon
existing classes. When you inherit from an existing class, you can reuse methods and
fields of parent class, and you can add new methods and fields also.
Inheritance represents the IS-A relationship, also known as parent-child relationship.
There are three types of inheritance in java: single, multilevel and hierarchical.
When a class extends multiple classes i.e. known as multiple inheritance. For Example:
3.2
Single-level Inheritance
class A
class B extends A
Output –
Multilevel Inheritance
class X
System.out.println("class X method");
class Y extends X
System.out.println("class Y method");
class Z extends Y
System.out.println("class Z method");
Output –
class X method
class Y method
class Z method
Hierarchical Inheritance
class A
class B extends A
class C extends A
class D extends A
class MIDemo
obj1.methodA();
obj2.methodA();
obj3.methodA();
Output –
method of Class A
method of Class A
method of Class A
Method Overloading –
Method Overloading is a feature that allows a class to have two or more methods having
same name, if their argument lists are different.
class overDemo
System.out.println(s);
class OverTest
obj.disp("Hello");
obj.disp("Welcome",10);
Output –
Hello
Welcome 10
class overDemo
System.out.println(s);
System.out.println(s);
class OverTest
obj.disp("Hello");
obj.disp(100);
Output –
Hello
100
Method Overriding
One of the simplest example – Here Boy class extends Human class. Both the classes have a
common method void eat(). Boy class is giving its own implementation to the eat() method or in
other words it is overriding the method eat().
class Human
System.out.println("Human is eating");
System.out.println("Boy is eating");
obj.eat();
Method Overloading –
Method Overloading is a feature that allows a class to have two or more methods having
same name, if their argument lists are different.
class overDemo
System.out.println(s);
class OverTest
obj.disp("Hello");
obj.disp("Welcome",10);
Output –
Hello
Welcome 10
class overDemo
System.out.println(s);
System.out.println(s);
class OverTest
obj.disp("Hello");
obj.disp(100);
Output –
Hello
100
Method Overriding
Declaring a method in subclass which is already present in parent class is known as
method overriding
Advantage of method overriding - The main advantage of method overriding is that the
class can give its own specific implementation to a inherited method without even
modifying the parent class(base class).
One of the simplest example – Here Boy class extends Human class. Both the classes have a
common method void eat(). Boy class is giving its own implementation to the eat() method or in
other words it is overriding the method eat().
class Human
System.out.println("Human is eating");
System.out.println("Boy is eating");
obj.eat();
Boy is eating
class Game
{
public void type()
{ System.out.println("Indoor & outdoor"); }
}
Output
Notice the last output. This is because of gm = ck; Now gm.type() will call Cricket version of
type method. Because here gm refers to cricket object.
Polymorphism in java is a concept by which we can perform a single action by different ways.
Polymorphism is derived from 2 greek words: poly and morphs. The word "poly" means many
and "morphs" means forms. So polymorphism means many forms.
There are two types of polymorphism in java: compile time polymorphism and runtime
polymorphism. We can perform polymorphism in java by method overloading and method
overriding.
If you overload static method in java, it is the example of compile time polymorphism. Here, we
will focus on runtime polymorphism in java.
In this process, an overridden method is called through the reference variable of a superclass.
The determination of the method to be called is based on the object being referred to by the
reference variable.
Upcasting
When reference variable of Parent class refers to the object of Child class, it is known as
upcasting. For example:
class A{}
A a=new B();//upcasting
In this example, we are creating two classes Bike and Splendar. Splendar class extends Bike
class and overrides its run() method. We are calling the run method by the reference variable of
Parent class. Since it refers to the subclass object and subclass method overrides the Parent class
method, subclass method is invoked at runtime.
Since method invocation is determined by the JVM not compiler, it is known as runtime
polymorphism.
class Bike{
void run(){System.out.println("running");}
b.run();
Finalize()
class a
String n;
a()
n="svcp";
System.out.println(n);
System.out.println("finalized....");
a obj=new a();
obj.finalize();
1) final variable
final variables are nothing but constants. We cannot change the value of a final variable once it is
initialized.
class Demo{
final int MAX_VALUE=99;
void myMethod()
{
//MAX_VALUE=101;
}
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 (Error: variable MAX_VALUE might not have been initialized).
class Demo{
//Blank final variable
final int MAX_VALUE;
Demo(){
//It must be initialized in constructor
MAX_VALUE=100;
}
void myMethod(){
System.out.println(MAX_VALUE);
}
public static void main(String args[]){
Demo obj=new Demo();
obj.myMethod();
}
}
Output:
100
Use of blank final variable- Lets say we have a Student class which is having a field called Roll
No. Since Roll No should not be changed once the student is registered, we can declare it as a
final variable in a class but we cannot initialize roll no in advance for all the students(otherwise
all students would be having same roll no). In such case we can declare roll no variable as blank
final and we initialize this value during object creation like this:
class StudentData{
//Blank final variable
final int ROLL_NO;
StudentData(int rnum){
//It must be initialized in constructor
ROLL_NO=rnum;
}
void myMethod(){
System.out.println("Roll no is:"+ROLL_NO);
}
public static void main(String args[]){
StudentData obj=new StudentData(1234);
obj.myMethod();
}
}
Output:
Roll no is:1234
More about blank final variable at StackOverflow and Wiki.
A static final variable that is not initialized during declaration can only be initialized in static
block. Example:
class Example{
//static blank final variable
static final int ROLL_NO;
static{
ROLL_NO=1230;
}
public static void main(String args[]){
System.out.println(Example.ROLL_NO);
}
}
Output:
1230
2) final method
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.
Example:
class XYZ{
final void demo(){
System.out.println("XYZ Class Method");
}
}
class XYZ{
final void demo(){
System.out.println("XYZ Class Method");
}
}
}
}
Output:
3) final class
Points to Remember:
1) A constructor cannot be declared as final.
2) Local final variable must be initializing during declaration.
3) All variables declared in an interface are by default final.
4) We cannot change the value of a final variable.
5) A final method cannot be overridden.
Super
super keyword is used for calling the parent class method/constructor.
super Usage:
class parent
String s="Parent";
String s="Child";
void print()
System.out.println(s);
System.out.println(super.s);
obj.print();
Output –
Child
Parent
class Parentclass
Parentclass()
System.out.println("Constructor of Superclass");
Subclass()
super();
System.out.println("Constructor of Subclass");
void display(){
System.out.println("Hello");
obj.display();
Output –
Constructor of Superclass
Constructor of Subclass
Hello
class Human
System.out.println("Human is eating");
super.eat();
System.out.println("Boy is eating");
obj.eat();
Output –
Human is eating
Boy is eating
Static Keyword
The static keyword in java is used for memory management mainly. We can apply java static
keyword with variables, methods, blocks and nested class. The static keyword belongs to the
class than instance of the class.
Static Variable
The static variable can be used to refer the common property of all objects (that is not
unique for each object) e.g. company name of employees,college name of students etc.
The static variable gets memory only once in class area at the time of class loading.
Program –
class Counter{
int count=0;//will get memory when instance is created
Counter(){
count++;
System.out.println(count);
}
}
}
Output:1
1
1
class Counter2{
static int count=0;//will get memory only once and retain its value
Counter2(){
count++;
System.out.println(count);
}
}
}
Output:1
2
3
Example -
class staticdemo
int rollno;
String name;
rollno = r;
name = n;
void display ()
s1.display();
s2.display();
Static Method –
If you apply static keyword with any method, it is known as static method.
A static method can call only other static methods and cannot call a non-static method
from it.
A static method can be accessed directly by the class name and doesn’t need any object
Syntax : <class-name>.<method-name>
A static method cannot refer to “this” or “super” keywords in anyway
The static method cannot use non static data member or call non-static method directly.
class smethod
int rollno;
String name;
college = "SVCP";
smethod(int r, String n)
rollno = r;
name = n;
void display ()
smethod.change();
s1.display();
s2.display();
s3.display();
Static Block
class sblock{
static
System.out.println("Hello main");
Important Points –
A class that is declared using “abstract” keyword is known as abstract class. It may or may not
include abstract methods which means in abstract class you can have concrete methods (methods
with body) as well along with abstract methods ( without an implementation, without braces, and
followed by a semicolon). An abstract class can not be instantiated (you are not allowed to
create object of Abstract class).
Syntax –
1) If the class is having few abstract methods and few concrete methods: declare it as
abstract class.
2) If the class is having only abstract methods: declare it as interface.
Key Points:
1. An abstract class has no use until unless it is extended by some other class.
2. If you declare an abstract method (discussed below) in a class then you must declare the
class abstract as well. you can’t have abstract method in a non-abstract class. It’s vice
versa is not always true: If a class is not having any abstract method then also it can be
marked as abstract.
3. Abstract class can have non-abstract method (concrete) as well.
Abstract methods
Well, we already discussed about abstract methods in the above section. Lets take few examples
to understand it better.
Syntax:
3) It must be overridden. An abstract class must be extended and in a same way abstract
method must be overridden.
Note: The class which is extending abstract class must override (or implement) all the abstract
methods.
3.3 Interface
Interface is a pure abstract class. They are syntactically similar to classes, but you cannot create
instance of an Interface and their methods are declared without any body. Interface is used to
achieve complete abstraction in Java. When you create an interface it defines what a class can
do without saying anything about how the class will do it.
Syntax :
interface interface_name { }
Example of Interface
interface Moveable
int AVERAGE-SPEED=40;
void move();
interface Moveable
void move();
vc.move();
Output :
Though classes in java doesn't suppost multiple inheritance, but a class can implement more than
one interface.
interface Moveable
boolean isMoveable();
interface Rollable
boolean isRollable
int width;
boolean isMoveable()
return true;
boolean isRollable()
return true;
System.out.println(tr.isMoveable());
System.out.println(tr.isRollable());
Output :
true
true
interface NewsPaper
news();
colorful();
Abstract class is a class which contain one Interface is a Java Object containing method
or more abstract methods, which has to be declaration but no implementation. The classes
implemented by its sub classes. which implement the Interfaces must provide the
method definition for all the methods.
Abstract class is a Class prefix with an Interface is a pure abstract class which starts with
abstract keyword followed by Class interface keyword.
definition.
Abstract class can also contain concrete Whereas, Interface contains all abstract methods
methods. and final variable declarations.
Abstract classes are useful in a situation Interfaces are useful in a situation that all
that Some general methods should be properties should be implemented.
implemented and specialization behavior
should be implemented by child classes.
3.4 Packages
Package are used in Java, in-order to avoid name conflicts and to control access of class,
interface and enumeration etc. A package can be defined as a group of similar types of classes,
interface, enumeration and sub-package. Using package it becomes easier to locate the related
classes.
Creating a package
Creating a package in java is quite easy. Simply include a package command followed by name
of the package as the first statement in java source file.
package mypack;
...statement;
Java uses file system directory to store package. For example the .class for any classes you to
define to be part of mypack package must be stored in a directory called mypack
package mypack
class Book
String bookname;
String author;
Book(String b, String c)
this.bookname = b;
this.author = c;
class test
bk.show();
create a directory under your current working development directory(i.e. JDK directory),
name it as mypack.
compile the source file
Put the class file into the directory you have created.
Execute the program from development directory.
Package is a way to organize files in java, it is used when a project consists of multiple modules.
It also helps resolve naming conflicts. Package's access level also allows you to protect data from
being used by the non-authorized classes.
import keyword
import keyword is used to import built-in and user-defined packages into your java source file.
So that your class can refer to a class that is in another package by directly using its name.
There are 3 different ways to refer to class that is present in different package
Example :
//statement;
Example :
import java.util.Date;
//statement.
Example :
import java.util.*;
//statement;
Access Specifiers