Docsity

Lecture-2-Encapsulation Abstraction, Thesis of Object Oriented Programming

Partial preview of the text

Download Lecture-2-Encapsulation Abstraction and more Thesis Object Oriented Programming in PDF only on Docsity!

Encapsulation & Abstraction

Lecture 2

Encapsulation

All programs are made up of two fundamental elements: Data Information that the program holds Functions Perform actions on and manipulate the data Users should not be allowed to “mess around” with the data Avoid Encapsulation keeps data and functions safe from outside interference and manipulation. Exposes only the interfaces and hides the details Done through the use of public, private and protected keywords Also known as data hiding

Example

class Box { private double length; public double getVolume (void) { return length * length * length; } public double Length{ get {return length;} set {length = value;} } }; //end class Box Abstractio n Encapsulat ion

Accessors

Notice the first method’s name in the previous example? getVolume() What does the word ‘get’ signify? Also notice how this function has no input and only a return type This type of function is called an “Accessor” OR a “Getter” function.  As it is obvious from the name, it is used to access or get a value

Creating Reusable Classes

 As programs become larger with multiple functions and classes, it becomes difficult to maintain a single file for everything. Solution: divide your code into multiple files that are easier to maintain.

Do it yourself!

 Write a class named “Pizza” which has the following attributes: Size Toppings (list of different ingredients) Crust (type) Price Create the class diagram for the class “Pizza” Write the code for the class and test it. How will you make sure the data is properly abstracted and encapsulated?