Learning Objectives
After completing this session, you will be able to:
Describe OOP as a programming methodology
Explain classes and objects Object Oriented Programming OOP maps your problem in the real world.
OOP defines “things” (objects), which can either do something or have something done to them.
OOP creates a “type” (class) for these objects so that you do not have to redo all the work in defining the properties and behavior of an object.
Examples of class:
Classroom
Car
Person
Procedural Versus OOP
“Nouns” refer to data and “Verbs” refer to operations.
Procedural Languages:
C or Pascal and so on
Verb-oriented
No formal noun-verb structure (not enforced by language or compiler)
OOP languages: Operations (verbs) are performed by or on “Actors” (objects), which have names and store data (nouns)
Objects
An object is a unique programming entity that has attributes to describe it (like adjectives in grammar) and methods to retrieve or set attribute values (like verbs in grammar).
Part of a program which:
Models some real or conceptual object
Has behavioural responsibilities (behaviors)
Has informational responsibilities (attributes)
Behaviors (methods):
Things an object can “do”
Like procedures and functions in other languages
Attributes (fields):
Information an object “knows” (has-a)
Like data and variables in other languages (records)
Class Exists once:
The class is the template for the object Defines the attributes and behavior of the objects
Every object must belong to a class: The creation (construction) of an object is called instantiation.
The created object is often called an instance (or an instance of class X) Example:
Person is a class
EdmundHillary is an instance of class Person Try It Out
Problem Statement:
What is the difference between a class and an object?
Answer:
A class is not an object. But it is used to construct objects.
A class is a blueprint for an object. It tells the virtual machine how to make an object of that
particular type. Each object made from the class can have its own values for the instance variables of that class.
Class Book { String id;
String title;
String author;
void getChaptersList() {
System.out.println(“Getting the chapters list”);
}
public static void main(String[] args) { Book book1 = new Book();
book1.getChaptersList();
Book book2 = new Book();
book2.getChaptersList();
} }
Refer File Name: Book.java to obtain soft copy of the program code
How It Works:
In the example provided, you have used the Book class to make different books, and each book has its own id, title, and author.
Tips and Tricks
Please tell whether the following file could be compiled:
Class DiscDeck {
boolean canRecord = false;
void playDisc() {
System.out.println(“disc playing”);
}
void recordDisc() {
System.out.println(“disc recording”);
}
public static void main(String[] args) { dd.canRecord = true;
Solution: The preceding file will result in compilation error since object is not created for the DiscDeck class. This error will be fixed by adding DiskDeck dd = new DiscDeck(); statement in the main method.
Summary
Object-oriented programming lets you to extend a program without having to touch the working code that is tested earlier.
A class describes how to make an object of that class type. A class is like a blueprint.
An object knows things and does things.
The things an object knows about itself are called instance variables. They represent the state of an object.
The things an object does are called methods. They represent the behavior of an object.
Test Your Understanding Find out who am I from the following:
1. I am compiled from a .java file ____
2. I behave like a template or blueprint ____
3. I have behaviors ____
4. I declare methods ____
5. I represent ‘state’ ____
6. I am used to create object instances ____
7. I am located in objects ____, ____
Session 03: Introduction to OOPS
Learning Objectives
After completing this session, you will be able to:
Describe abstraction, encapsulation, and inheritance Abstraction
One of the chief advantages of object oriented programming is the idea that programmers can essentially focus on the “big picture” and ignore specific details regarding the inner-workings of an object. This concept is called abstraction.
Encapsulation
Abstraction in OOP is closely related to a concept called encapsulation.
The Object Orientation has two major promises/benefits. They are: flexibility and maintainability.
You have to write your classes and code in a way that supports flexibility and maintainability.
The ability to make changes in your implementation code without breaking the code of others who use your code is a key benefit of encapsulation.
If you want maintainability, flexibility and extensibility your design must include encapsulation.
The following are some of the ways to include encapsulation:
o Keep instance variables protected (with an access modifier, often private).
o Make public accessor methods, and force calling code to use those methods rather than directly accessing the instance variable.
o For the methods, use the JavaBeans naming convention of set<someProperty> and get<someProperty>
Encapsulation is the mechanism that binds together the code and the data it manipulates, and keeps both safe from outside interference and misuse.
public variables and methods
private variables and methods
public variables are not recommended
A Class
Encapsulation: Example Bank machine
Hidden data Account balance Personal information Interface
Deposit, Withdraw, Transfer Display account information
Class Hierarchy
Classes are arranged in a tree hierarchy:
A class’ “superclass” is the class preceding it in the hierarchy
Classes following it are “subclasses”
Classes have all the properties of their superclasses:
General: Towards the root (top)
More specific: Towards the leaves (down)
NB: In Computer Science trees grow upside down!
Class Hierarchy: Example
Object
Animal
Bird
Duck
...
...
...
...
Inheritance
One of the main tenets of OOP is inheritance.
The process by which a class inherits the properties of its superclasses is called inheritance:
Methods
Instance variables
A child class inherits its properties and attributes from its parents.
Inheritance is the process by which one object acquires the properties of another object. By use of inheritance, an object needs only to define all of its characteristics that make it unique within its class; it can inherit its general attributes from its parent.
The inheriting class contains all the attributes and behaviors of its parent class. Moreover the inheriting class can define its own attributes and behaviors.
The inheriting class can override the definition of existing methods by providing its own implementation.
The code of the inheriting class consists only the changes and additions to the base class.
Need of inheritance
Inheritance is required for the following reasons:
Modular coding, which means less code and easier to get an idea about the code
Code reuse:
Do not break what is already working
Easier updates
Inheritance: Example
Try It Out
Problem Statement:
Design a class inheritance class diagram (tree structure) for the following:
Class Superclasses Subclasses
Clothing --- Shirt, Trouser
Class Superclasses Subclasses
Trouser Clothing
Answer:
Inheritance Class Diagram
Refer File Name: Clothing.java, Shirt.java, Trouser.java to obtain soft copy of the program code
How It Works:
In the given example, Clothing is the superclass and its subclasses are Shirt and Trouser that is a Shirt extends Clothing and also a Trouser extends Clothing.
Tips and Tricks
1. The typical problems include real-time problems and challenges:
2. Are there any practical limits on the level of subclassing using Java?
3. Can you extend any class in Java?
Solution: With regard to Java API, there is no hard limit for the limits on the level of subclassing.
Using Java, you cannot extend any class as such. The factors like access control and access modifier determine whether a class can be subclassed.
Summary
A class can inherit instance variables and methods from a more abstract superclass.
Test Your Understanding
1. Fill in the blanks for the following:
a) A sub class ______ all the public instance variables and methods of the super class.
b) If the base class or super class has functionality, then its ______ automatically gets the same functionality.
2. State true or false for the following:
a) Guitar extends Instrument b) Animal extends Cat
Clothing
Trouser Shirt
Session 04: Introduction to OOPS
Learning Objectives
After completing this session, you will be able to:
Describe polymorphism
Explain the relationship between objects Polymorphism
Polymorphism (from Greek, meaning “many forms”) is a feature that allows one interface to be used for a general class of actions that is one interface with multiple methods.
Idea of polymorphism:
See internet definition: On Google type “definition polymorphism” and see the results
Moreover, refer the following url:
http://www.wordiq.com/definition/Polymorphism_%28computer_science%29
Generally, polymorphism allows you to mix methods and objects of different types in a consistent way.
Method Overloading
This is called ad hoc polymorphism, or method overloading. In this case, different methods within the same class or in a common hierarchy share the same name but have different method signatures (name + parameters)
public static float max(float a, float b)
public static float max(float a, float b, float c) public static int max(int a, int b)
When a method is called, the call signature is matched to the correct method version.
Note: This is done during program compilation
Subclassing Polymorphism
Subclassing polymorphism is sometimes called “true polymorphism”.
It consists basically of two ideas:
Method overriding:
o A method defined in a superclass is redefined in a subclass with an identical method signature.
o As the signatures are identical, rather than overloading the method, it is instead overriding the method:
o For subclass objects, the definition in the subclass replaces the version in the superclass.
Dynamic (or late) binding:
o The code executed for a method call is associated with the call during run-time.
o The actual method executed is determined by the type of the object and not the type of the reference.
o Allows superclass and subclass objects to be accessed in a regular and consistent way:
o Array or collection of superclass references can be used to access a mixture of superclass and subclass objects
o This is very useful if you want access collections of mixed data types (for example draw different graphical objects using the same draw() method call for each)
Example of a class
move()
Example of objects of the subclasses
Each subclass overrides the move() method in its own way.
Animal [] A = new Animal[3];
A[0] = new Bird();
A[1] = new Person();
A[2] = new Fish();
for (int i = 0; i < A.length; i++) A[i].move();
References are all the same, but objects are not.
The method invoked is associated with the object and not with the reference.
Relationship Between Objects Association:
Association states that there is a relation between two classes.
Example: The relation is of association type between Car and Owner or BankAccount and Customer.
Aggregation:
Aggregation is a special form of association. The relation may be referred alternatively as “contains”, “is composed of”, or “is part of”.
Example: A car contains wheels. Wheels can exist independently from the car and are not necessarily destroyed when the car is wrecked.
Composition:
Composition is the relation in which the objects cannot exist independently from the whole.
Example: The car registration cannot exist without a car. So the relationship between car and car registration number is composition.
Tips and Tricks
If you do not have access to the source code for a class, but you want to change the way a method of that class works, then could you use subclassing to do that that is to extend the “bad”
class and override the method with your own better code?
Solution: Yes. This is a great feature of Object Oriented approach, and sometimes it saves you from having to rewrite the class from scratch, or track down the programmer who is hiding the source code.
Summary
Object-oriented programming lets you to extend a program without having to touch the working code that is tested earlier.
All Java code is defined in a class.
A class describes how to make an object of that class type. A class is like a blueprint.
An object can take care of itself, you do not have to know or care how the object does it.
An object knows things and does things.
The things an object knows about itself are called instance variables. They represent the state of an object.
The things an object does are called methods. They represent the behavior of an object.
When you create a class, you may also want to create a separate test class, which you will use to create objects of your new class type.
A class can inherit instance variables and methods from a more abstract superclass.
At run-time, a Java program is nothing more than objects ‘talking’ to other objects.
Test Your Understanding
1. State true or false for the following:
a) Polymorphism means many forms.
b) An overloaded method is not the same as overridden method.