0% found this document useful (0 votes)
7 views30 pages

Java Unit 2

This document provides an overview of strings in Java, including their creation, immutability, and various built-in methods. It also introduces object-oriented programming concepts such as classes, objects, inheritance, polymorphism, and encapsulation, along with the benefits and applications of OOP. Additionally, it covers variable types, constructors, and the use of wrapper classes and vectors in Java programming.

Uploaded by

kavyaadhireddy5
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)
7 views30 pages

Java Unit 2

This document provides an overview of strings in Java, including their creation, immutability, and various built-in methods. It also introduces object-oriented programming concepts such as classes, objects, inheritance, polymorphism, and encapsulation, along with the benefits and applications of OOP. Additionally, it covers variable types, constructors, and the use of wrapper classes and vectors in Java programming.

Uploaded by

kavyaadhireddy5
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/ 30

UNIT II

STRINGS
String: A group of characters is called String. For example, “hello” is a string containing a sequence of
characters ‘h’,’e’,’l’,’l’,’o’. Java string provides a lot of concepts that can be performed on a string such as
compare, concatenation, equal, split, lemgth etc.
Creating Strings
The most direct way to create a string is to write
String greeting = "Hello world!”;
Whenever it encounters a string literal in your code, the compiler creates a String object with its value in this
case, "Hello world!'.
1) Example program for java strings
class StringDemo
{
public static void main(String args[])
{
// create strings
String first = "Java";
String second = "Python";
String third = "JavaScript";
// print strings
System.out.println(first); // print Java
System.out.println(second); // print Python
System.out.println(third); // print JavaScript
}
}
Output : D:\> javac StringDemo.java
D:\> java StringDemo
Java
Python
JavaScript
2) Example program for java strings
public class StringExample
{
Department of Computer Science Object Oriented Programming with JAVA Page 1
public static void main(String args[])
{
String s1="java";//creating string by java string literal
char ch[]={'s','t','r','i','n','g','s'};
String s2=new String(ch);//converting char array to string
String s3=new String("example");//creating java string by new keyword
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
}
}
Output : D:\> javac StringExample.java
D:\> java StringExample
java
strings
example
Immutability of Strings
In java, string objects are immutable. Immutable simply means un-modifiable or un-changeable. Once
string object is created its data or state can't be changed but a new string object is created. If we are trying to
perform any changes, with those changes will create new object. This non-changeable nature is nothing but
Immutability of the string object
STRING CLASS METHODS: The String class has a set of built-in methods that you can use on strings.
Method Description
1. s2=s1.toLOwerCase(); Converts the String to all lower case letters
2. s2=s1.toUpperCase(); Converts the String to all upper case letters
3. s2=s1.replace(“x”,”y”); Replace x with y
4.s2=s1.trim(); Remove white spaces at the beginning and end of the string s1.
5. s1.equals(s2); Compares two strings. Returns true if the strings are equal, and
false if not
6.s1.length(); Returns the length of a specified string
7.s1.charAt(n); Returns the character at the specified index (position)
8.s1.compareTo(s2); Compares two strings lexicographically

Department of Computer Science Object Oriented Programming with JAVA Page 2


9.s1.concat(s2); Appends a string to the end of another string
10.s1.split(); Split s1 string into an array of objects.
11.s1.isEmpty(); Checks s1 string is empty or not.
12.s1.lastIndexOf(); Returns the position of the last found occurrence of specified
characters in a string
13. s1.contains(); Checks whether a string contains a sequence of characters

14. s1.endsWith(); Checks whether a string ends with the specified character.

Example program for String handling functions


1. Example program Converting Lower case to Upper case
class StringDemo
{
public static void main(String args[])
{
String s1=new String("hello");
String s2=s1.toUpperCase();
System.out.println(s2);
}
}
Output : D:\> javac StringDemo.java
D:\> java StringDEmo
HELLO
2. Example program Converting Lower case to Upper case
class StringDemo
{
public static void main(String args[])
{
String s1=new String("HELLO");
String s2=s1.toLowerCase();
System.out.println(s2);
}
}

Department of Computer Science Object Oriented Programming with JAVA Page 3


Output : D:\> javac StringDemo.java
D:\> java StringDemo
hello
3. Example program Replacing string
class StringDemo1
{
public static void main(String args[])
{
String s1=new String("hello");
String s2=s1.replace("hello","dnr");
System.out.println(s2);
}
}
Output : D:\> javac StringDemo.java
D:\> java StringDemo
Dnr
4. Example program Trim a string
class StringDemo1
{
public static void main(String args[])
{
String s1=new String(" Hello ");
String s2=s1.trim();
System.out.println(s2);
}
}
Output : D:\> javac StringDemo.java
D:\> java StringDemo
Hello
Wrapper Classes: Primitive data types may be converted into object type by using Wrapper classes.
1. Taking of a variable and putting in a object is known as Wrapping.
2. Taking out that variable from an object is known as Unwrapping

Department of Computer Science Object Oriented Programming with JAVA Page 4


Converting primitive data type to object type by using Constructor method
Examples: Integer obj=new Integer(i);
Float obj=new Float(f);
Long obj=new Long(l);
Converting object data type to primitive data using type value method
Example: int i=obj.intValue();
float f=obj.floatValue();
long l=obj.longValue();
Vector: Vector is like the dynamic array which can grow or shrink its size. Unlike array, we can store n-
number of elements in it as there is no size limit. That can hold objects of any type and any number.
1. The vector is resizable (or) Growable array
2. Duplicate values are allowed
3. Insertion order is preserved
4. Null insertion is possible
5. Heterogeneous objects are allowed
6. Random access interface

INTRODUCTION TO OOPS
OOP(Object oriented programming): Object-Oriented Programming is a methodology or paradigm
to design a programs using classes and objects. It simplifies software development and maintenance by
providing some concepts
FEATURES OF OOP: There are 8 main features of OOPS as follows.
1) Class
2) Object
3) Inheritance
4) Polymorphism
5) Abstraction
6) Encapsulation
7) Dynamic Binding
8) Message Communication
1. Class: Class is a set of objects with similar properties and common behaviour. A class is a collection of
objects of similar type. Once class is defined, we can create any number objects belongs to that class
Ex: Class is SHAPE.
Department of Computer Science Object Oriented Programming with JAVA Page 5
2) Objects:
Objects are basic runtime entities, they may be characterized a location, a bank account and a table of
information .Each object holds data and code to operate on data. Object is an instance of a class. An object
contains properties and methods.
Ex: Object is Car.

Object : Car
Properties :
Colour :
Cost :
Methods :
Start()
Stop()
Drive()
3) Inheritance:
Inheritance is the process of acquiring properties from one class to another class. It supports the
concept of hierarchical classification. A super class exists in a hierarchical relationship with its subclass. One
super class can have many subclasses. In OOP the concept inheritance provides the idea of code reusability.

Department of Computer Science Object Oriented Programming with JAVA Page 6


4) Polymorphism:
Ability to take more than one form is known as Polymorphism. Polymorphism means many forms.
An operation may takes different behaviour in different instances.

5) Data Abstraction :
Data abstraction refers to the act of representing essential features without including background
details that is hiding the data.
Ex: Making a phone call
Information in Data and methods Information out

We know only how to make a phone call and how to receive a phone call but we don’t know internally what
goes on.
6) Data Encapsulation:
Wrapping up of data and member functions into single unit(binding the data) is known as Data
encapsulation. This is most useful feature for class.
Ex : java class.

7) Dynamic Binding:
The code related with the given procedure call is not known until the time of call run time.

Department of Computer Science Object Oriented Programming with JAVA Page 7


Ex: class A
{
void add();
}
class B
{
void add();
}

class C
{
public static void main(String args[])
{
A x=new A();
x.add();
}
}
In the above example the function add is not known their code until the time of call.
8) Message Communication :
An object oriented program consists set of objects that communicate with each other . It involves the
following basic steps.
1. Creating class the define objects and their behaviour.
2. Creating objects from class definitions.
3. Establishing communication among objects.
4.Objects communicate with one another by sending and receiving information.

Message

Sending Object Receiving Object

Department of Computer Science Object Oriented Programming with JAVA Page 8


BENFITS OF OOP:
 Through inheritance we can eliminate redundant code
 The principle of data hiding helps the programmer to build secure programs
 Software complexity can be easily managed
 Object oriented system can be easily upgraded from small to large system.
 It is easy to partition the work in a project based on objects
 Message passing techniques for communication between objets.
APPLICATION OF OOP:
 The most popular application of OOP is windows.
 There is hundreds of windows system developed by using OOP techniques.
Application of OOP includes:
a. Real-time Systems
b. Simulation and medalling
c. Object oriented data base
d. Hyper text, hyper media
e. AI and expert system
CLASSES AND OBJECTS
Class: Class is a set of objects with similar properties and Common behaviour.
Object : Objects are basic run time entities. Once Class is defined we can create any number of objects.
Syntax for Class:-
class classname
{
field declaration;
method declaration;
}
1.Field declaration:
We Can create any number of field in a class. These variables are called instance variables.
Syntax:-
class Rectangle
{
int length;
int width;
}
Department of Computer Science Object Oriented Programming with JAVA Page 9
2. Method Declaration:
A method which contains the actual implementation code. Methods are necessary for manipulating the data
contained in the class. Methods are declared inside of the class. But immediately after declaration of variable.
The general form of method is,
Syntax:-
return type methodname (parameter list)
{
Body of the method;
}
Example:- class Rectangle
{
int length;
int width;
void get data (int x, int y)
{
length=x;
width=y;
}
}
Creating Objects:-
Objects in java are created by using new operator. The new operator creates an object of the specified class
and returns a reference to the object.
Syntax:-
classname objectname = new classname();
Example:-
Rectangle rect1= new Rectangle();
Rectangle rect2= new Rectangle();
ACCESSING CLASS MEMBERS:
In outside of the class, we cannot access the instance variables and methods directly. We must use object
with dot(.) operator to access the class members.
Syntax:-
object name.variable name;
object name.method name;

Department of Computer Science Object Oriented Programming with JAVA Page 10


Example:-
class Student
{
void display()
{
int a=10, b=20, c;
c=a+b;
System.out.println(“Sum of c is =”+c);
}
public static void main(String args[])
{
Student s=new Student();
s.display();
}
}
Output : D:\> javac Student.java
D:\> java Student
Sum of c is = 30
TYPES OF VARIABLES: Java variables can be classified into three types
1. Instance Variables
2. Static Variables
3. Local Variables
1. Instance Variable
A variable declared inside the class but outside the body of the method, is called instance variable.
We call the instance variables by using the object.
Without creating an object there is no use of instance variable why because whenever we create an
object then only memory will be allocated for instance variables.
// Example program instance variables
class InstanceDemo
{
int a=10; // Instance variable
public static void main(String args[])
{

Department of Computer Science Object Oriented Programming with JAVA Page 11


InstanceDemo d=new InstanceDemo();
System.out.println(d.a);
System.out.println(“a value is :”+d.a);
}
}
OUTPUT :
D:\>javac InstanceDemo.java
D:\>java InstanceDemo
10
10
2. Static Variable
A variable which is declared as static is called static variable. Static variables lso known as Class
variables. Static variables are very flexible to access, we can access these static variables directly or by using
object name, or by using class name.
// Example program static variables
class StaticDemo
{
static int a=10; // static variable
public static void main(String args[])
{
System.out.println(a);
StaticDemo d=new StaticDemo();
System.out.println(d.a);
System.out.println(StaticDemo.a);
}
}
OUTPUT :
D:\>javac StaticDemo.java
D:\>java StaticDemo
10
10
10

Department of Computer Science Object Oriented Programming with JAVA Page 12


3. Local variables
A variable declared inside the body of the method is called local variable. You can use this variable
only within that method and the other methods in the class aren't even aware that the variable exists.
this keyword :
‘this’ keyword is used to access the instance variables whenever the instance variable names and the
local variables are same.
// Example program for Local variables
class LocalDemo
{
int a=10; // Instance variable
void show()
{
int a=15; //Local variable
System.out.println(a);
System.out.println(this.a);
}
public static void main(String args[])
{
LocalDemo d=new LocalDemo();
d.show();
System.out.println(d.a);
}
}
OUTPUT :
D:\>javac LocalDemo.java
D:\>java LocalDemo
15
10
10
CONSTRUCTORS: “A Constructor is a special type of method that is used to initialize the object. Java
constructor is invoked (activated) at the time of object creation. It constructs the values i.e., provides the data
for object that’s why it is called as constructor.”

Department of Computer Science Object Oriented Programming with JAVA Page 13


Rules for creating Constructor:-
There are basically two rules defined for the constructor.
• Constructor name must be same as the class name.
• Constructor must have no explicit return type.
Types of java Constructors:- There are two types of java constructors,
1. Default Constructor
2. Parameterized Constructor
1. Default Constructor:- A constructor that have no parameters is known as default constructor.
Purpose of Default Constructor:- It provides the default values to the object (like 0,null etc) depending on
the type.
Example:- class Student
{
int id;
String name;
void display()
{
System.out.println(id+" "+name);
}
public static void main(String args[])
{
Student s1=new Student();
s1.display();
Student s2=new Student();
s2.display();
}
}
Output : D:\> javac Student.java
D:\> java Student
0 null
0 null
Above class we are not creating any constructor so, compiler provides a default constructor. 0 and null
values are provided by default constructor.

Department of Computer Science Object Oriented Programming with JAVA Page 14


2. Parameterized Constructor:- A Constructor that have parameters is known as parameterized
constructors.
Purpose of Default Constructor:-
Parameterized constructor is used to provide different values to the distinct objects.
Example : class Student
{
int id;
String name;
Student(int a,String b)
{
id=a;
name=b;
}
void display()
{
System. out. println(id+" "+name);
}
public static void main(String args[])
{
Student s1=new Student(10, "Ramu");
s1.display();
Student s2=new Student(11,"Syam");
s2.display();
}
}

Output : D:\> javac Student.java


D:\> java Student
10 Ramu
11 Syam

Department of Computer Science Object Oriented Programming with JAVA Page 15


METHODS IN JAVA

METHODS IN JAVA
“A method in Java or Java Method is a collection of statements that perform some specific task and return
the result to the caller”. A Java method can perform some specific task without returning anything.
Methods in Java allow us to reuse the code without retyping the code
TYPES OF METHODS IN JAVA:
“A method in Java or Java Method is a collection of statements that perform some specific task and return
the result to the caller”. A Java method can perform some specific task without returning anything.
Methods in Java allow us to reuse the code without retyping the code.
There are two types of methods in Java
1. Predefined Method: In Java, predefined methods are the method that is already defined in the Java
class libraries is known as predefined methods. It is also known as the standard library method or built-in
method. We can directly use these methods just by calling them in the program at any point.
2. User-defined Method: The method written by the user or programmer is known as a user-
defined method. These methods are modified according to the requirement.
METHOD DECLARATION: The method declaration provides information about method attributes, such
as visibility, return-type, name, and arguments.

The general form of method is,


Syntax:-
return type methodname (parameter list)
{
Body of the method;
}
Example:- class Rectangle
{
int length;
int width;
void get data (int x, int y)
{
length=x;
width=y;
}
Department of Computer Science Object Oriented Programming with JAVA Page 16
}

Method Signature: Every method has a method signature. It is a part of the method declaration. It includes
the method name and parameter list.
Access Specifier: Access specifier or modifier is the access type of the method. It specifies the visibility of
the method. Java provides four types of access specifier:
o Public: The method is accessible by all classes when we use public specifier in our application.
o Private: When we use a private access specifier, the method is accessible only in the classes in which
it is defined.
o Protected: When we use protected access specifier, the method is accessible within the same package
or subclasses in a different package.
o Default: When we do not use any access specifier in the method declaration, Java uses default access
specifier by default. It is visible only from the same package only.
Return Type: Return type is a data type that the method returns. It may have a primitive data type, object,
collection, void, etc. If the method does not return anything, we use void keyword.
Method Name: It is a unique name that is used to define the name of a method. It must be corresponding to
the functionality of the method. Suppose, if we are creating a method for subtraction of two numbers, the
method name must be subtraction(). A method is invoked by its name.
Parameter List: It is the list of parameters separated by a comma and enclosed in the pair of parentheses. It
contains the data type and variable name. If the method has no parameter, left the parentheses blank.
Method Body: It is a part of the method declaration. It contains all the actions to be performed. It is enclosed
within the pair of curly braces.

Department of Computer Science Object Oriented Programming with JAVA Page 17


STATIC MEMBERS IN JAVA
The static keyword in Java is used for memory management mainly. We can apply static
keyword with variables, methods, blocks and nested classes
1. Static variable:
If we declare any variable as static is known as static variable. The static variable can be used to
refer to the common property of all objects (which is not unique for each object)
Example :
Company name of employees
College name of Students
Example program:
class Student
{
int rollno;//instance variable
String name;
static String college ="DNR COLLEGE";//static variable
Student(int r, String n)
{
rollno = r;
name = n;
}
void display()
{
System.out.println(rollno+" "+name+" "+college);
}
public static void main(String args[])
{
Student s1 = new Student(111,"Ramu");
Student s2 = new Student(222,"Raju");
s1.display();
s2.display();
}
}

Department of Computer Science Object Oriented Programming with JAVA Page 18


Output : D:\> javac Student.java
D:\> java Student
111 Ramu DNR COLLEGE
222 Raju DNR COLLEGE
2. Static method :
 If we apply static keyword to any method is known as static method.

 A static method can be invoked without the need for creating an instance of a class.

 A static method can access static data member and can change the value of it.

Restrictions for the static method :


There are two main restrictions for the static method. They are:
1. The static method cannot use non static data member or call non-static method directly.
2. “this” and “super” keywords are not used in this static context.
Example program
class Student
{
int rollno;
String name;
static String college = "DNR";
//static method to change the value of static variable
static void change()
{
college = "BV RAJU";
}
Student(int r, String n)
{
rollno = r;
name = n;
}
//method to display values
void display()
{
System.out.println(rollno+" "+name+" "+college);
}

Department of Computer Science Object Oriented Programming with JAVA Page 19


public static void main(String args[])
{
change(); // Student.change();
Student s1 = new Student(111,"Ramu");
s1.display();
Student s2 = new Student(222,"Raju");
s2.display();
Student s3 = new Student(333,"Ravi");
s3.display();
}
}
Output : D:\> javac Student.java
D:\> java Student
111 Ramu BV RAJU
222 Raju BV RAJU
333 Ravi BV RAJU
3. Static block :
 Is used to initialize the static data member.
 It is executed before the main method at the time of class loading.
Example program
class StaticBlock
{
static
{
System.out.println("static block is invoked");
}
public static void main(String args[])
{
System.out.println("Hello main");
}
}
Output : D:\> javac StaticBlock.java
D:\> java StaticBlock

Department of Computer Science Object Oriented Programming with JAVA Page 20


static block is invoked
Hello main
4. Nested class:
A class can be made static only if it is a nested class.
1. Nested static class doesn’t need reference of Outer class
2. A static class cannot access non-static members of the Outer class
Example program :
class StaticClassDemo
{
private static String str = "DNR COLLEGE";
//Static class
static class NestedDemo
{
//non-static method
public void display()
{
System.out.println(str);
}
}
public static void main(String args[])
{
NestedDemo obj = new NestedDemo();
obj.display();
}
}
Output : D:\> javac StaticClassDemo.java
D:\> java StaticClassDemo
DNR COLLEGE
this keyword :
‘this’ keyword is used to access the instance variables whenever the instance variable names and the
local variables are same. The main purpose of using this keyword in Java is to remove the confusion between
class attributes and parameters that have same names.

Department of Computer Science Object Oriented Programming with JAVA Page 21


// Example program for Local variables
class LocalDemo
{
int a=10; // Instance variable
void show()
{
int a=15; //Local variable
System.out.println(a);
System.out.println(this.a);
}
public static void main(String args[])
{
LocalDemo d=new LocalDemo();
d.show();
System.out.println(d.a);
}
}
OUTPUT :
D:\>javac LocalDemo.java
D:\>java LocalDemo
15
10
10
SUPER KEYWORD: By using super keyword, we can access the class members of the super class from
sub class. It is used to call super class methods from sub class. super keyword is used to call the super class
constructor in the sub class constructor. The most common use of the super keyword is to eliminate the
confusion between super classes and subclasses that have methods with the same name.
Example program:
class A
{
int a,b;
void show()
{

Department of Computer Science Object Oriented Programming with JAVA Page 22


System.out.println(“b value in super class :”+b);
}
}
class B extends A
{
int a,b;
B(int p,int q)
{
a=p;
super.b=q;
}
void show()
{
super.show();
System.out.println(“b value in super class :”+super.b);
System.out.println(“a value in sub class :”+a);
}
public static void main(String args[])
{
B obj=new B(10,20);
obj.show();
}
}
Output : D:\ javac B.java
D:\java B
b value in super class : 20
b value in super class : 20
a value in sub class : 10
METHOD OVERLOADING
Definition : “If a class contains multiple methods with same name but different parameters is known as
Method overloading.”

Department of Computer Science Object Oriented Programming with JAVA Page 23


Advantages:
Method overloading increases the readability of the program.
Different ways to overload the method
There are two ways to overload the method in java
1. By changing number of arguments
2. By changing the data type
1. By changing number of arguments :
In this example, we have created two methods, first sum() method performs addition of two numbers and
second sum method performs addition of three numbers.
Example program:
class Addition
{
void sum(int a,int b)
{
System.out.println(a+b);
}
void sum(int a,int b,int c)
{
System.out.println(a+b+c);
}
public static void main(String args[])
{
Addition a=new Addition();
a.sum(10,20);
a.sum(10,20,30);
}
}
Output : D:\> javac Addition.java

Department of Computer Science Object Oriented Programming with JAVA Page 24


D:\> java Addition
30
60
2. By changing the data type :
In this example, we have created two methods that differs in data type. The first sum method receives two
integer arguments and second sum method receives two double arguments.
Example program:
class Addition
{
void sum(int a,int b)
{
System.out.println(a+b);
}
void sum(double a,double b)
{
System.out.println(a+b);
}
public static void main(String args[])
{
Addition a=new Addition();
a.sum(10,20);
a.sum(10.5,10.5);
}
}
Output : D:\> javac Addition.java
D:\> java Addition
30
21.0
METHOD OVERRIDING
Definition : “If subclass (child class) has the same method as declared in the parent class, it is known
as method overriding.”

Department of Computer Science Object Oriented Programming with JAVA Page 25


Advantages:
1. Method overriding is used to provide the specific implementation of a method which is already
provided by its super class.
2. 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.
Example program:
class Vehicle
{
void run()
{
System.out.println("Vehicle is running");
}
}
class Bike extends Vehicle
{
void run()
{
System.out.println("Bike is running");
}
public static void main(String args[])
{
Bike b= new Bike();
b.run();
Vehicle v=new Vehicle();
v.run();
}
}
Output : D:\> javac Bike.java
D:\> java Bike
Bike is running

Department of Computer Science Object Oriented Programming with JAVA Page 26


Vehicle is running

INHERITANCE
Definition: Acquiring properties from one class to another class is called Inheritance.
Inheritance is one of the important feature of object oriented programming. Inheritance is a mechanism, in
which one object acquires all the properties and behaviours of parent objects. The idea behind inheritance is
that we can create new classes built upon existing classes.
When we inherit from an existing class, we can reuse methods and fields of parent class and we can
add new methods and fields also.
Syntax :
class subclass-name extends superclass-name
{
//methods and fields
}
Example :
class Dog extends Animal
{
eat()
sleep()
bark()
}

Advantages:
 For code re usability(To reuse the existing code without writing the new code)
 For method overriding(Run time polymorphism can be achieved)

TYPES OF INHERITANCE

Department of Computer Science Object Oriented Programming with JAVA Page 27


Java supports five types of inheritances as follows.
1. Single inheritance
2. Multiple inheritance
3. Hierarchical inheritance
4. Multi level inheritance
5. Hybrid inheritance

1. Single inheritance: Deriving a class from only one base class(super class) is known as Single inheritance.
In below image, the class A serves as a base class for the derived class B.

2. Multiple inheritance: Deriving a class from one or more base classes is known as Multiple inheritance.
Java does not support multiple inheritance with classes. In java, we can achieve multiple inheritance only
through Interfaces. In image below, Class C is derived from interface A and B.

3. Hierarchical inheritance: Deriving several classes from one base class is known as Hierarchical
inheritance. In below image, the class A serves as a base class for the derived class B,C and D.

Department of Computer Science Object Oriented Programming with JAVA Page 28


4. Multi level inheritance: Deriving a class from another derived class is known as Multi level inheritance.
In below image, the class A serves as a base class for the derived class B, which in turn serves as a base class
for the derived class C. In Java, a class cannot directly access the grandparent’s members.

5. Hybrid inheritance: Deriving a class from one or more derived classes that is derived from only one base
class is known as Hybrid inheritance. In below image, the class A serves as a base class for the derived class
B, C, which in turn B,C serves as a base classes for the derived class D. Since java doesn’t support multiple
inheritance with classes, the hybrid inheritance is also not possible with classes. In java, we can achieve
hybrid inheritance only through Interfaces.

Department of Computer Science Object Oriented Programming with JAVA Page 29


// Example program for Single inheritance
class A
{
void methodA()
{
System.out.println("Base class is Running");
}
}
class B extends A
{
void methodB()
{
System.out.println("Child class is Running");
}
public static void main(String args[])
{
B obj=new B();
obj.methodA();
obj.methodB();
}
}
Output : D:\> javac B.java
D:\> java B
Base class is Running
Child class is Running

Department of Computer Science Object Oriented Programming with JAVA Page 30

You might also like