0% found this document useful (0 votes)
17 views20 pages

Java 2nd Chapter

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views20 pages

Java 2nd Chapter

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

UNIT-2

Inheritance, Overriding, Interfaces and Packages


Inheritance:
An inheritance is a process of deriving properties and behaviours from base class to the sub class.
Inheritance is a mechanism wherein a new class is derived from an existing class. In Java, classes may inherit or
acquire the properties and methods of other classes.
Ex: Relation between father and son.
Types of inheritances in java:
 Single-level inheritance.
 Multi-level Inheritance.
 Hierarchical Inheritance.
 Multiple Inheritance.
 Hybrid Inheritance.
Single-level inheritance:
A class inherits the properties from single class is known as single-level inheritance. Which is having only one
super class and only one sub class.

Syntax:
Class A
{
Block of code
}
Class B extends A
{
Block of code
}
Sample program for single level inheritance:
public class A
UNIT-2
Inheritance, Overriding, Interfaces and Packages
{
public void display()
{
System.out.println("I am from class A");
}
}
// B is inheriting display method of A
class B extends A
{
public void print()
{
System.out.println("I am from class B");
}
public static void main(String[] args) {
B objB = new B();
objB.display();
// Reusing the method of A named display
objB.print();
}
}
Multi-level inheritance:
In multi-level inheritance we have only one super class and multiple sub classes. The multi-level inheritance
includes the involvement of at least two or more than two classes.

Syntax:
Class A
UNIT-2
Inheritance, Overriding, Interfaces and Packages
{
}
Class B extends A
{
}
Class C extends B
{
}
Sample programm for multi-level inheritance:
class Animal
{
void eat()
{
System.out.println("eating...");
}
}
class Dog extends Animal
{
void bark()
{
System.out.println("barking...");
}
}
class BabyDog extends Dog
{
void weep()
{
System.out.println("weeping...");
}
}
class TestInheritance2
UNIT-2
Inheritance, Overriding, Interfaces and Packages
{
public static void main(String args[])
{
BabyDog d=new BabyDog();
d.weep();
d.bark();
d.eat();
}
}
Hierarchical inheritance:
An inheritance which contain only one super class and multiple sub classes and all sub classes directly extends
super class called hierarchical inheritance.

Syntax:
class A
{
}
Class B extends A
{
}
Class c extends A
{
}
Sample program for hierarchical inheritance:
Class A
{
UNIT-2
Inheritance, Overriding, Interfaces and Packages
void input()
{
System.out.println(“Enter your name:”);
}
}
Class B extends A
{
void show()
{
System.out.println(“My name is puneeth”);
}
}
Class C extends A
{
void disp()
{
System.out.println(“My name is chowhan”);
}
}
Class demo
{
Public static void main(String[] args)
{
B r=new B();
C r2=new C();
r.input(); r.show();
r2.input(); r2.disp();
}
}
Multiple inheritance:
UNIT-2
Inheritance, Overriding, Interfaces and Packages
The multiple inheritance is having capability of creating a single class with multiple super classes. JAVA
doesn’t support multiple inheritance but we can achieve this through “interfaces” because interface contains
only abstract method, which implementation is provided by the sub classes.
Note: Class C extends A, B (A, B are super classes we can’t extend them)
Class C implements A, B (by using implement we can access the properties of A, B to C)

Syntax: Syntax:
Class A Interface A
{
{
}
}
Class B
Interface B
{
{
}
}
Class C extends A, B
Class C implements A, B
{
{
}
}
(This is not allowed in java)
Sample program for multiple intheritance:
interface AnimalEat
{
void eat();
}
interface AnimalTravel
{
void travel();
}
class Animal implements AnimalEat, AnimalTravel
{
UNIT-2
Inheritance, Overriding, Interfaces and Packages
public void eat()
{
System.out.println("Animal is eating");
}
public void travel()
{
System.out.println("Animal is travelling");
}
}
public class Demo
{
public static void main(String args[])
{
Animal a = new Animal();
a.eat(
a.travel();
}
}

Hybrid inheritance:
The hybrid inheritance is the composition of two or more types of inheritance. The main purpose of using hybrid
inheritance is to modularize the code into well-defined classes. It also provides the code reusability. The hybrid
inheritance can be achieved by using the following combinations:
 Single and Multiple Inheritance (not supported but can be achieved through interface)
 Multilevel and Hierarchical Inheritance
 Hierarchical and Single Inheritance
 Multiple and Multilevel Inheritance

Program to implementing Single and Multiple Inheritance


class HumanBody
UNIT-2
Inheritance, Overriding, Interfaces and Packages
{
public void displayHuman()
{
System.out.println("Method defined inside HumanBody class");
}
}
interface Male
{
public void show();
}
interface Female
{
public void show();
}
public class Child extends HumanBody implements Male, Female
{
public void show()
{
System.out.println("Implementation of show() method defined in interfaces Male and Female");
}
public void displayChild()
{
System.out.println("Method defined inside Child class");
}
public static void main(String args[])
{
Child obj = new Child();
System.out.println("Implementation of Hybrid Inheritance in Java");
obj.show();
obj.displayChild();
} }
UNIT-2
Inheritance, Overriding, Interfaces and Packages
Program to implement Multilevel and Hierarchical Inheritance:
//parent class
class GrandFather
{
public void showG()
{
System.out.println("He is grandfather.");
}
}
class Father extends GrandFather
{
public void showF()
{
System.out.println("He is father.");
}
}
class Son extends Father
{
public void showS()
{
System.out.println("He is son.");
}
}
public class Daughter extends Father
{
public void showD()
{
System.out.println("She is daughter.");
}
public static void main(String args[])
UNIT-2
Inheritance, Overriding, Interfaces and Packages
{
Son obj = new Son();
obj.showS(); // Accessing Son class method
obj.showF(); // Accessing Father class method
obj.showG(); // Accessing GrandFather class method
Daughter obj2 = new Daughter();
obj2.showD(); // Accessing Daughter class method
obj2.showF(); // Accessing Father class method
obj2.showG(); // Accessing GrandFather class method
} }
Program to implement Hierarchical and Single Inheritance:
class C
{
public void disp()
{
System.out.println("C");
}
}
class A extends C
{
public void disp()
{
System.out.println("A");
}
}
class B extends C
{
public void disp()
{
System.out.println("B");
} }
UNIT-2
Inheritance, Overriding, Interfaces and Packages
public class D extends A
{
public void disp()
{
System.out.println("D");
}
public static void main(String args[])
{
D obj = new D();
obj.disp();
} }
METHOD OVERRIDING AND USAGE OF SUPER KEYWORD:
A method overriding is a runtime polymorphism. The term overriding means writing the same method in different
ways. Which is both parent and children classes have same method decleration will be called method overriding.
Uses of method overriding:
 Provide specific implementation of a method which is already provided by parent class.
 Used for runtime polymorphism.
Rules for method overriding:
 Override method should have same name and parameter list in super class.
 Overriding is done in only related classes.
 Static and final methods are not overridden.
Sample program for method overriding in java
class Vehicle
{
//defining a method
void run()
{
System.out.println("Vehicle is running");
}
}
//Creating a child class
class Bike2 extends Vehicle
UNIT-2
Inheritance, Overriding, Interfaces and Packages
{
//defining the same method as in the parent class
void run()
{
System.out.println("Bike is running safely");
}
public static void main(String args[])
{
Bike2 obj = new Bike2(); //creating object
obj.run(); //calling method
}
}
SUPER KEYWORD
The super keyword in Java is a reference variable which is used to refer immediate parent class object.
Whenever you create the instance of subclass, an instance of parent class is created implicitly which is referred
by super reference variable.
Usage of super keyword:
 Super can be used to refer immediate parent class instance variable.
 Super can be used to invoke immediate parent class method.
 Super () can be used to invoke immediate parent class constructor.
Sample program for use of super keyword:
class Animal
{
void eat()
{
System.out.println("eating...");
}
}
class Dog extends Animal
{
void eat(){System.out.println("eating bread...");
}
UNIT-2
Inheritance, Overriding, Interfaces and Packages
void bark()
{
System.out.println("barking...");
}
void work()
{
super.eat();
bark();
}
}
class TestSuper2
{
public static void main(String args[])
{
Dog d=new Dog();
d.work();
}
}
CONCEPT OF INTERFACES
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. There can be only abstract methods in the Java
interface, not method body. It is used to achieve abstraction and multiple inheritance in Java.
 An interface can contain any number of methods.
 An interface is written in a file with a .java extension, with the name interface matching the name of the
file.
 The byte code of an interface appears in a .class file.
Example:
public interface MyInterface
{ System.out.println(MyInterface.hello);
public String hello=”Hello”;
public void sayHELLO();
}
UNIT-2
Inheritance, Overriding, Interfaces and Packages
Implementing an interface
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();
}
}
Rules for interface
o A class can implements more than one interface at a time.
o A class can extend only one class, but implement many interfaces.
o An interface can extend another interface, similarly to the way that a class can extend another class.
The scope of variables in interfaces:
Every variable used in a programming language holds a scope. The scope tells the compiler about the segment
within a program where the variable is accessible or used. A java interface can contain both variables and
constants.
DIFFERENCES BETWEEN INTERFACE AND ABSTRACT CLASS
S.NO INTERFACE ABSTRACT CLASS
1. The interface keyword is used to declare The abstract keyword is used to declare abstract
interface. class
2. An interface can be implemented using keyword An abstract class can be extended using keyword
"implements" "extends".
3. Members of a Java interface are public by default. A Java abstract class can have class members like
private, protected, etc
4. Interface has only static and final variables Abstract class can have final, non-final, static and
non-static variables.
UNIT-2
Inheritance, Overriding, Interfaces and Packages
5. Interface supports multiple inheritance. Abstract class doesn't support multiple inheritance
6. Example: Example:
public interface Drawable public abstract class Shape
{ {
void draw(); public abstract void draw();
} }
7. Interface can have only abstract methods. Since Abstract class can have abstract and non-abstract
Java 8, it can have default and static methods also. methods.
8. Interface supports multiple inheritance Abstract class doesn't support multiple inheritance
9. Interface doesn’t contain data member. Abstract class contain data member.
PACKAGE
A java package is a group of similar types of classes, interfaces and sub-packages. It can be categorized in two
forms, 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.

Advantages of java package:


 Java package is used to categorize the classes and interfaces so that they can be easily maintained.
 Java package provides access protection.
 Java package removes naming collision.
Example for create a package in java by using package keyword:
//save as Simple.java.
package mypack;
public class Simple
{
public static void main(String args[])
{
System.out.println("Welcome to package");
}}
UNIT-2
Inheritance, Overriding, Interfaces and Packages
How to compile java package:
If you are not using any IDE, you need to follow the syntax given below:
javac -d directory javafilename
Example
javac -d. Simple.java
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
The -d is a switch that tells the compiler where to put the class file i.e. it represents destination. The . represents
the current folder.
CONCEPT OF CLASS PATH
CLASSPATH is an environment variable which is used by Application ClassLoader to locate and load the .class
files. The CLASSPATH defines the path, to find third-party and user-defined classes that are not extensions or
part of Java platform.
>SET CLASSPATH=.;c\myProject\classes;d:\tomcat\lib\servelet-api.jar
>java classpath c:\myProject\classes com.abc.project1.subproject2.MyClass3
CONCEPT OF ACCESS PROTECTION
There are two types of modifiers in java : access modifiers and non-access modifiers. The access modifiers in
java specifies accessibility of a data member, method, constructor or class.
1. Private
2. Default
3. Protected
4. Public
The non-access modifiers such as static, abstract, synchronized, native, volatile, transient.
Private access modifier:
This will be access modifiers is accessible only within class.
Default access modifier:
If we don’t use any modifier, it is treated as default by default this will be accessed only within the package.
Protected access modifier:
The protected modifier is accessible within and outside the package but through inheritance only. The protected
access modifier can be applied on the data member, method and constructor. It can’t be applied on the class.
Public access modifier:
This will be accessed from everywhere. It has the widest scope among all other modifiers.
UNIT-2
Inheritance, Overriding, Interfaces and Packages
MECHANISM OF IMPORTING PACKAGES
If we want to use a package in Java program it is necessary to import that package at the top of the program by
using the import keyword before the package name.
1. Import package.*;
2. Import package.classname;
3. Fully qualified name.
Using packagename:
If we 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:
package pack;
public class A
{
Public void msg()
{
System.out.println(“Hello”);
}
}
package mypack;
import pack.*;
class B
{
public static void main(string args[])
{
A.obj=new A();
Obj.msg();
}}
Using packagename.classname:
If we can import package.classname then only declared class of thos package will be accessible
Example:
package pack;
public class A
UNIT-2
Inheritance, Overriding, Interfaces and Packages
{
public void msg()
{
System.out.println(“Hello”);
}
}
package mypack;
import pack.A;
class B
{
public static void main(string args[])
{
A.obj=new A();
Obj.msg();
}}
Using fully qualified name:
A fully-qualified class name in Java contains the package that the class originated from. Also, an inner class is a
class that is another class member. So, the fully-qualified name of an inner class can be obtained using the
getName() method.
Example:
package pack;
public class A
{
public void msg()
{
System.ou.println(“Hello”);
}
}
package mypack;
class B
{
UNIT-2
Inheritance, Overriding, Interfaces and Packages
public static void main(string args[])
{
pack.A obj=new pack.A();
obj.msg();
}}
SIMPLE APPLICATION TO DESING PACKAGES WITH SAMPLE PROGRAMS
Importing a package:
If we want to use a package in java program it is necessary to import that package at the top of the program by
using the import keyword before the package name
Syntax:
Import packageName;
Program to create package
package Animal;
public interface behaviours
{
void type()
void food()
}
Importing the package in java program:
Import Animals.*
class Elephant implements behaviours
{
public void type()
{
System.out.println(“n Elephant is of Viviparity type.”);
}
public void food()
{
System.out.println(“n Elephant is of Herbivorous type.”);
}
}
UNIT-2
Inheritance, Overriding, Interfaces and Packages
class DemoPackage
{
public static void main(string args[])
{
Elephant e1=new Elephant();
e1.type();
e1.food();
}
}

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy