Object Oriented Programming Using Java
Subject Code: 033CSC011
Unit - II
Sajeetkumar Pujar
Assistant Professor of Computer Science
Govt. First Grade College, Haliyal
Inheritance:
• Inheritance is the process by which objects of one class acquire
the properties of objects of another class
• Or the process of deriving a new class from an already existing
class.
• The advantage of inheritance is the idea of reusability.
• It means that we can add additional features to an existing class
without modifying it.
• The new class will have the combined features of both the classes.
Types of Inheritance:
• Single inheritance (One base class & one derived class)
• Multilevel inheritance (Derived from another derived class)
• Hierarchical inheritance (One base class & many derived classes)
• Multiple inheritance (Several base classes)
Note:
• Java does not support multiple inheritance.
• Multiple inheritance is implemented using the concept called
interface.
Single Inheritance:
• Single inheritance (One base class & one derived class)
// Program to demonstrate single inheritance.
class Base
{
void displayBase()
{
[Link]("Base Class");
}
}
class Derived extends Base
{
void displayDerived()
{
[Link]("Derived Class");
}
}
class SingleInheritance
{
public static void main(String args[])
{
Derived d = new Derived();
[Link]();
[Link]();
}
}
Multilevel Inheritance:
• Multilevel inheritance (Derived from another derived class)
// Program to demonstrate Multilevel
inheritance.
class A class Multilevel
{ {
void displayA() public static void main(String args[])
{ {
[Link]("Class A"); C c = new C();
} [Link]();
} [Link]();
class B extends A [Link]();
{ }
void displayB() }
{
[Link]("Class B");
}
}
class C extends B
{
void displayC()
{
[Link]("Class C");
}
}
Hierarchical Inheritance:
• Hierarchical inheritance (One base class & many derived classes)
// Program to demonstrate Hierarchical
inheritance.
class A class Hierarchical
{ {
void displayA()
{ public static void main(String args[])
[Link]("Class A"); {
} A a = new A();
} B b = new B();
class B extends A
{ C c = new C();
void displayB()
{ [Link]();
[Link]("Class B"); [Link]();
}
} [Link]();
class C extends A }
{ }
void displayC()
{
[Link]("Class C");
}
}
Multiple Inheritance(Interface):
• Multiple inheritance (Several base classes)
Note:
• Java does not support multiple inheritance.
• Multiple inheritance is implemented using the concept called
interface.
Abstract class:
• A class which is declared as abstract is known as an abstract class.
• It can have abstract and non-abstract methods.
• It needs to be extended and its method implemented.
• It cannot be instantiated(its object cannot be created).
• The abstract methods of an abstract class must be defined in its
subclass.
• The abstract class can have constructors.
Abstract class example:
abstract class shape
{
………
abstract void draw();
………
}
// Program to demonstrate abstract class.
abstract class Bank
{
abstract int getROI();
}
class SBI extends Bank
{
int getROI()
{
return 7;
}
}
class PNB extends Bank
{
int getROI()
{
return 8;
}
}
class TestBank
{
public static void main(String args[])
{
Bank b;
b=new SBI();
int x = [Link]();
[Link]("SBI ROI: "+x+" %");
b=new PNB();
int y = [Link]();
[Link]("PNB ROI: "+y+" %");
}
}
final:
• The keyword final can be used in three ways.
– final with variables
– final with methods
– final with classes
final with variables:
• final behaves like const of C++ i.e. the value of a final variable is
fixed and it cannot be modified.
• Single copy of memory is created for a class.
Example:
class Demo
{
final int a = 10;
…………
}
final with method:
• If you make any method as final, you cannot override it.
Example:
class Demo
{
final void display()
{
}
…………
}
final with class:
• If you make any class as final, you cannot extend it.
Example:
final class Demo
{
…………
…………
}
Polymorphism:
• Polymorphism in Java is a concept by which we can perform a
single action in 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.
• In Java polymorphism is mainly divided into two types:
– Compile-time Polymorphism
– Runtime Polymorphism
Compile-time Polymorphism:
• It is also known as static polymorphism.
• This type of polymorphism is achieved by method overloading and
operator overloading.
Note: Operator overloading is not supported by Java
Method Overloading:
• The methods that have the same name, but different
parameter lists and different definitions is called
method overloading.
Runtime Polymorphism:
• It is also known as Dynamic Method Dispatch.
• It is a process in which a function call to the overridden method is
resolved at Runtime.
• This type of polymorphism is achieved by Method Overriding.
Method Overriding:
• If subclass (child class) has the same method as declared in the
parent class, it is known as method overriding in Java.
• Method overriding is used to achieve runtime polymorphism.
• Rules for Java Method Overriding
– The method must have the same name as in the parent class
– The method must have the same parameter as in the parent
class.
Method Overriding:
• Which method is executed will be determined by the object that is
used to invoke it.
• If an object of a parent class is used to invoke the method, then
the method in the parent class will be executed, but if an object
of the subclass is used to invoke the method, then the method in
the child class will be executed.
// Program to demonstrate method overriding.
class Parent
{
void display()
{
[Link]("Parent class");
}
}
class Child extends Parent
{
void display()
{
[Link]("Child class");
}
}
class MethodOverriding
{
public static void main(String[] args)
{
Parent p = new Parent();
Child c = new Child();
[Link]();
[Link]();
}
}
Static and Dynamic Binding:
• Connecting a method call to the method body using an object is
known as binding.
• There are two types of binding
– Static Binding (also known as Early Binding).
– Dynamic Binding (also known as Late Binding).
Static Binding:
• Connecting/linking a method call to the method body using an
object during compile time is known as Static or Early binding.
// Program to demonstrate static binding.
class A
{
void displayA()
{
[Link]("Class A");
}
}
class B extends A
{
void displayB()
{
[Link]("Class B");
}
}
class StaticBinding
{
public static void main(String[] args)
{
B b = new B();
[Link]();
[Link]();
}
}
Dynamic Binding:
• Connecting/linking a method call to the method body using an
object during execution time is known as Dynamic or Late binding.
// Program to demonstrate Dynamic binding.
import [Link]; class DynamicBinding
{
abstract class Shape public static void main(String[] args)
{ {
abstract void display(); Scanner in = new Scanner([Link]);
} [Link]("1. Rectangle");
class Rectangle extends Shape
[Link]("2. Circle");
{ [Link]("Enter your choice");
void display() int ch = [Link]();
{
[Link]("Rectangle"); Shape s;
} if(ch==1)
} {
s = new Rectangle();
class Circle extends Shape [Link]();
{ }
void display() else if(ch==2)
{ {
[Link]("Circle"); s = new Circle();
} [Link]();
} }
else
[Link]("Invalid choice");
}
}
Interface:
• An interface is basically a kind of class.
• Like a class an interface also contains variables and methods.
• The difference is that an interface can contain only final variables
and abstract methods.
• This means that in an interface all the data members must be
constants and all the methods have only header without the body.
• The instructions for these methods will be written in the class
which implements the interface.
Defining an Interface:
interface InterfaceName
{
variables declaration;
Methods declaration;
}
Where
interface is the keyword.
InterfaceName is the name of the interface.
Defining an Interface:
interface Sample
{
float pi = 3.142f;
float compute(float x, float y);
}
Defining an Interface:
interface Sample
{
public static final float pi = 3.142f;
public abstract float compute(float x, float y);
}
by default, all the variables in an interface are
public static final.
by default, all the methods in an interface are
public abstract.
Implementing an Interface:
class Demo implements Sample
{
…………
}
Where
Demo is a class name,
Sample is an interface
// Program to demonstrate an interface.
class InterfaceDemo
interface Shape {
{ public static void main(String[] args)
void show(); {
} Shape s;
s = new Circle();
class Circle implements Shape [Link]();
{
public void show() s = new Rectangle();
{ [Link]() ;
[Link]("Circle"); }
} }
}
class Rectangle implements Shape
{
public void show()
{
[Link]("Rectangle");
}
}
Various forms of implementing interfaces :
Difference between class and interface:
class interface
The members of a class can be constants or The members of an interface are always declared
variables. as constant, i.e. Their values are final
The class definition can contain the code for each The methods in an interface are abstract in
of its methods. That is methods can be abstract or nature. These are methods are overridden by the
non-abstract. class that implements the interface.
It can be instantiated by declaring objects. It cannot be used to declare objects.
It can use various access specifiers like public, It can only use the public access specifier.
private, or protected.
Generic Programming:
• Java Generics allows us to create a single class, interface, and
method that can be used with different types of data (objects).
Java Generics Class:
• We can create a class that can be used with any type of data. Such
a class is known as Generics Class.
// Program to demonstrate Generic class.
class Sample <T>
{
T x;
public Sample(T a)
{
x = a;
}
public T getData()
{
return x;
}
}
class GenericClass
{
public static void main(String[] args)
{
Sample<Integer> intObj = new Sample<>(5);
[Link]("int object: " + [Link]());
Sample<String> stringObj = new Sample<>("Java Programming");
[Link]("string object: " + [Link]());
}
}
Java Generics Method:
• Similar to the generics class, we can also create a method that can
be used with any type of data. Such a class is known as Generics
Method.
// Program to demonstrate Generic Method.
class Demo
{
<T> void display(T x)
{
[Link]("Data Passed: " + x);
}
}
class GenericMethod
{
public static void main(String[] args)
{
Demo d = new Demo();
d.<String>display("Java Programming");
d.<Integer>display(25);
}
}
Static Members:
class
Variables Methods
Instance Static Instance Static
Variables Variables Methods Methods
Instance Variables and Instance Methods:
• Instance Variables:
– Instance variables in Java are non-static variables which are
declared in a class.
– Each instantiated object of the class has a separate copy or
instance of that variable.
• Instance Methods:
– Instance methods are methods which require an object of its
class to be created before it can be called/invoked.
– To invoke a instance method, we have to create an object of
the class in which the method is defined.
Static Variables:
• Static variables are also known as class variables.
• These variables are declared similarly as instance variables.
• The difference is that static variables are declared using the static
keyword within a class.
• We can only have one copy of a static variable per class,
irrespective of how many objects we create.
• Static variables are created at the start of program execution and
destroyed automatically when execution ends.
Static Methods:
• A static method is a method that belongs to a class rather than an
instance of a class.
• This means you can call a static method without creating an
object of the class.
• Static methods are sometimes called class methods.
// Program to demonstrate static variables and static methods.
class StaticDemo
{
int rollno;
String name;
static String college="GFGC Haliyal";
StaticDemo(int r, String n)
{
rollno=r;
name=n;
}
void display()
{
[Link](rollno+" : "+name+" : "+college);
}
static void change()
{
college="GFGC Alnavar";
}
public static void main(String[] args)
{
StaticDemo sd1 = new StaticDemo(10,"Ram");
StaticDemo sd2 = new StaticDemo(11,"Sham");
StaticDemo sd3 = new StaticDemo(12,"Ram");
[Link]();
[Link]();
[Link]();
[Link]();
}
}
// Program to demonstrate static method.
class MathOperation
{
static float product(float x, float y)
{
return x*y;
}
static float divide(float x, float y)
{
return x/y;
}
}
class MathApplication
{
public static void main(String[] args)
{
float a = [Link](4,5);
float b = [Link](a,2);
[Link]("b = "+b);
}
}
Difference between static and instance variables:
Static Variables Instance Variables
Single copy is shared by all the objects of that Separate copy for each object is created.
class.
Longer life. Created as soon as class is loaded Shorter life. Created only when an object is
into memory. Released at the end of the program. created . Released when object goes out of
scope.
Can be initialized at the point of declaration itself. Can be initialized using constructor.
Can be accessed from outside the class using Can be accessed from outside the class using an
class name or any object of that class. object only.
Object class:
• Object class in Java is the topmost class among all the classes in
Java.
• We can also say that the Object class in Java is the parent class for
all the classes. It means that all the classes in Java are derived
classes and their base class is the Object class.
• All the classes directly or indirectly inherit from the Object class
in Java.
• The Object class is present in [Link] package.
Object class:
Instanceof operator:
• The java instanceof operator is used to test whether the object is
of the specified type (class or subclass or interface).
• The instanceof in java is also known as type comparison operator
because it compares the instance/object with type. It returns
either true or false.
• If we apply the instanceof operator with any variable that has null
value, it returns false.
// Program to demonstrate instanceof operator.
class InstanceOfOperator1
{
public static void main(String[] args)
{
InstanceOfOperator1 s = new InstanceOfOperator1();
[Link](s instanceof InstanceOfOperator1);
}
}
// Program to demonstrate instanceof operator.
class InstanceOfOperator1
{
public static void main(String[] args)
{
InstanceOfOperator1 s = null;
[Link](s instanceof InstanceOfOperator1);
}
}
Type Casting:
• Type casting is a method or process that converts a data type into
another data type in both ways manually and automatically.
• The automatic conversion is done by the compiler and manual
conversion performed by the programmer.
Widening Type Casting
byte short int long float double
Narrowing Type Casting
Widening Type Casting:
• Converting a lower data type into a higher one is called widening
type casting.
• It is also known as implicit conversion or casting down.
• It is done automatically.
• It is safe because there is no chance to lose data.
// Program to demonstrate Widening Type Casting.
public class WideningTypeCasting
{
public static void main(String[] args)
{
int x = 7;
long y = x;
float z = y;
[Link]("Before conversion, int value "+x);
[Link]("After conversion, long value "+y);
[Link]("After conversion, float value "+z);
}
}
Narrowing Type Casting:
• Converting a higher data type into a lower one is called narrowing
type casting.
• It is also known as explicit conversion or casting up.
• It is done manually by the programmer.
• If we do not perform casting then the compiler reports a
compile-time error.
// Program to demonstrate Narrowing Type Casting.
public class NarrowingTypeCasting
{
public static void main(String args[])
{
double d = 166.66;
long l = (long)d;
int i = (int)l;
[Link]("Before conversion: "+d);
[Link]("After conversion into long type: "+l);
[Link]("After conversion into int type: "+i);
}
}
Casting Objects:
• A process of converting one data type(primitive) to
another(primitive) is known as Typecasting.
• A process of converting one object type to another object type is
known as object type casting or casting object.
• Types of Casting Objects:
– Upcasting
– Downcasting
Upcasting:
• Upcasting is a object type casting in which a child object (derived
class object) is type casted to a parent class object (base class
object).
• Upcasting is also known as Generalization and Widening.
• Upcasting can be done implicitly or explicitly.
// Program to demonstrate upcasting.
class Parent
{
void display()
{
[Link]("parent class");
}
}
class Child extends Parent
{
void display()
{
[Link]("child class");
}
}
class UpcastingExample
{
public static void main(String args[])
{
Parent obj1 = new Child(); //Implicit type casting
Parent obj2 = (Parent) new Child(); //Explicit type casting
[Link]();
[Link]();
}
}
Downcasting:
• Downcasting is a object type casting in which a parent object
(base class object) is type casted to a child class object (derived
class object).
• Downcasting is also known as Narrowing.
• Upcasting can be done explicitly.
// Program to demonstrate Downcasting.
class Parent
{
void display()
{
[Link]("parent class");
}
}
class Child extends Parent
{
void display()
{
[Link]("child class");
}
}
class DowncastingExample
{
public static void main(String args[])
{
Parent obj1 = new Child();
Child obj2 = (Child)obj1; //Explicit type casting
[Link]();
[Link]();
}
}
Visibility Modifiers:
• The variables and methods of a class are visible everywhere in the
program.
• However, it may be necessary is some situations to restrict the
access to certain variables and methods from outside the class.
• It can be achieved in java by applying visibility modifiers to the
instance variables and methods.
• The visibility modifiers are also known as access modifiers.
Visibility Modifiers:
• The types of visibility modifiers are:
– default - No keyword is used
– public
– private
– protected
default:
• The methods or data members declared as default (No keyword is
used) are accessible only within the class and the current
package.
public:
• The methods or data members declared as public are accessible
throughout the program.
• It can be accessed from within the class, outside the class, within
the package and outside the package.
private:
• The methods or data members declared as private are accessible
only within the class.
• These cannot be accessed outside the class.
protected:
• The methods or data members declared as protected are
accessible within the same package or subclasses in different
packages.
Package:
• 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
– user-defined package.
• There are many built-in packages such as java, lang, awt, javax,
swing, net, io, util, sql etc.
Advantages of Package:
• Java package is used to categorize the classes and interfaces so
that they can be easily maintained.
• It provides access protection.
• It removes naming collision.
References:
• Programming with Java, E. Balagurusamy, 4th Edition, McGraw Hill Publications.
• [Link]
• [Link]
• [Link]
• [Link]
• [Link]
• [Link]
• [Link]
• [Link]
• [Link]
• [Link]
• [Link]
• [Link]
•