SRCMBMM Sanchalit SMT K.S Kapashi Bca College, Palitana Java Unit-3
SRCMBMM Sanchalit SMT K.S Kapashi Bca College, Palitana Java Unit-3
S KAPASHI BCA
COLLEGE,PALITANA
JAVA UNIT-3
Inheritance
- The class which inherits the properties of other is known as subclass (derived
class, child class) and the class whose properties are inherited is known as
superclass (base class, parent class).
- Inheritance can be defined as the procedure or mechanism of acquiring all the
properties and behavior of one class to another, i.e., acquiring the properties and
behavior of child class from the parent class. This concept was built to achieve
the advantage of creating a new class that gets built upon an already existing
class(es). It is mainly used for code reusability within a Java program.
- Moreover, a hierarchical order of management of information can also be done
using this concept. Here two types of classes build relationships with each other
which are a base class and derived class.
- The class that gets inherited taking the properties of another class is the subclass
or derived class or child class. Again, the class whose properties get inherited is
the superclass or base class or parent class. The keyword extends used to inherit
the properties of the base class to derived class.
Extends Keyword
extends is the keyword used to inherit the properties of a class. Following is the syntax of
extends keyword.
Syntax
class Super {
.....
.....
}
class Sub extends Super {
.....
.....
Example:-
class employee {
intwt = 8;
}
Super is a keyword of Java which refers to the immediate parent of a class and is used inside
the subclass method definition for calling a method defined in the superclass. A superclass
having methods as private cannot be called. Only the methods which are public and protected
can be called by the keyword super. It is also used by class constructors to invoke
constructors of its parent class.
Syntax:-
super.<method-name>();
Example:-
class Superclass {
int age;
Superclass(int age) {
this.age = age;
}
IS-A Relationship
IS-A is a way of saying: This object is a type of that object. Let us see how the extends
keyword is used to achieve inheritance.
publicclassAnimal{
}
publicclassMammalextendsAnimal{
}
publicclassReptileextendsAnimal{
}
publicclassDogextendsMammal{
}
Now, based on the above example, in Object-Oriented terms, the following are true −
With the use of the extends keyword, the subclasses will be able to inherit all the properties
of the superclass except for the private properties of the superclass.
HAS-A relationship
These relationships are mainly based on the usage. This determines whether a certain class
HAS-A certain thing. This relationship helps to reduce duplication of code as well as bugs.
Example
publicclassVehicle{}
publicclassSpeed{}
publicclassVanextendsVehicle{
privateSpeedsp;
}
Types of Inheritance
Single inheritance:-
When a single class gets derived from its base class, then this type of inheritance is termed
as single inheritance. The figure drawn above has class A as the base class, and class B gets
derived from that base class.
class Teacher {
void teach() {
System.out.println("Teaching subjects");
}
}
class Students extends Teacher {
void listen() {
System.out.println("Listening to teacher");
}
}
classCheckForInheritance {
public static void main(String args[]) {
Students s1 = new Students();
s1.teach();
s1.listen();
}
}
Multi-level Inheritance
In this type of inheritance, a derived class gets created from another derived class and can
have any number of levels.
Example:-
class Teacher {
void teach() {
System.out.println("Teaching subject");
}
}
class Student extends Teacher {
void listen() {
System.out.println("Listening");
}
}
classhomeTution extends Student {
void explains() {
System.out.println("Does homework");
}
}
classCheckForInheritance {
Hierarchical Inheritance
In this type of inheritance, there are more than one derived classes which get created from
one single base class.
Example:-
class Teacher {
void teach() {
System.out.println("Teaching subject");
}
}
class Student extends Teacher {
void listen() {
System.out.println("Listening");
}
}
class Principal extends Teacher {
void evaluate() {
System.out.println("Evaluating");
}
}
classCheckForInheritance {
public static void main(String argu[]) {
Principal p = new Principal();
p.evaluate();
p.teach();
// p.listen(); will produce an error
}
}
Method Overriding
Declaring a method in the subclass which already exists there in the parent class is known as
method overriding. When a class is inheriting a method from a superclass of its own, then
there is an option of overriding the method provided it is not declared as final. The
advantage of using overriding is the ability to classify a behavior that's specific to the child
class, and the child class can implement a parent class method based on its necessity.
There are certain rules that a programmer should follow to implement overriding. These are:
In Java, a method can only be written in the child class and not in same class.
Argument list should be the same as that of the overridden method of that class.
Instance methods can also be overridden if they are inherited by the child class.
A constructor cannot be overridden.
Final - declared methods cannot be overridden.
Any method that is static cannot be used to override.
The return type must have to be the same, or a subtype of the return type declared in
the original overridden method in the parent class.
If a method cannot be inherited, then it cannot be overridden.
A child class within the same package as the instance's parent class can override any
parent class method that is not declared private or final.
A child class in a different package can only override the non-final methods declared
as public or protected.
Example:-
class college {
public void move() {
System.out.println("College is open");
}
}
classuniv extends college {
public void move() {
System.out.println("University is open too");
}
}
public class stud {
public static void main(String args[]) {
college a = new college();
college b = new univ();
a.move();
b.move();
}
}
Example:-2
class parent {
public void work() {
System.out.println("Parent is under retirement from work.");
}
}
class child extends parent {
public void work() {
System.out.println("Child has a job");
System.out.println(" He is doing it well");
}
Polymorphism
Static Polymorphism
Dynamic Polymorphism.
Abstract classes
A class which contains the abstract keyword in its declaration is known as abstract class.
Abstract classes may or may not contain abstract methods, i.e., methods without body
( public void get(); )
But, if a class has at least one abstract method, then the class must be declared
abstract.
If a class is declared abstract, it cannot be instantiated.
To use an abstract class, you have to inherit it from another class, provide
implementations to the abstract methods in it.
If you inherit an abstract class, you have to provide implementations to all the abstract
methods in it.
Example:-
}
Abstract method
When a programmer wants any class having a specific method but also want the actual
execution of that method to be resolute by its child classes, the methods can be declared in
the base class in the form of abstract methods.
Interfaces
An interface is a reference type in Java. It is similar to class. It is a collection of abstract
methods. A class implements an interface, thereby inheriting the abstract methods of the
interface.
Writing an interface is similar to writing a class. But a class describes the attributes and
behaviors of an object. And an interface contains behaviors that a class implements.
Unless the class that implements the interface is abstract, all the methods of the interface need
to be defined in the class.
Use:-
Declaring Interfaces
The interface keyword is used to declare an interface. Here is a simple example to declare an
interface −
Example
/* File name : NameOfInterface.java */
importjava.lang.*;
// Any number of import statements
publicinterfaceNameOfInterface{
// Any number of final, static fields
// Any number of abstract method declarations\
}
An interface is implicitly abstract. You do not need to use the abstract keyword while
declaring an interface.
Each method in an interface is also implicitly abstract, so the abstract keyword is not
needed.
Methods in an interface are implicitly public.
Example
/* File name : Animal.java */
interfaceAnimal{
publicvoid eat();
publicvoid travel();
}
Implementing Interfaces
When a class implements an interface, you can think of the class as signing a contract,
agreeing to perform the specific behaviors of the interface. If a class does not perform all the
behaviors of the interface, the class must declare itself as abstract.
A class uses the implements keyword to implement an interface. The implements keyword
appears in the class declaration following the extends portion of the declaration.
Example
/* File name : MammalInt.java */
publicclassMammalIntimplementsAnimal{
publicvoid eat(){
System.out.println("Mammal eats");
}
publicvoid travel(){
System.out.println("Mammal travels");
}
publicintnoOfLegs(){
return0;
}
publicstaticvoid main(Stringargs[]){
MammalInt m =newMammalInt();
m.eat();
m.travel();
}
}
Extending Interfaces
An interface can extend another interface in the same way that a class can extend another
class. The extends keyword is used to extend an interface, and the child interface inherits the
methods of the parent interface.
Example
// Filename: Sports.java
publicinterfaceSports{
publicvoidsetHomeTeam(String name);
publicvoidsetVisitingTeam(String name);
}
// Filename: Football.java
publicinterfaceFootballextendsSports{
publicvoidhomeTeamScored(int points);
publicvoidvisitingTeamScored(int points);
publicvoidendOfQuarter(int quarter);
}
// Filename: Hockey.java
publicinterfaceHockeyextendsSports{
publicvoidhomeGoalScored();
publicvoidvisitingGoalScored();
publicvoidendOfPeriod(int period);
publicvoidovertimePeriod(intot);
}
A Java class can only extend one parent class. Multiple inheritance is not allowed. Interfaces
are not classes, however, and an interface can extend more than one parent interface.The
extends keyword is used once, and the parent interfaces are declared in a comma-separated
list.
For example, if the Hockey interface extended both Sports and Event, it would be declared as
Example
publicinterfaceHockeyextendsSports,Event
Introduction to Packages
A package is a mechanism to group the similar type of classes, interfaces and sub-packages
and provide access control. It organizes classes into single unit.
In Java already many predefined packages are available, used while programming.
For example: java.lang, java.io, java.util etc.
Advantages of Packages
Types of Packages
There are two types of packages available in Java.
1. Built-in packages
Built-in packages are already defined in java API. For example: java.util, java.io, java,lang,
java.awt, java.applet, java.net, etc.
2. User defined packages
The package we create according to our need is called user defined package.
Creating a Package
We can create our own package by creating our own classes and interfaces together. The
package statement should be declared at the beginning of the program.
Syntax:
package <packagename>;
class ClassName
{
……..
……..
}
// Demo.java
package p1;
class Demo
{
public void m1()
{
System.out.println("Method m1..");
}
}
How to compile?
Syntax: javac –d directory javafilename
For Example: javac –d . Demo.java
How to run?
To run: java p1.Demo
// Vehicle.java
package vehicles;
interface Vehicle
{
public void run();
public void speed();
}
//Bike.java
package vehicles;
public class Bike implements Vehicle
{
public void run()
{
System.out.println("Bike is running.");
}
public void speed()
{
System.out.println("Speed of Bike: 50 Km/h");
}
public static void main(String args[])
{
Bike bike = new Bike();
bike.run();
bike.speed();
}
}
Compile:
javac –d . Vehicle.java
javac –d . Bike.java
Run:
java vehicles.Bike
Output:
Bike is running
Speed of Bike: 50 Km/h
The import keyword provides the access to other package classes and interfaces in current
packages. “import” keyword is used to import built-in and user defined packages in java
program.
Interface
Syntax:
interface InterfaceName
{
public void method1();
public void method2();
<type> variableName = value;
}
interface Employee
{
static final Id = 101;
static final String name = “ABC”;
void show();
void getSalary(double salary);
}
Extending interfaces
An interface has to extend another interface as it happens in class. It cannot implement another
interface.
interface Base
{
public void display ();
}
interface Derive extends Base
{
public void show ();
}
Implementing interfaces
A class implements an interface. After that, class can perform the specific behavior on
an interface.
The implements keyword is used by class to implement an interface.
Syntax:
interface Results
{
final static float pi = 3.14f;
float areaOf(float l, float b);
}
class Rectangle implements Results
{
public float areaOf(float l, float b)
{
return (l * b);
}
}
class Square implements Results
{
public float areaOf(float l, float b)
{
return (l * l);
}
}
class Circle implements Results
{
public float areaOf(float r, float b)
{
return (pi * r * r);
}
}
public class InterfaceDemo
{
public static void main(String args[])
{
Rectangle rect = new Rectangle();
Square square = new Square();
Circle circle = new Circle();
System.out.println("Area of Rectangle: "+rect.areaOf(20.3f, 28.7f));
System.out.println("Are of square: "+square.areaOf(10.0f, 10.0f));
System.out.println("Area of Circle: "+circle.areaOf(5.2f, 0));
}
}
Output:
Area of Rectangle: 582.61
Are of square: 100.0
Area of Circle: 84.905594
interface Vehicle
{
void run();
}
interface Bike extends Vehicle
{
void stop();
}
public class Demo implements Bike
{
public void run()
{
System.out.println("Vehicle is running.");
}
public void stop()
{
System.out.println("Bike is stop.");
}
public static void main(String args[])
{
Demo obj = new Demo();
obj.run();
obj.stop();
}
}
Output:
Vehicle is running.
Bike is stop.
Marker Interface
An interface which does not contain any fields and methods is known as marker or tag
interface. It is an empty interface.
Example:
package java.util;
public interface EventListner
{
}
Access modifiers are simply a keyword in Java that provides accessibility of a class and its
member. They set the access level to methods, variable, classes and constructors.
public
default
protected
private
public
The member with public modifiers can be accessed by any classes. The public methods,
variables or class have the widest scope.
default
When we do not mention any access modifier, it is treated as default. It is accessible only within
same package.
int a = 25;
String str = "Java";
boolean m1()
{
return true;
}
protected
The protected modifier is used within same package. It lies between public and default access
modifier. It can be accessed outside the package but through inheritance only.
A class cannot be protected.
class Employee
{
protected int id = 101;
protected String name = "Jack";
}
public class ProtectedDemo extends Employee
{
private String dept = "Networking";
public void display()
{
System.out.println("Employee Id : "+id);
System.out.println("Employee name : "+name);
System.out.println("Employee Department : "+dept);
}
public static void main(String args[])
{
ProtectedDemo pd = new ProtectedDemo();
pd.display();
}
}
Output:
Employee Id : 101
Employee name : Jack
Employee Department : Networking
Private
The private methods, variables and constructor are not accessible to any other class. It is the most
restrictive access modifier. A class except a nested class cannot be private.
Output:
Private int a = 101
String s = TutorialRide
101 TutorialRide
Private Yes No No No