3. Object Oriented Programming MODIFIED bonga
3. Object Oriented Programming MODIFIED bonga
▪ Programming languages are the heart of computer science. They are the tools used to
communicate not only with computers but also with people.
▪ The challenge of designing language features that support clear expressions, the
puzzle of fitting together, the different features to make a useful language, the
challenge of appropriately using those features for the clear expression of algorithms
all these make up part of the excitement of the study of programming languages.
Cont…
▪ PL is designed to communicate ideas about algorithms between people
and computers.
▪ There are 4 computational models that describe most programming
languages paradigm.
✓Declarative Ibsa
Example
• ATM machine: Here we can withdraw money using shown features but internal
details or implementation details are hidden which are not really required to
the user.
• TV remote: Person who using TV remote can able to operate. But don’t know
how it works internally.
Abstraction vs Encapsulation?
• In higher end both abstraction and Encapsulation looks similar.
• But purpose of these two concepts is totally different.
• Abstraction hides the things at design level but encapsulation hide
things at implementation level.
• Abstraction can be achieved using interface and abstract class while
Encapsulation can be achieved by using access modifiers
e.g. public, private and protected.
• Abstraction focus on What should be done and Encapsulation focus
on How it should be done.
Inheritance
• Inheritance represents the IS-A relationship between the objects which is also
known as a parent-child relationship.
• The process by which one class acquires the properties (data members) and
functionalities (methods) of another class is called inheritance.
• Inheritance which allows a class to inherit behavior and data from other class. In
other word, inheritance is a mechanism where in a new class is derived from an
existing class.
• The code that is already present in base class need not be rewritten in the child
class.
• The inheritance mechanism is very useful in code reuse.
• A class which is inherited is called a Base Class / Parent class / Super class. The
classes which are inheriting Base classes are called Child class / Sub class.
• In Java, A subclass can have only one Parent class, whereas a Parent class may
have one or more Child classes. Because Java doesn’t support multiple
inheritance.
• The meaning of “extends” is to increase the functionality.
Types of Inheritance
❑ Single inheritance
❑ Multiple inheritance
❑ Hierarchical inheritance
❑ Multilevel inheritance
❑ Hybrid inheritance
Cont…
What is the primary benefit of inheritance?
• Code reusability and reduces duplicate code.
• It makes code more flexible.
• It takes less time for application development and execution.
• Memory consumption is less and performance will be improved.
• Since less number of code, storage cost will be reduced.
Polymorphism
• Polymorphism
✓makes to perform a single action in different ways.
✓Single task can be done in different way.
✓is the ability of an object to take on many forms.
int x = 5;
• The value of any variable whose data type is a reference type, such
as rect, is a reference (a pointer in other terminology) to the actual value
or set of values represented by the variable.
You will read more about Object and Class Example: Initialization
through a constructor
Member Variables
• A member variable has a name (or identifier) and a type; and holds
a value of that particular type.
• Variable Naming Convention
• A variable name shall be a noun or a noun phrase made up of several words.
• The first word is in lowercase and the rest of the words are initial-capitalized
(camel-case), e.g., fontSize, roomNumber, xMax, yMin and xTopLeft.
• The formal syntax for variable definition in Java is:
• [AccessControlModifier] type variableName [= initialValue];
• [AccessControlModifier] type variableName-1 [= initialValue-1] [, type
variableName-2 [= initialValue-2]] ... ;
• For example
• private double radius;
• public int length = 1, width = 1;
Member Methods
• A method
1. receives arguments from the caller,
2. performs the operations defined in the method body, and
3. returns a piece of result (or void) to the caller.
• The syntax for method declaration in Java is as follows:
[AccessControlModifier] returnType methodName ([parameterList]) {
// method body or implementation
......
}
• For examples:
// Return the area of this Circle instance
public double getArea() {
return radius * radius * PI;
}
Cont….
❖ Method Naming Convention
• A method name shall be a verb, or a verb phrase made up of several words.
• The first word is in lowercase and the rest of the words are initial-capitalized (camel-
case).
• For example, getArea(), setRadius(), getParameterValues(), hasNext().
❖ Variable name vs. Method name vs. Class name
• A variable name is a noun, denoting an attribute; while a method name is a verb,
denoting an action.
• They have the same naming convention (the first word in lowercase and the rest are
initial-capitalized). Nevertheless, you can easily distinguish them from the context.
Methods take arguments in parentheses (possibly zero arguments with empty
parentheses), but variables do not.
• In this writing, methods are denoted with a pair of parentheses,
e.g., println(), getArea() for clarity.
• On the other hand, class name is a noun beginning with uppercase.
Constructors
• A constructor initializes an object when it is created.
• It has the same name as its class and is syntactically similar to a
method. However, constructors have no explicit return type.
• Typically, you will use a constructor to give initial values to the
instance variables defined by the class, or to perform any other
start-up procedures required to create a fully formed object.
• All classes have constructors, whether you define one or not,
because Java automatically provides a default constructor that
initializes all member variables to zero. However, once you
define your own constructor, the default constructor is no
longer used.
Cont…
• Syntax
Class Student {
Student(){
………
}
}
• Two types of constructors
• No argument Constructors
• Parameterized Constructors
Cont…
No argument Constructors
As the name specifies the no argument constructors of Java does not
accept any parameters instead, using these constructors the instance
variables of a method will be initialized with fixed values for all objects.
private final int SIZE; // error: variable SIZE might not have been initialized
• Constant Naming Convention: A constant name is a noun, or a noun phrase made up of
several words. All words are in uppercase separated by underscores '_', for
examples, PI, MAX_INTEGER and MIN_VALUE.
• Advanced Notes:
• A final primitive variable cannot be re-assigned a new value.
• A final instance cannot be re-assigned a new object.
• A final class cannot be sub-classed (or extended).
• A final method cannot be overridden.
Method toString()
read by yourself
Chapter Three
Inheritance and Polymorphism
Inheritance
• Inheritance in Java is a mechanism in which one object acquires all the
properties and behaviors of a parent object. It is an important part
of OOPs. The idea behind inheritance in Java is that you can create
new classes that are built upon existing classes.
• When you inherit from an existing class, you can reuse methods and
fields of the parent class.
• Moreover, you can add new methods and fields in your current class
also.
• Inheritance represents the IS-A relationship which is also known as
a parent-child relationship.
Inheritance
❖Why use inheritance in java
• For Method Overriding(so runtime polymorphism can be achieved).
• For Code Reusability.
❖ Terms used in Inheritance
• Class: A class is a group of objects which have common properties. It is a template or
blueprint from which objects are created.
• Sub Class/Child Class: Subclass is a class which inherits the other class. It is also
called a derived class, extended class, or child class.
• Super Class/Parent Class: Superclass is the class from where a subclass inherits the
features. It is also called a base class or a parent class.
• Reusability: As the name specifies, reusability is a mechanism which facilitates you to
reuse the fields and methods of the existing class when you create a new class. You
can use the same fields and methods already defined in the previous class.
Inheritance
• The syntax of Java Inheritance
class Subclass-name extends Superclass-name
{
//methods and fields
}
• The extends keyword indicates that you are making a new class that
derives from an existing class. The meaning of "extends" is to
increase the functionality.
Inheritance
Inheritance
Output
Boy is eating
Method Overriding
❖ Advantage of method overriding
• The main advantage of method overriding is that the class can
give its own specific implementation to a inherited
method without even modifying the parent class code.
• This is helpful when a class has several child classes, so if a
child class needs to use the parent class method, it can use it
and the other classes that want to have different
implementation can use overriding feature to make changes
without touching the parent class code.
Super keyword in java
• Note: The class which is extending abstract class must override all
the abstract methods.
Example ( Abstract class and method)
abstract class MyClass{
public void disp(){
System.out.println("Concrete method of parent class"); }
abstract public void disp2();
}
class Demo extends MyClass{ /* Must Override this method
while extending * MyClas */
public void disp2() {
System.out.println("overriding abstract method");
}
public static void main(String args[]){
Demo obj = new Demo();
obj.disp2(); }
}
Output: overriding abstract method
Interface in java
• In the last tutorial we discussed abstract class which is used for achieving
partial abstraction. Unlike abstract class an interface is used for full
abstraction.
• Abstraction is a process where you show only “relevant” data and “hide”
unnecessary details of an object from the user(See: Abstraction). In this
topic, we will cover what is an interface in java, why we use it and what
are rules that we must follow while using interfaces in Java Programming.
What is an interface in Java?
• Interface looks like a class but it is not a class.
• An interface can have methods and variables just like the class but the
methods declared in interface are by default abstract (only method
signature, no body, see: Java abstract method). Also, the variables
declared in an interface are public, static & final by default.
What is the use of interface in Java?
• As mentioned above they are used for full abstraction.
• Since methods in interfaces do not have body, they have to be
implemented by the class before you can access them.
• The class that implements interface must implement all the methods of
that interface. Also, java programming language does not allow you to
extend more than one class, However you can implement more than one
interfaces in your class.
Syntax:
Interfaces are declared by specifying a keyword “interface”.
Example
interface MyInterface {
/* All the methods are public
abstract by default * As you see they
have no body */
public void method1();
public void method2();
}
Example ( Interface in Java)
• This is how a class implements an interface. It has to provide the body
of all the methods that are declared in interface or in other words you
can say that class has to implement all the methods of interface.
• Class implements interface but an interface extends another interface
interface MyInterface {
/* compiler will treat them as: * public abstract void method1();
* public abstract void method2(); */
public void method1();
public void method2(); }
class Demo implements MyInterface {
/* This class must have to implement both the abstract methods * else
you will get compilation error */
public void method1() { System.out.println("implementation of method1"); }
public void method2() { System.out.println("implementation of method2"); }
public static void main(String arg[]) {
MyInterface obj = new Demo();
obj.method1(); } }
Interface and Inheritance
• See the below example where we have two interfaces Inf1 and Inf2.
}catch(Exception_class_Name ref){}
Example:TryCatchExample1
public class TryCatchExample1 {
public static void main(String[] args) {
int data=50/0; //may throw exception
System.out.println("rest of the code");
}
}
Solution by exception handling
• Let's see the solution of the
previous problem by a java try-
catch block.
• TryCatchExample2
Output: 25
Read or refer This link to know more about Exception
handling in java
• https://www.javatpoint.com/try-catch-block