4 OOP Concepts
4 OOP Concepts
Encapsulation
Encapsulation is a programming mechanism that binds together code and the data it manipulates
and keeps both safe from outside interference and misuse. In an object-oriented language, code
and data can be bound together in such a way that a self-contained Black Box is created. Within
the box are all necessary data and code. When code and data are linked together an object is
created. In other words, an object supports encapsulation.
Within an object, code, data or both may be private to that or public. Private code or data is
accessible by another part of the object. That is, private code or data cannot be accessed by piece
of the program that exists outside the object. When code and data is public, other parts of program
1
can access it even through it is defined within an object. Typically, the public parts of an object
are used to provide a controlled interface to the private elements of the object.
Java basic unit of encapsulation is the class. A class defines the form of an object. The code and
data constitute a class are members of the class. The data defined by the class are referred to as
member variables or instance variables. The code that operates on the data is referred to as
member methods or methods.
2
The “extends” keyword is used to inherit a class and incorporate the definition of one class into
another. A subclass (inherited class) is defined as follows.
Class sub classname extends super classname
{
Declaration of variables;
Declaration of methods;
}
The “extends” keyword indicates that the properties of the superclass name are extended to the
subclass name. The subclass contains its own variables and methods as well those of the
superclass. This kind of situation occurs when we want to add some more properties to an existing
class without actually modifying the superclass members.
Example:
class Room{
int length;
int breadth;
Room(int a,int b){
length = a;
breadth = b;
}
int area(){
return(length * breadth);
}}
class Bed extends Room{
int height;
Bed(int a,int b,int c);{
super(a,b);
height = c;
}
int vol(){
return( length * breadth * height);
}}
3
class Test
{
public static void main(String args[])
{
Bed room1 = new Bed(10,20,30);
int area1 = room1.area();
int vol1 = room1.vol();
System.out.println(“Area = “+area1);
System.out.println(“Volume = “ +vol1);
}
}
Output:
Area =200
Volume =6000
The above program finds a class Room and extends it to another class Bed. Here the class Bed
defines its own data members and methods. The subclass Bed includes three instance variables.
They are length, breadth and height and two methods area and vol.
The constructor in the derived class uses the super keyword to pass values that are required by the
base constructor the statement.
Bed room1 = new Bed(10,20,30);
First the “Bed” constructor, which in turn calls the Room constructor by using the keyword.
Finally, the object room1 of the subclass Bed calls the method “area()” defined superclass as well
as the method “ vol() ”defined in the subclass itself.
3. Hierarchical inheritance
4. Multilevel inheritance
4
1. In single inheritance there is only on base class and only one derived class
2. In multiple inheritance there is only one derived class that is derived from several base
classes i.e. there are several base classes but only one derived class.
X Y Many super
classes
3. In Hierarchical inheritance there is only one base class but many derived classes. These
derived classes are derived only from one base class.
One super class
X
5
Method Overloading:
Method overloading is a concept, which is supported by Java. In method overloading two or more
methods have the same name but different parameters. Method overloading is used when objects
are required to perform different parameters. When a method by an object is called, Java matches
the method name and then the number and data types of parameters to decide which one of the
overloaded methods to execute.
Overloaded method can be created by providing several different method definitions in the class,
with all the same name, different parameter lists. The difference may either be in the number or
type of arguments. Thus, each parameter list should be unique.
Relationship between methods available in the same class. It does not block inheritance from the
superclass. Separate method sharing (overload) the same name different method signatures may
have different return types, may have different declared exceptions.
Example:
class Overloadingdemo{
void test(){
System.out.println("No parameters");
}
void test(int x){
System.out.println("x:"+x);
}
void test(int x,int y) {
System.out.println("x and y are:"+x+" "+y);
}
double test (double x){
System.out.println("double x:"+x);
return x*x;
}
public static void main(String args[]){
Overloadingdemo ord=new Overloadingdemo();
double result;
ord.test();
ord.test(100);
ord.test(100,200);
result=ord.test(123.2);
System.out.println("Result of ord.test(123.2):"+result);
}
}
6
Method Overriding:
Overriding is a concept where instead of inheriting a method from its super class, a sub class
override the method by providing its own definition for it. Overriding is useful on same method
but have different parameters when that method is called method overriding.
That means we should override the method defined in the superclass. This is possible by defining
a method in the subclass that has the same name, same argument s and same return types as the
method in the superclass. When that method is called, the method defined in the sub class is
invoked and executed instead of the super class.
Relationship between a superclass method and a subclass method. Blocks inheritance from the
super class. Sub class method replaces(overrides) the superclass method. Same method signatures.
must have matching return types. Must have compatible declared exceptions.
When a method in a subclass has the same method signature as that of the superclass, then the
method in the sub class is said to “override” the method in the superclass. When an overridden
method exists in the subclass, the subclass object always refers its own. That is subclass overridden
method hides (or blocks) that of the superclass method.
Example:
class X{
int i,j;
X(int a,int b){
i=a;
j=b;
}
void show(){
System.out.println("iandj are:"+i+ " "+j);
}
}
class Y extends X{
int k;
Y(int a,int b,int c)
{
super(a,b);
k=c;
}
void show(){
System.out.println("k:"+k);
}
}
7
class Overridedemo{
public static void main(String args[]){
Y subob=new Y(8,9,10);
subob.show();
}
}
Output:
k = 10
When show() is invoked on an object of type y, the version of show() defined in y is used. That
is version show() inside y overrides the version declared in x.
Polymorphism
Polymorphism is the quality that allows one interface to access a general class of actions. The
concept of polymorphism is often expressed by “ one interface, multiple methods”. This means
that is possible to design a generic interface to a group of related activities. polymorphism reduce
complexity by allowing the same interface to be used to specify a general class of action. It is the
compiler`s job to select the specific action (i.e method) as it applies to each situation.
These are two types 1. Static Polymorphism
2. Dynamic polymorphism or Dynamic Method Dispatch
1. Static Polymorphism:
In Static polymorphism, which method is to be called is decided at compile-time. Method
overloading is an example of Static polymorphism. Method overloading is a concept which we use
the same method name many times in the same class, but with different parameters depending on
the parameters we pass, it is decided at compile-time only, which is method is to be called. The
same method name with the parameters is an error and it is a case of duplication of methods which
Java does not permit.
Relationship between methods available in the same class. Separate method share (overload) the
same name. different method signatures, may have different return types, may have different
declared exceptions. Does not block inheritance from the super class.
Example:
class Staticpolydemo{
public void display(int x){
System.out.println("Area of the square:" +x*x);
}
public void display(int x,int y){
8
public static void main(String args[])
{
Staticpolydemo spd=new Staticpolydemo();
spd.display(20);
spd.display(20,40);
}
}
Output :
In the above program, display() method is overloaded(two times). Compiler is able to decide
which method is to be called depending on the parameters passed their number and the sequence
of data types.
2. Dynamic polymorphism or Dynamic Method Dispatch:
Dynamic Polymorphism also called as Dynamic method dispatch is the mechanism by which a
call to an overridden function is resolved at run-time. Dynamic method dispatch is implements
run-time polymorphism.
Relationship between a superclass method and a subclass method. Blocks inheritance from the
superclass. Subclass method replaces(overrides) the super class method. Same method signature.
Must have matching return types. must have compatible declared exceptions.
In this determination is made at run time. Different types of objects are referred to different
versions of an overridden method. Superclass contains a method that is overridden by a subclass,
when different types of objects are referred to through a superclass reference variable, different
versions of the method are executed.
Example:
class Test{
public void show(){
System.out.println("From superclass:");
}
}
class Dynamicpolydemo extends Test{
public void show(){
System.out.println("From subclass:");
}
9
public static void main(String args[]){
Dynamicpolydemo dpd=new Dynamicpolydemo();
dpd.show();
Test t=new Test();
t.show();
}
}
10
class B extends A {
void callme() {
System.out.println("B's implementation of callme.");
}
}
class AbstractDemo {
public static void main(String args[]) {
B b = new B();
b.callme();
b.callmetoo();
}
}
Interfaces:
Interfaces are syntactically similar to classes, but they lack instance variables and their methods
are declared without any body. In practice, this means that you can define interfaces which don’t
make assumptions about how they are implemented. Once it is defined, any number of classes
can implement an interface. Also, one class can implement any number of interfaces. To
implement an interface, a class must create the complete set of methods defined by the interface.
However, each class is free to determine the details of its own implementation. By providing the
interface keyword, Java allows you to fully utilize the “one interface, multiple methods” aspect
of polymorphism.
Interfaces are designed to support dynamic method resolution at run time. Normally, in order for
a method to be called from one class to another, both classes need to be present at compile time so
the Java compiler can check to ensure that the method signatures are compatible. This requirement
by itself makes for a static and non-extensible classing environment. Inevitably in a system like
this, functionality gets pushed up higher and higher in the class hierarchy so that the mechanisms
will be available to more and more subclasses. Interfaces are designed to avoid this problem.
They disconnect the definition of a method or set of methods from the inheritance hierarchy. Since
interfaces are in a different hierarchy from classes, it is possible for classes that are unrelated in
terms of the class hierarchy to implement the same interface. This is where the real power of
interfaces is realized. Java does not support multiple interfaces. either through concrete classes or
abstract classes Just to overcome these introducing interfaces. i.e. java supports multiple
inheritance through interface. Interface is a special type of abstract class where all methods should
be abstract. To inform the compiler that we are inheriting multiple interfaces replace “extends”
with implements keyword. It must be remembered that extends keyword used with concrete classes
and abstract classes. Also it must be meted that after extends there must be only one class of either
concrete or abstract. But after implements there can be any number of interfaces.
11
Implementing interfaces:
Once an “interface” has been defined, one or more classes can implement that interface. To
implement an interface, the “implements” keyword is included in the class definition, and then the
methods defined by the interface are created. It is either “public” or not used. If a class implements
more than one interface, If a class implements two interfaces that declare the same method will be
used by clients of either interface. The method that an interface must be declared ”public” Also,
the type signature of the implementing must match exactly the type signature specified in the
interface.
Example:
Interface Figured{
public final static float pi = 3.14F; //this variable is not used in Rect class
public abstract float compute(float x, float y)
}
Class Rect implements Figured //Interface implemented
{
public float compute (float x, float y){
return(x*y);
}
}
Class InterfaceTest{
public static void main (String args[]){
Rect rect = new Rect();
System.out.println(“Area of Rectangle = “+rect.compute(10,30));
}
}
Output:
Area of Rectangle = 300
Any number of classes can implement an interface. However, to implement the methods, we
need to refer to the class objects as types of the interface rather than types of their respective
classes. If a class that implements an interface does not implement all the methods of the
interface, then the class becomes an “ abstract” class and cannot be instantiated.
12
Implementation Extension
Interface Class Class
Implementation Extension
Class Interface Interface
Extending Interfaces:
Yes, the interfaces can be extended. An interface can be sub interfaced by other interfaces. The
new sub interfaces will inherit All the members of the sub interface in the manner similar to
subclasses. This is achieved using the keyword extends as shown below:
Interface name2 extends name1 //name1 is an interface
{
// variables and methods of name2
}
For example, we can put all constants in one interface and the methods in the other. this will
enable us to see the constants in classes where the methods are not required.
Interface ItemConstants{
int itemcode = 1001;
String itemname = “Fan”;
}
13
int itemcode = 1001;
String itemname = “Fan”;
}
interface ItemMethods
{
Void display();
}
Interface Item extends ItemConstants,ItemMethods
{
………………………………
……………………………..
}
Difference between Abstract class and interfaces:
Abstract Classes Interfaces
1.Java does not support multiple interface. 1.Java supports multiple interface.
2. Can contain concrete methods. 2. Only abstract methods.
3. Must use extends keyword. 3. Must use implements keyword.
4.The keywords public, abstract method. 4. If not mentioned it takes default.
5. The abstract method can be public, protected, 5.The abstract methods must be public only
default modifier and can not be private.
6.The variables can be private. 6. The variables must be public, static, final and if
omitted they are taken by default.
7.Can have constructors and main methods. 7. Cannot have constructors and main methods.
8.Single inheritance. 8. Multiple inheritance.
9.Extends can be only once. 9. Extends can be many number of times.
10.Classes implements interfaces 10. Interfaces extends interfaces.
14