Features of OOP 9... · 2018-01-15 · Features of OOP This is module covers Object-Oriented...

12
Programming NC IV Features of OOP 1 Course Module Features of OOP This is module covers Object-Oriented Programming (OOP) concepts and features – abstraction, inheritance, encapsulation and polymorphism. Upon completing this module, students are expected to: 1. learn the fundamental concepts of object-oriented programming; 2. use encapsulation and inheritance in writing Java programs; and 3. utilize polymorphism and abstraction in Java. Object Oriented Programming (OOP) Object-oriented programming is a programming pattern that uses abstraction (in the form of classes and objects) to create models based on the real world environment. Objects are capable of passing messages, receiving messages, and processing data. The aim of object-oriented programming is to try to increase the flexibility and maintainability of programs. Because programs created through OOP language are modular, they can be easier to develop, and simpler to understand after development. However, the procedural-oriented languages use a design method called Top Down Design where the focus is on procedures, with function as the basic unit. First, you need to figure out all the functions and then think about how to represent the data. Object-Oriented programming has many benefits: 1. Ease in software design: Being able to think in the problem space rather than the machine's bits and bytes is a large help when dealing with high-level concepts and abstractions. Ease in design leads to more productive software development. 2. Ease in software maintenance: Object-oriented software are easier to understand, therefore easier to test, debug, and maintain. 3. Reusable software: There will be no need for you to keep re-inventing the wheels and re-writing the same functions for different applications. The quickest and safest way in developing a new application software is to reuse old or existing codes – fully tested and proven codes.

Transcript of Features of OOP 9... · 2018-01-15 · Features of OOP This is module covers Object-Oriented...

Page 1: Features of OOP 9... · 2018-01-15 · Features of OOP This is module covers Object-Oriented Programming (OOP) concepts and features – abstraction, inheritance, encapsulation and

Programming NC IV Features of OOP

1

Course Module

Features of OOP

This is module covers Object-Oriented Programming (OOP) concepts and features – abstraction, inheritance, encapsulation and polymorphism.

Upon completing this module, students are expected to:

1. learn the fundamental concepts of object-oriented programming; 2. use encapsulation and inheritance in writing Java programs; and 3. utilize polymorphism and abstraction in Java.

Object Oriented Programming (OOP)

Object-oriented programming is a programming pattern that uses abstraction (in the form of classes and objects) to create models based on the real world environment. Objects are capable of passing messages, receiving messages, and processing data.

The aim of object-oriented programming is to try to increase the flexibility and maintainability of programs. Because programs created through OOP language are modular, they can be easier to develop, and simpler to understand after development.

However, the procedural-oriented languages use a design method called Top Down Design where the focus is on procedures, with function as the basic unit. First, you need to figure out all the functions and then think about how to represent the data.

Object-Oriented programming has many benefits:

1. Ease in software design: Being able to think in the problem space rather than the machine's bits and bytes is a large help when dealing with high-level concepts and abstractions. Ease in design leads to more productive software development.

2. Ease in software maintenance: Object-oriented software are easier to understand, therefore easier to test, debug, and maintain.

3. Reusable software: There will be no need for you to keep re-inventing the wheels and re-writing the same functions for different applications. The quickest and safest way in developing a new application software is to reuse old or existing codes – fully tested and proven codes.

Page 2: Features of OOP 9... · 2018-01-15 · Features of OOP This is module covers Object-Oriented Programming (OOP) concepts and features – abstraction, inheritance, encapsulation and

Java Objects

Java is an object-oriented programming (OOP) language. But what on earth is an OOP? An OOP is heavily focused on objects – which are the key to understanding the concept of object-oriented programming.

Look around you – you’re surrounded with real-life objects – desks, chairs, the Computer teacher/mentor, door, laptop/computer, iPhone, Android tablet, Persian cat, lizard, switch, etc.

Each of these objects has different characteristics and behaviors.

Take the following for example:

iPhone (Object) Characteristics: Name, Brand, Color, Size Behavior: Charging, Updating, Turn Off, Turn On, Lock Screen Computer Teacher (Object) Characteristics: Name, Height, Age Behavior: Discussing, Checking, Recording

Switch (Object)

Characteristics: On, Off Behavior: Turn On, Turn Off Those are sample of real-life objects. Java objects are somewhat similar to the real-life ones. They also have characteristics (or variables in Java) and behaviors (called methods in Java).

Creating Objects The syntax in creating an object is as follows:

<class name> <variable name> = new <class name>(parameters);

Example:

Point originOne = new Point(23, 94); Rectangle rectOne = new Rectangle(originOne, 100, 200); Rectangle rectTwo = new Rectangle(50, 100);

An object statement has the following parts:

1. Declaration – This refers to the variable declaration associated with a variable name and object type.

2. Instantiation – The keyword new is used to create a new object in Java. 3. Initialization – This is the part where the object is initialized by calling a

constructor.

Page 3: Features of OOP 9... · 2018-01-15 · Features of OOP This is module covers Object-Oriented Programming (OOP) concepts and features – abstraction, inheritance, encapsulation and

Programming NC IV Features of OOP

3

Course Module

Using an Object Object fields are accessed by their name. You must use a name that is unambiguous. You may use a simple name for a field within its own class. For example, we can add a statement in a class named Rectangle that displays the width and height:

System.out.println(“The width and height are: ” + width

+ “, ” + height);

In this case, width and height are simple names. The code that is outside the object's class must use an object reference or expression, followed by the dot (.) operator and a simple field name, as in: objectReference.fieldName Example:

We have an object named Rectangle with defined fields width and height.

//Instantiate the Rectangle object

Rectangle r = new Rectangle;

// Display fields (width, height) from Rectangle object

System.out.println(“The width and height are: ” + r.width

+ “, ” + r.height);

Features of OOP

Java has four fundamental object-oriented programming concepts – (1) encapsulation, (2) inheritance, (3) polymorphism, and (4) abstraction.

Encapsulation

Encapsulation is a mechanism of packing up the data (variables) and the code acting on the data (methods) together as a single unit. In encapsulation, the variables of a class will be hidden from other classes. The hidden variables can be accessed only through the methods of their current class. This process is also known as data hiding.

For example, you discovered that you only have one piece of chocolate wafer left. What do you do? You hide it in the crisper to prevent your younger brother from eating it. It’s your private property, you know?

Page 4: Features of OOP 9... · 2018-01-15 · Features of OOP This is module covers Object-Oriented Programming (OOP) concepts and features – abstraction, inheritance, encapsulation and

To do this, you have to:

1. Declare the class variables as private. 2. Use public getter and setter methods to change and view the values of

variables.

Example:

Figure 1. Encapsulation

Figure 2. Getter and Setter

In the example above, we hide the variable chocolate by declaring it as a private variable.

Its string value can be set via setChocolate() method and can be retrieved by calling the getChocolate() which are declared in a separate class – Choco.java.

Page 5: Features of OOP 9... · 2018-01-15 · Features of OOP This is module covers Object-Oriented Programming (OOP) concepts and features – abstraction, inheritance, encapsulation and

Programming NC IV Features of OOP

5

Course Module

These methods are called in the main class – EncapsulateChoco.java by declaring the constructor ch.

Inheritance

Inheritance can be defined as the process where one class acquires the methods and fields of another class. Using inheritance, the information is made manageable in a hierarchical order.

The class which inherits the properties of another is known as subclass (derived class, child class). On the other hand, the class whose properties are inherited is known as superclass (base class, parent class).

In other words,

a child class inherits from the parent class.

Why is inheritance implemented in Java? It’s simple. If you want to create a new class but realized that some of the code you need are already written in another class, then you can derive the fields and methods from the existing one.

Here are the advantages of using a subclass:

1. The fields inherited can be used directly. 2. You can also declare new fields in the child class which are not in

the parent class. 3. The methods inherited can be used directly as well. 4. You can override methods by writing a new instance of the method

inherited from the superclass. 5. You can declare new methods in the child class which are not in the

parent class. 6. You can use a subclass constructor that invokes the superclass

constructor.

The keyword used to inherit the properties of a class is the “extends” keyword.

Page 6: Features of OOP 9... · 2018-01-15 · Features of OOP This is module covers Object-Oriented Programming (OOP) concepts and features – abstraction, inheritance, encapsulation and

Example:

“When the great King perishes, the Prince will inherit all of his belongings.”

Therefore, the Prince will own everything that his father had – palaces, cows, altars, museums and other territories.

public class King{

// body

}

public class Prince extends King{

// body

}

Given that the King’s treasures will be inherited directly by the Prince and a method to get the value of the TREASURE, then we will use the code below.

Give it a try!

Figure 3. King Class

Figure 4. Prince Class

Page 7: Features of OOP 9... · 2018-01-15 · Features of OOP This is module covers Object-Oriented Programming (OOP) concepts and features – abstraction, inheritance, encapsulation and

Programming NC IV Features of OOP

7

Course Module

Polymorphism

Do you know Morphling from Defense of the Ancients? How about this hero’s ability? (Flexible abilities)

Not playing DoTA? Okay, let’s talk about Biology. Polymorphism occurs when there are different forms of an individual in the same species.

Take a lion and a lioness for example – they belong to the same species but they look different. Or even us, humans. Boy and girls are of the same species but we have different traits – physically and emotionally.

The same goes with Java programming language polymorphism – it is the ability of a Java object to take different forms. Subclasses or child classes could have different behaviors and still share the same functions from their parent class or superclass.

A Java object that can pass more than one IS-A test is considered to be polymorphic. All Java objects are polymorphic since any object will pass the IS-A test for their own type and for the class Object.

It is important to know that you can only access an object using a reference variable. A reference variable can be of only one type. Once declared, the reference variable type cannot be changed.

If a reference variable is not declared as final, it can be reassigned to other objects. The reference variable type would determine the methods that it can invoke on the object.

A reference variable can refer to any object of its type or any subtype of its type. A reference variable can be declared as a class or interface type.

Example:

public interface Vegetarian{}

public class Animal{}

public class Horse extends Animal implements Vegetarian{}

In the example above, the Horse class is considered to be polymorphic since it has multiple inheritance. The following are true for the example above:

1. A Horse IS-A (an) Animal 2. A Horse IS-A Vegetarian 3. A Horse IS-A Horse 4. A Horse IS-A (an) Object

Page 8: Features of OOP 9... · 2018-01-15 · Features of OOP This is module covers Object-Oriented Programming (OOP) concepts and features – abstraction, inheritance, encapsulation and

Now let’s try a sample code in Java.

Create a class named Person with the following code:

Figure 5. Person Class

Create another class named Dancer with the following code:

Figure 6. Dancer Class

If you run the Dancer class, you should get the following output:

Figure 7. Dancer Class Output

Page 9: Features of OOP 9... · 2018-01-15 · Features of OOP This is module covers Object-Oriented Programming (OOP) concepts and features – abstraction, inheritance, encapsulation and

Programming NC IV Features of OOP

9

Course Module

Now create another class named Singer and type the following code:

Figure 8. Singer Class

Run the file Singer and your output should be:

Figure 9. Singer Class Output

In the examples above, take note of the following:

Dancer IS-A Person

The Dancer class overrides the dance() method from the parent class Person.

Singer IS-A Person

The Singer class overrides the sing() method from the parent class Person.

Page 10: Features of OOP 9... · 2018-01-15 · Features of OOP This is module covers Object-Oriented Programming (OOP) concepts and features – abstraction, inheritance, encapsulation and

Abstraction

You type “Potato Corner branches” in Google and hit the enter key. Google displays different results from the search keyword you entered.

Do you even wonder what happens when you hit Enter and how Google manages to find what you’re looking for? How did Google even manage to find about 85,400 results in just 0.48 seconds?

Figure 10. Google Search Result

The truth is, search engines hide the protocol or whatever is happening behind that Search button and shows us only what we need.

The same can be applied in Java through abstraction. This refers to the process of hiding the details of implementation and showing only the necessary functions.

In Object-oriented programming, abstraction is a process of hiding the implementation details from the user, providing only the functionality. With this, the user will have the information on what the object does instead of how the object does it.

In Java, abstraction is achieved using Abstract classes and interfaces.

A class which contains the abstract keyword in its declaration is known as abstract class.

Example: Create a class named Employee.

Figure 11. Employee Class

Page 11: Features of OOP 9... · 2018-01-15 · Features of OOP This is module covers Object-Oriented Programming (OOP) concepts and features – abstraction, inheritance, encapsulation and

Programming NC IV Features of OOP

11

Course Module

Create a class named Intern:

Figure 12. Intern Class

Create the main class named AbstracTest:

Figure 13. AbstractTest Class

Run AbstractTest and the output would be:

Figure 14. Abstraction Output

Page 12: Features of OOP 9... · 2018-01-15 · Features of OOP This is module covers Object-Oriented Programming (OOP) concepts and features – abstraction, inheritance, encapsulation and

In the given example, you cannot instantiate the Employee class directly from your main class. Instead, you can instantiate the Intern class, and access all the fields and methods from the Employee class.

You can observe that the constructor inside the Employee class is the same name with the class itself.

Glossary

Constructor (n.) – a special type of Java method that is used to initialize a a Java object.

References

Java T Point. Constructor in Java. Retrieved from: http://www.javatpoint.com/constructor

Oracle. Java™ Platform Standard Ed. 7. Retrieved from: https://docs.oracle.com/javase/tutorial/java/

Tutorials Point. Java. Retrieved from: http://www.tutorialspoint.com/java/java_tutorial.pdf