0% found this document useful (0 votes)
40 views

4 OOP Concepts

The document discusses basic object-oriented programming concepts such as classes, objects, encapsulation, inheritance, polymorphism, and abstraction. It defines objects as instances of classes that have properties and methods. Encapsulation binds code and data together into self-contained objects that control access to their internal representation. Inheritance allows classes to inherit properties from parent classes, supporting code reuse. Polymorphism allows methods to take different forms based on object type.

Uploaded by

Abdi saba
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)
40 views

4 OOP Concepts

The document discusses basic object-oriented programming concepts such as classes, objects, encapsulation, inheritance, polymorphism, and abstraction. It defines objects as instances of classes that have properties and methods. Encapsulation binds code and data together into self-contained objects that control access to their internal representation. Inheritance allows classes to inherit properties from parent classes, supporting code reuse. Polymorphism allows methods to take different forms based on object type.

Uploaded by

Abdi saba
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/ 14

OOP Concepts

Basic Concepts of Object-Oriented Programming:


1. High level programming languages mentioned earlier fall in to two major groups.
2. First group consists of the older languages (COBAL, FORTRAN, BASIC, C and PASCAL)
uses called a procedural approach.
3. In this procedural approach leads to development of the object-oriented approach and to
several new languages (Smalltalk, C++, PYTHON, Eiffel, CLOS and Java).
4. These two approaches are used in programming text. But object-oriented approach is widely
considered the superior of the two It is used for advanced text and several other approach to
programming.
5. It is used for hundreds of thousands of lines of code and executing the programming.

6. Introduce fundamental object-oriented programming concepts such as class, encapsulation,


polymorphism, Inheritance and abstraction.
Basic object-oriented concepts:
Object: Provides a particular basis for computer applications.
Class: Describes a set of related objects.
Property: A characteristics of an object – also called attribute.
Method: An action performed by an object.
Data abstraction: Identifying the properties related to a particular application.
Data Encapsulation: Data Encapsulation means wrapping of data and functions into a single unit
(i.e. class).
Dynamic Binding: Binding refers to the linking of a procedure call to the code to be executed in
response to the call.

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.

Inheritance, Method overloading and overriding


Inheritance:
Inheritance is the process by which one object can acquire the properties of another object. Or
Objects of one class acquire the properties of another class. We can add additional features to an
existing class without modifying it. This is possible by deriving a new class from the existing one.
This is important because it supports the concept of hierarchical classification. If you think about
it, most knowledge is made manageable by hierarchical (i.e top-down) classifications. Without the
use of hierarchies, each object would have to explicitly define all of its characteristics. Using
inheritance, an object need only define those qualities that make it unique within its class. It can
inherit it general attributes from its parent. Thus, it is the inheritance mechanism that makes it
possible for one object to be a specific instance of a more general case. Inheritance provides the
idea of reusability.
What is meant by Inheritance? How is it implemented in Java?
Inheritance is a OOPs concept. Inheritance is a mechanism by which a sub class is derived from a
base class. Inheritance is a subclass uses method definitions and variables from a superclass just
as if they belonged to the subclass itself.
In general, any instance method or instance variable not defined in a sub class from its super class.
A subclass can use the inherited methods and variables. Inheritance is a powerful mechanism for
reusing the code. We can start existing classes and write code to provide the extra functionality
required.
Inheritance provides a chain in which a class inherits not only from its immediate superclass. But
also, from any superclass upwards to the Object class. All java classes ultimately inherit from class
object. Object is super most class of all classes and beyond which there is no superclass.
For Example, The Button class in the java.awt package is defined as a subclass of the powerful,
generic component class. The java language uses the extends keyword to declare this subclass
relationship.
public class Button extends Component
{
//……… class definition code
}

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.

Different types of Inheritances:


There are four types of inheritances, they are
1. Single inheritance
2. Multiple inheritance

3. Hierarchical inheritance
4. Multilevel inheritance

4
1. In single inheritance there is only on base class and only one derived class

X One super class

One sub class


Y

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

One sub class


Z

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

Y W Many sub classes


Z

4. In multilevel inheritance the class is derived from the derived class.


One super class
X

One sub class


Y

One super class and a chain continues


Z

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){

System.out.println("Area of the rectangle:" +x*y);


}

8
public static void main(String args[])
{
Staticpolydemo spd=new Staticpolydemo();
spd.display(20);
spd.display(20,40);
}

}
Output :

Area of the square : 400


Area of the rectangle : 800

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();
}
}

Abstract classes and Interfaces


There are situations in which you will want to define a superclass that declares the structure of a
given abstraction without providing a complete implementation of every method. That is,
sometimes you will want to create a superclass that only defines a generalized form that will be
shared by all of its subclasses, leaving it to each subclass to fill in the details. Such a class
determines the nature of the methods that the subclasses must implement. One way this situation
can occur is when a superclass is unable to create a meaningful implementation for a method.
Java’s solution to this problem is the abstract method. You can require that certain methods be
overridden by subclasses by specifying the abstract type modifier. These methods are sometimes
referred to as subclasser responsibility because they have no implementation specified in the
superclass. Thus, a subclass must override them—it cannot simply use the version defined in the
superclass. To declare an abstract method, use this general form:
abstract type name(parameter-list);
As you can see, no method body is present. Any class that contains one or more abstract methods
must also be declared abstract. To declare a class abstract, you simply use the abstract keyword
in front of the class keyword at the beginning of the class declaration. There can be no objects of
an abstract class. That is, an abstract class cannot be directly instantiated with the new operator.
Such objects would be useless, because an abstract class is not fully defined. Also, you cannot
declare abstract constructors, or abstract static methods. Any subclass of an abstract class must
either implement all of the abstract methods in the superclass, or be itself declared abstract.
Here is a simple example of a class with an abstract method, followed by a class which implements
that method:
Example :
abstract class A {
abstract void callme();
// concrete methods are still allowed in abstract classes
void callmetoo() {
System.out.println("This is a concrete method.");
}
}

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

Various forms of interface implementation

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”;
}

interface Item extends ItemConstants{


void display(); //by default all methods are public and abstract in an interface
}
The interface Item would inherit both the constants itemcode and itemname into it. We can also
combine several interfaces together into a single interface. Following declarations are valid.
interface ItemConstants
{

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

You might also like