Introduction: What is Object-Oriented Programming?
What is object-oriented programming, what is an object, sequential operation, object's data, object-oriented problem solving approach, object-oriented paradigm, data abstraction, encapsulation, polymorphism, inheritance, the power of reuse.
Jan 13, 2021
Object-Oriented Programming- concepts and problem solving.
The world consists of objects. Each object has its own behaviour and characteristics. Imagine how hard it would be to build an aeroplane if we had to design everything from scratch, including reinventing the wheel, vulcanizing rubber and hardening plastic etc. Fortunately, we have stored the information common to all air crafts previously and simply use it which saves a huge amount of time and reduces the complexity. This is exactly the concept on which the object-oriented paradigm is built. Common characteristics between objects is stored in a class and then objects are built as their instances.
Computers were designed to solve problems that human would usually take a lot of time to solve. Hence, this makes problem solving a core domain of computer science and what a programmer must learn. We can call computer programmers as problem solvers and in order to solve a problem they must:
1. Represent and understand the data(information) that describes the problem.
2. Map the steps to use the information to solve the problem.
In computer science, problem solving has the following 6 steps,
1. Understanding the problem
2. Formulating a model
3. Developing an algorithm
4. Writing a subsequent program
5. Testing and improving the program
6. Evaluating the solution.
Write a program to calculate the average of the grades of a student.
1. Understanding the problem:
The question has asked to find the mean of all the given grades of a student
2. Formulating a model:
Average = grade1 + grade2 + …. + gradeN / number of records
3. Developing an algorithm:
grades_array = grades, sum=0 for grade in grade array add grades -> sum average <- sum / length(grades_array)
A program is written following the above algorithm in the programming language of choice.
The program is tested against all kinds of data including but not limited to corner cases that may break the algorithm such as the length of the array being returned as 0.
6. Evaluating the solution
The solution is evaluated and checked whether the output is correct or not.
When we are asked to perform a task, we require a set of instructions to perform that task. These instructions can be previously stored in the memory or explicitly stated at the time of task assignment. An algorithm is just a fancy name for a set of instructions.
Programmers use algorithms to tell a machine how to perform a certain task. For example: If a human is asked to get a stack of papers off the table, the instructions given would be, go to the table, turn towards the stack of papers, pick up the papers. Similarly, when a task is assigned to a computer/machine we need to provide it a set of instruction or algorithm in short to achieve a successful result in the said task.
A good programmer can define the necessary steps to give to a computer for completion of a task. However, a computer is bound by the limited set of possible steps. For example, given a set of number, it can add them. But if it is required to calculate the mean of the given set, the task is beyond its capability. A programmer would need to specify the steps for it to achieve this,
1. Add the numbers and save the result in a variable.
2. Calculate the length of the set and store it in the variable
3. Divide the sum variable by the length variable and store the result in a third variable.
4. Convey the result.
Note: Step 2 requires another set of instructions to be completed and is not within the capability of a computer.
Object Oriented Programming
A brief history.
The first ever object-oriented language invented was named Simula. Ole-Johan dal and Nygaard laid the foundation stone of object-oriented programming that is now the dominating version of programming in the modern day. Through their design Simula 1 was born. Simula 1 along with Simula 67 was awarded the IEEE von Neuman medal in 2002. Simula 1 programming language had neither classes nor inheritance, however Simula 67 introduced the idea of the “fundamentals of the object-oriented programming”.
Samlltalk-72, which was an early version of Smalltalk, refined the idea of objects as little computers. Tim Rentsch in his paper named “object-oriented programming”, published in 1982, said
“The immediate ancestor of object-oriented programming is the programming language Simula. The Smalltalk programming language system carried the object-oriented paradigm to a smoother model.” (Rentsch)
What is Object Oriented Programming?
Object Oriented programming, which may be thought as a new concept in the programming world by many was developed in the 1960s along with most of its concepts used in the present.
Object Oriented programming breaks down a program into various tasks which are then assigned to different objects. Considering a real-world example, Mike has been some experiencing some issues with his computer which he cannot fix on his own. He would need the help of an engineer provided by the manufacturing company. Mikes contacts the technical support and requests for an engineer to be sent to his home for fixing the issues. The technical support then does the required for assigning an engineer to this task. The engineer arrives at Mike’ s house and fixes the computer and takes his leave. In this example Mike uses an object/agent (technical support) to pass the message to the engineer. It is important to take note on how Mike does not know or need to know how the technical support contacted the engineer and assigned him the task. Then the engineer then does the assigned task and takes his leave. We must note again that Mike does not know how the computer was fixed by the engineer. This is concept is referred to as abstraction.
The concept of object-oriented programming dictates building reusable code and having the willingness of using code built by other. Technical support is a code built by someone and was used by Mike and can also be used by others for similar purposes.
Concepts of Object-Oriented Programming.
1. Method and Methods
In the example presented in the previous section Mike passes a message to technical support for calling upon a function. Similarly, in the OOP we pass messages to objects to call upon methods that would do a specific task for us. A task(method) is called upon when we pass a message to an object with some additional information called arguments. A method is only called by an object if the method has the same name as the message passed.
l. Message Vs Procedure Calls
Both consist of well-defined steps of action to perform a task after a request has been made. However, A message requires a receiver(object) to call upon a method to perform a task. A procedure call requires none such receiver. The method to call upon for the task is at the sole discretion of the receiver(object).
Mike could have asked his friend to fix his computer and could have gotten a satisfactory outcome. But the method used by this friend would have been different than the one used by the technical support. Mike could have also asked a plumber to fix his computer, but the plumber might not have the appropriate method to perform the task and would put forward an appropriate error message.
In context of computers, the method that is called upon depends upon the receiver. Different receiver may call upon different method to solve the same task. The presence of this receiver that acts as a middleman is what differentiates message passing from procedure calls.
2. Classes and Objects.
Objects: Objects act as receivers. They receive messages from the program and use them to call upon method for performing tasks. Objects contain not only methods but also data. Objects provide security to the data by not disclosing any data marked as private to the user. In the example, the technical support does not reveal the internal working to Mike, they simply receive the request and perform the task. In this scenario Mike does not know what data is used for the completion of the request. Similarly, in OOP the object does not let the user know what data it contains and how it is using it.
Classes: Classes act as a blueprint for an object. They define the behaviour and inner working of the object. All the objects derived from a class must follow the same behaviour. Technical support operator that talked to Mike in the above example was an object that followed the behaviour that was defined by a class which may be called technical support staff. All the other technical support staff communicating with a customer would also follow the same behaviour defined by the class.
In the above given code TechSupport is the class that dictates the behaviour of any object that is based on this class. Operator1 is the object that follows the design that has been laid down by the class TechSupport. A message is passed to the object which then receives the message and matches it with a corresponding method which is thereafter called and performs a task.
Objects can also be created within the same class.
In the above code the object is defined within the same class and then carries out the task successfully.
A lot of objects. in the real world, contain a lot of similarities and may follow the same behaviour. Let us consider a class Human. Now a man and a woman are two objects that are both part of the class Human. They both have various similar characteristic and behaviour. They both consume food, talk, see, hear etc. However, they both also contain some dissimilarities, like body structure, reproductive organs etc. Now due to these differences we cannot have man and women be instances of the same class. So, one way to approach this would be to create two different classes for man and women. But then there would also be a lot of repetitive code that for the two classes due to the similarities. So, to solve this we could define a super class called Human that would contain the code for the similar characteristics and behaviour of the two classes and then derive these two classes from the super class (parent class). The sub classes (child classes) would contain the code from the super class and would have the ability to override it if need be or add some of its own code. This ability of OOP is called inheritance.
The above code demonstrates how inheritance works. The class Man and Woman is derived from the super class Human. Both Man and Woman contain the method sleep() of the Human class and are able to call upon it. They also redefine the method shave according to their own needs. This is called method overriding.
Polymorphism is one of the most important characteristics of an object-oriented programming language. It refers to one object taking many forms i.e., using one thing for performing different tasks.
Method overriding: In the above example we saw two derived classes using the same function shave() to perform two different tasks. This is called run time polymorphism or method overriding.
Method Overloading: When we define more than one method with the same name in the same class to different method, we call it method overriding. An object-oriented programming language differentiates between the two method by the number or type of parameters passed in the method. If the number of parameters does not differ an error message will be generated. Let us take an example: Mary and Ajay were asked to cook a meal for the guests that were arriving for dinner. Mary cooked a wonderful dish of Chicken Curry whereas Ajay cooked a delicious Pasta. Mary and Ajay cooked quite different things and followed different instructions. However, the message passed to both was the same that is “cook a meal”. Similarly, when the message that needs to be passed to an object is similar, but the task needs to be carried out a differently bases on the specifications of the task we use method overloading.
As it is evident from the code the same name for two different methods is used. The two methods print 2 different things however they differ by the type of the parameters passed to the method.
Virtual Functions: A virtual function allows the base class to override a function defined in the parent class. If a function in base class is not defined as virtual then the base class will not override that function. In programming languages such as C++, to achieve rum time polymorphism that is method overriding the parent class method must be defined as virtual. However, in programming language such as Java, all the method are defined as virtual by default.
Abstract classes: An abstract class acts as super class from which more specific classes can be derived. It defines general methods and forces the sub classes to override them. For example, all cars contain a drive function, a neutral function and a reverse function. But how they implement it can be quite different among different brands and different models. A lower model of Maruti car may have a shift drive model and the upper model of the same car may have an automatic drive model. In OOP we can define Maruti as an abstract class that forces all it is sub classes that would the car models to have a drive function in it. In languages such as Java the method should be declared abstract whereas languages such as C++ require the function to be declared virtual. A function that is declared as virtual and as not body is known as pure virtual function. The abstract method of Java can be considered as a pure virtual function.
Note: An abstract class can contain both abstract and non-abstract methods. However, it will throw an error if an abstract method is not overridden in the sub class.
5. Abstraction & Encapsulation:
Abstraction is a concept of dealing with the action without worrying about the details of the process of the action. Abstraction has been discussed before in this paper however let us reiterate. Considering a previous example, where Mike contacted the technical support for assistance with his computer. Mike is not informed about how the engineer was contacted, how the engineer reached to Mike’s home and how the computer was fixed. Mike was spared from the details of the process. Similarly, in the world of OOP the objects receive the message, call the method and the method does its job and user does not know how the action was performed by the method.
Objects consist of both data and methods. The data can only be accessed and modified by the object’s methods. This bundling of data and methods together is called encapsulation. Data encapsulation provides added security to the data and prevents it from being modified by anything other than the methods of the object to which that belongs. In the fixing the computer example, the technical support operator must have data, such as customer phone number, employee phone number, customer address etc., encapsulated with the functions they can perform that were used together to contact the engineer and get him/her to Mike’s house.
Advantages of Object-Oriented Programming
Object Oriented Programming has been around for decades now and has gone through evolution to becomes what it is in the modern day. But the inherent concepts such as objects, classes, abstraction, encapsulation etc remain unchanged. We should also keep in mind that different programming languages may have their own implementation of the OOPs concepts.
Here are a few advantages of object-oriented programming without dependence on any specific language.
1. The real world is made up of objects and each object has its own behaviour and characteristics. Using object-oriented programming we can represent real world problems and solve them in a much more efficient manner. This paper has represented several real-world problems and how it is solved using objects and classes.
2. Object oriented programming provides higher data security as it bundles data and methods together and only allows the data to be accessed and modified by the methods. It also only gives the user necessary information and hides all the unnecessary details making it more user friendly. Recall in how technical support officer did not trouble Mike with ant of the unnecessary information about how the engineer will get there and do his job.
3. In object-oriented programming we can write reusable code using inheritance which not only makes our code more concise and requires less space but also makes it much more readable. Recall how we were able to use the same method that was written in the Human class for both its sub classes, Man and Woman.
4. As codes is modular it is easier to debug. As all objects are independent i.e., they do not dependent on any of the other objects for execution we can quickly and very easily figure out where the problem in our code is. If the engineer has not arrived at Mike’s house it would have been easy for company to figure out that the problem must have been in the technical support class.
5. Using polymorphism, we can override or overload a method to make it perform more than one task. Polymorphism gives the code the super ability to shape shift into something else. Recall how the ‘shave’ method was made to do different things depending upon which object called it and how Mary and Ajay were able to cook different things using the ‘cook’ method.
6. Object oriented programming language require less space to store the code as most of the objects are created at run time when they are called and are destroyed after they have successfully accomplished their purpose.
Popularity of Object-Oriented Programming and Its Problems
Object oriented programming is a fairly popular concept. And it had become even popular now that it has been followed up by object-oriented analysis and object-oriented design. However, this concept can be hard to understand for new programmers or programmers who have usually coded in functional programming paradigm or procedural programming languages only. This causes the programming world to be split in two sections, the one who has adopted object-oriented programming and one who hates it. It is not only new programmers who are against the idea of object-oriented programming but some experienced programmers such as, Ilya Suzdalnitski, who is a senior full stack developer at Replicon has called OOP a “Trillion-dollar disaster” (Suzdalnitski, 2019). People believe that object-oriented programming is a paradigm for elite programmers whereas the code base is mostly edited by average programmers since they are more in numbers. This requirement of elite programmers, who are harder keep around, may cause the paradigm to fail over time.
However, no matter how much object-oriented programming is hated by experienced or novice programmers the success of object programming languages such as Java and C++ are undeniable.
Object oriented programming has gained so much popularity that it does not seem to stop. Most of the problems in real life are being solved using this paradigm. Even though, object-oriented programming may not be very well understood by everyone it is an undeniable fact that it has made revolutionary changes in the programming world. This paper tries to explain each terminology and concept in relation to their real-life usage which proves its importance in the real-world problem solving. It is essential to understand how the paradigm works and effect the problem before selecting it to reach the solution.
2.Object-oriented programming: Some history, and challenges for the next fifty years. Andrew P. Black, Portland State University.
3.Object-oriented programming and its concepts. Ashwin Urdhwareshe, Department of Technology Management, University of Bridgeport.
4. Introduction to Network Simulator NS2 (second edition). Teerawat Issariyakul Ekram Hossain
5.Object-Oriented Programming. Tim Rentsch, Computer Science Department, University of Southern California.
6.Data abstraction, data encapsulation and object-oriented programming. A. Toni Cohen, Department of Computer and Information Sciences, University of Delaware.
More from Riyan Pahuja
Studying engineering as information technology major.
About Help Terms Privacy
Get the Medium app
Text to speech
- Lecture 1.1 Data Types in C++
- Lecture 1.2 Constant and Variable
- Lecture 1.3 Arrays in C++
- Lecture 1.4 Strings in C++
- Lecture 1.5 Structures in C++
- Lecture 1.6 Function Overloading in C++
Lab Task 16
- Lecture 2.1 Difference between Object Oriented and Procedural Programming
- Lecture 2.2 Problem Solving in Object Oriented Paradigm
- Lecture 2.3 Defining classes and objects in JAVA
- Lecture 2.4 Controlling access to class members – Encapsulation
- Lecture 2.5 Passing and returning non primitive values from methods
- Lecture 2.6 Static Data members and Methods
- Lecture 2.7 Composition / Containership(Has-a relationship)
- Lecture 2.8 Inheritance
- Lecture 2.9 Method Overriding and Abstract Classes
- Lecture 2.10 Review of Basic Programming Concepts, Using Inner Classes
- Lecture 2.11 Interfaces and their usage
- Lecture 2.12 Arraylist Class and Generic Types
- Lecture 2.13 Exceptions and Error Handling
- Lecture 2.14 File Handling
- Lecture 2.15 Graphical User Interface – Layout Managers
- Lecture 2.16 Graphical User Interface – Event Driven Programming
Problem Solving in Object Oriented Paradigm
Introduction:, problem solving methodology in oop:.
The world around us is made up of objects, such as people, automobiles, buildings, streets, and so forth. Each of these objects has the ability to perform certain actions, and each of these actions has some effect on some of the other objects in the world.
OOP is a programming methodology that views a program as similarly consisting of objects that interact with each other by means of actions.
Object-oriented programming has its own specialized terminology. The objects are called, appropriately enough, objects. The actions that an object can take are called methods. Objects of the same kind are said to have the same type or, more often, are said to be in the same class.
For example, in an airport simulation program, all the simulated airplanes might belong to the same class, probably called the Airplane class. All objects within a class have the same methods. Thus, in a simulation program, all airplanes have the same methods (or possible actions), such as taking off, flying to a specific location, landing, and so forth. However, all simulated airplanes are not identical. They can have different characteristics, which are indicated in the program by associating different data (that is, some different information) with each particular airplane object. For example, the data associated with an airplane object might be two numbers for its speed and altitude.
Things that are called procedures, methods, functions, or subprograms in other languages are all called methods in Java. In Java, all methods (and for that matter, any programming constructs whatsoever) are part of a class.
Consider the concept of a CourseResult. The CourseResult should have data members like the student name, course name and grade obtained in that course.
This concept can be represented in a class as follows:
Public class CourseResult
Public String studentname; Public String coursename; Public String grade;
public void display()
System.out.println(“Student Name is: ― + studentname + “Course Name is: ― + coursename + “Grade is: ― + grade);
Public class CourseResultRun
public static void main(Stringargs)
CourseResult c1=new CourseResult (); c1.studentName= ―Ali‖; c1.courseName= ―OOP‖;
c1.grade= ―A‖; c1.display();
CourseResult c2=new CourseResult (); c2.studentName= ―Saba‖; c2.courseName= ―ICP‖;
c2.grade= ―A+‖; c2.display();
Note that both objects; c1 and c2 have three data members, but each object has different values for their data members.
The example below represents a Date class. As date is composed of three attributes, namely month, year and day; so the class contains three Data Members. Now every date object will have these three attributes, but each object can have different values for these three
public class Date
public String month; public int day;
public int year; //a four digit number.
public void displayDate()
System.out.println(month + ” ” + day + “, ” + year);
public class DateDemo
public static void main(String args)
Date date1, date2; date1 = new Date();
date1.month = “December”; date1.day = 31;
date1.year = 2012; System.out.println(“date1:”); date1.display();
date2 = new Date(); date2.month = “July”; date2.day = 4;
date2.year = 1776; System.out.println(“date2:”); date2.display();
Consider the concept of a Car Part. After analyzing this concept we may consider that it can be described by three data members: modelNumber , partNumber and cost.
The methods should facilitate the user to assign values to these data members and show the values for each object.
Public class CarPart
private String modelNumber; private String partNumber; private String cost;
public void setparameter(String x, String y,String z)
modelNumber=x; partNumber=y; cost=z;
public static void display()
System.out.println(“Model Number: ―+modelNumber + ―Part Number: ―+partNumber +
―Cost: ― + cost);
Public class CarPartRunner
CarPart car1=new CarPart ();
String x=JOptionPane.showInputDialog(“What is Model Number?” ); String y=JOptionPane.showInputDialog(“What is Part Number?” ); String z=JOptionPane.showInputDialog(“What is Cost?” ); car1.setparameter(x,y,z);
A Student is an object in a university management System. Analyze the concept and identify the data members that a Student class should have. Also analyze the behavior of student in a university management System and identify the methods that should be included in Student class.
Time is an intangible concept. Analyze the concept and identify the data members and methods that should be included in Time class.
Car is an object that helps us in transportation. Analyze the concept and identify the data members and methods that should be included in Car class.
Rectangle is an object that represents a specific shape. Analyze the concept and identify the data members and methods that should be included in Rectangle class.
Leave A Reply Cancel reply
You must be logged in to post a comment.
Algorithms and OOD (CSC 207 2014S) : Readings
[ Skip to Body ]
Primary: [ Front Door ] [ Schedule ] - [ Academic Honesty ] [ Disabilities ] [ Email ] - [ FAQ ] [ Teaching & Learning ] [ Grading ] [ Rubric ] - [ Calendar ]
Current: [ Assignment ] [ EBoard ] [ Lab ] [ Outline ] [ Reading ]
Sections: [ Assignments ] [ EBoards ] [ Examples ] [ Handouts ] [ Labs ] [ Outlines ] [ Partners ] [ Readings ]
Reference: [ Java 7 API ] [ Java Code Conventions ] [ GNU Code Conventions ]
Related Courses: [ CSC 152 2006S (Rebelsky) ] [ CSC 207 2013F (Rebelsky) ] [ CSC 207 2013S (Walker) ] [ CSC 207 2011S (Weinman) ]
Misc: [ SamR ] [ Glimmer Labs ] [ [email protected] ] [ Grinnell ] [ Issue Tracker (Course) ] [ Issue Tracker (Textbook) ]
Basics of Object-Oriented Problem Solving
Summary: We consider, at a high level, the basic issues involved in object-oriented problem solving.
Background: Problem-Solving Paradigms
As you may have heard, Computer Science is the study of algorithms (formalized instructions for solving problems) and data. One key aspect of this study involves the ways in which we represent algorithms. Early algorithms (by early, I mean long before computers) were often written as examples. For example, in describing how to compute the volume of a rectangular hole, one might say “ Suppose the hole is 3 feet deep, 4 feet wide, and 6 feet long. We multiply 4 and 6 to get the area of a cross section, and then by 3 to get the volume of the hole. ”
With the advent of automated computing devices, it became important to describe algorithms more carefully, and in such a way that the steps of the algorithm could be automated. In thinking about these descriptions, computer scientists developed four main paradigms for structuring solutions.
In imperative languages, we express algorithms as a sequence of individual steps. Steps traditionally involve basic computation, input, and output. To some, imperative algorithms look very much like the recipes in a cookbook (do this, do that, do this other thing this many times).
In functional languages, we express algorithms by defining and combining functions. Functional algorithms tend to deemphasize precise sequencing of operations; for example, it usually does not matter which argument to a function you compute first.
In object-oriented languages, we express algorithms by defining “ objects ” and having the objects interact with each other.
In declarative languages, we express algorithms by specifying a set of facts or goals, and let the computer determine how to apply those facts or goals to solve the problem at hand.
Right now, object-oriented languages currently dominate, although most of these languages also have a strong imperative aspect. Why do programmers like object-oriented languages? There are a variety of reasons to like these languages.
First, object-oriented languages are quite appropriate for programs that model the real world. In writing such models, we can have one object in the program for each object in the world. If your task is to, say, figure out optimal cashier placement at Wal-Mart, such modeling is completely appropriate.
Second, object-oriented languages can simplify parallelization. Since each object can, in effect, work independently, it is possible to put different objects on different processors, and therefore make the program faster.
Third, object-oriented languages are very appropriate for modern graphical user interfaces (GUIs). Programmers have found it much easier to design and implement GUIs when they think of each part of the interface as an object that communicates with other objects in the interface and with objects that provide the underlying computation. For example, we can think of each menu, each button, and each window as a separate object and write the code by which they react to user actions separately.
Finally, it turns out that many core ideas of object-oriented programming make it much easier to write large programs and to reuse code written for previous programs (or for other parts of the same program). We will visit and revisit these approaches and their associated efficiencies.
So, what is an object? In object-oriented problem solving, we think of an object as something that collects data and capabilities. Typically, the data within the object are categorized. For example, if we have an object that represents a book, we would identify part of the data as the title, part as the author, part as the publisher, and so on and so forth. Similarly, for an object that represents a menu, we would identify part of the data as the name of the menu and other parts as the items in the menu.
Traditionally, we call the categorized parts of an object the fields or attributes of the object.
But objects do more than collect data. Most objects also provide a variety of capabilities. That is, they can do things, typically things with their internal data (and with values passed in). For example, a book object might provide the text of a page, if you give it a page number, and a menu object might tell you what item was last selected. Some call these capabilities methods (the term we will use). Others refer to them as messages or message handlers . You may also think of them as procedures or functions .
Encapsulation: Separating What from How
In a well-designed object-oriented program, the clients of an object (that is, the other objects that use an object or the programmers who write those objects) interact with an object and the fields of the object exclusively through the methods of that object. Why limit that access? That is, why not give the client direct access to the fields? Experience suggests that giving the client such access can create problems in the long term. For example, suppose the client assumes your object has a field called lastName . If you later change the name of that field, to, say, surname , the client code will no longer work. In almost every case, the program will be just as efficient if the client does not directly access the fields, so there is little reason to give the client that access.
In fact, there are also other reasons to limit access to the internals of an object (not just the fields, but also the details of how each method works). By limiting such access, you absolve the client from having to know how each method works. Clients need only know what your methods do. Consider a rational number (fraction) object. It is likely that you will represent rational numbers as a pair of integers, one for the numerator and one for the denominator. A client that uses your numerator and denominator will need to know not only what names you have chosen for the numerator and denominator, but also particular other details of your representation, such as how you deal with negative numbers and whether you always store rational numbers in simplified form. Rather than forcing the client to know such details, we use methods to separate what one might do with an object (e.g., negate a number) from how we implement those methods.
Traditionally, we call such the separation of the interface (what an object does) from the implementation (how it achieves) its goals information hiding .
Because objects combine methods and data and protect the data from the outside world, we often say that objects encapsulate their contents.
Classes: Templates for Objects
One of the first problems any object-oriented language designer encounters is how programmers are to describe the objects that appear in their programs. Many object-oriented languages rely on classes . A class is, in effect, a template for objects. Each class gives the names (and, often, types) of the fields for related objects and the names (and, often, instructions) for the related methods.
For example, a class to represent rational numbers might have two fields, a numerator (integer) and a denominator (integer). It might provide methods to add another rational number to the current rational, subtract another rational number, multiply by another rational number, and so on and so forth.
Similarly, a class to represent books might have a field for the title (a string), a field for the authors (a list of names, where “ name ” is a previously defined class), a field for the pages, and so on and so forth. That class might provide methods to access the title and authors (but probably not to change them) and to get pages by number.
Inheritance: Building New Classes from Old
Object-oriented programmers quickly realize that the new classes they build often closely relate to previous classes they've built. For example, if we are called upon to write a class to represent library books, that class will be very similar to the class for regular books, except that the library book class will include additional fields (such as the call number) and additional methods (such as checking the book in or out). The technique called inheritance permits you to define a new class in terms of an old class, and “ automatically ” inherit all of the fields and methods of the original class.
At times, when we inherit from another class, we also want to override (change the behavior of) some of the methods of the original class. Most object-oriented languages permit such behavior. For example, suppose we design a square class that inherits from the rectangle class. If the rectangle class includes a method that sets the width, we would want the square class to change that method to set both width and height.
Although some aspects of inheritance could be implemented by the legendary technique of copying and pasting code, real inheritance permits one to make changes to the original class and have those changes automatically propagate to the inheriting class. The automatic reuse and update capabilities associate with inheritance are one of the reasons programmers so prefer object-oriented programming.
Polymorphism: Reusing Methods
The final key aspect of most object-oriented languages is called polymorphism . While inheritance lets you reuse field and method definitions by building new classes from old, polymorphism lets you reuse methods by applying them to new objects. In particular, polymorphism is the notion that you once you write methods that take objects as parameters (and use the methods that those objects provide), then your methods can take any objects as parameters, provided that they provide the appropriate methods.
For example, we know that we can square anything that we can multiply by itself. The square operation can therefore work with integers, real numbers, and complex numbers. It can even work with newly-defined rational numbers, as long as we define the multiply operation.
Summary: What to Look for When Learning OOP
In this reading, we've considered some key aspects of object-oriented programming languages. When you start to learn a new object-oriented language, you will need to find out how each of these features is implemented. In particular, you will need to figure out
- how to define a class (and the methods and fields in that class),
- how, given a class, to build objects that belong to that class,
- how to indicate that one class inherits from another, and
- how to write a polymorphic method.
We will cover each of these ideas in our explorations of Java.
- Why do programmers like object-oriented programming?
- What are two benefits to encapsulation?
- Why does inheritance improve code reuse?
- Why does polymorphism improve code reuse?
- In the reading, we noted that most, but not all, object-oriented languages use classes. Find an object-oriented language that does not use classes and determine how programmers create new objects in such languages.
- Find a few examples of polymorphic functions.
- Find a few examples of polymoprhic data structures (or ADTs).
Copyright (c) 2013-14 Samuel A. Rebelsky.
Object-Oriented Thought Process
In the first step of designing an OO program, programmers create a data model which tries to model the real world. The components of the real world are represented as objects that have properties ( attributes ) and behaviours ( methods ) which interact with each other to simulate the solution. In this process, the programmer considers;
- What data will be revealed to other objects (abstraction)
- What data do each object contain and how they behave (encapsulation)
- The hierarchy of objects (inheritance), and
- What combination of objects form another object (composition)
Abstraction is a very important concept of object-oriented programming that helps to reduce the complexity of an OO design by only allowing other objects to access the data that is required and hiding all the others. For example, lets say we have a timer object and the data that it contains are...
- total milliseconds counted
When we want other objects to use this object, we will only want them to have access hours , minutes and seconds attributes only because the total milliseconds counted property of the object is a low-level detail that will be used by the object to get the number of hours, minutes and seconds. So, we will make total milliseconds counted private while the others will be public.
This is a concept in OOP that deals with packaging data and the methods that works with them together in a class. It creates the concept of Internal State of an object, where only the object has access to the state data. For example, we are writing a code that fetches the latest news from the internet and we are using a class with the following contents:
- connected to the internet: false
- last fetch: 5 mins ago
- type of news to fetch: sports
Private hidden implementation
- fetch news from the internet
In this class, the internal state variables are connected to the internet and last fetch . Because we wouldn't want the user to worry about their code affecting the class and we also wouldn't want to allow other objects to mess with the internal state, this data is kept private to the object and no direct access is allowed outside the object.
Inheritance is another important feature of OO programming that is about basing classes or objects on other classes (for class-based constructor) or objects (prototype-based constructor). It allows a class to derive initial features from another class. It promotes code re-usability, efficiency and reduction of redundancy. In inheritance, parent to sub class relation can be represented as "sub" is a "parent" .e.g Apple is a Fruit , Car is a Vehicle , Dog is an Animal . Examples of inheritance scenarios are;
- Lets imagine that we just built a simple platform running game and in the pause menu we need a "resume" button, a "restart" button and an "exit" button. To do that we can create one major class "PauseMenuButtons" that holds all the methods that will be common to all the buttons like the buttons event handler reactions. Then we create the "resume", the "restart" and the "exit" buttons that extends (inherits properties from) "PauseMenuButtons".
- We made a game. In this game we will need to have two players, "User" and "CPU". The best way to implement this will be to create a "Player" class that houses all common features of the player ("User") and "CPU". Then have "User" and "CPU" inherit the "Player" class with little modifications made.
Composition one of the most important concept in OOP that allows building of bigger classes by using smaller objects as building blocks. It is similar to inheritance as they both object mechanism improve code re-usability. In composition, object relations are represented by "has a". That means if A is related to B through composition, A has a B . For example; lets say we have a program that counts down in seconds. For the app we will create a main class called "App". This class will contain timer, start button, stop button and an input field. This objects are representations of what will be included within the class. All the objects that compose the "App" will be connected to the UI (User Interface), the event handlers and the screen display. And that is how composition works.
Composition Over Inheritance
Composition over inheritance is an argument thats been in the OOP community for a very long time. For a lot of reasons some programmers say composition is more preferable to inheritance. There are certainly more areas where composition will be the best suit, but, it doesn't mean that it is the best form of reusability in all scenarios. Some of the reasons supporting composition are;
- It allows a model to be modified by simply adding objects of the desired functionality to the class without affecting the logic.
- It is simplier to model real-world problems using composition to break it down into what the objects contain, instead of struggling to find relations between classes and forming a hierarchical tree by inheritance.
- Modelling complex problems using composition is so much simpler than inheritance
- Changes can be made to the dependency at runtime, but once a class inherits a property it stays with those properties until deletion of the object.
A simple example of a constructor function is;
To create an object using this type of function, you put a new before the function call. Example;
The previous example's factory function version is;
This object is just like the first, only the properties and methods that are in the returned object are revealed to the user. And the returned objects access the workTheEngine function through a concept called closure . A closure is a concept of programming where returned functions or object access the local binding of the function that return ed it.
All class-notation objects are converted to the prototype-based version before runtime. The prototype-based constructor function works just like the normal constructor function but it add features like inheritance to it. A simple example the prototype-based constructor is;
In this construct too, It is not possible to create private methods or properties. Because, there is no way the that the fields can interact with each other if they are not public for all to see. To use inheritance, we first assign the parent's prototype to the child's prototype and then we start to add new features to the child. For example;
Object-oriented programming is a powerful and effective programming paradigm and it pays to learn it as it promotes creativity due to the fact that everything it deals with are imaginable objects.
Thanks for reading and have a good day!
Objects and object-oriented programming.
P rograms must be designed . No one can just sit down at the computer and compose a program of any complexity. The discipline called software engineering is concerned with the construction of correct, working, well-written programs. The software engineer tries to use accepted and proven methods for analyzing the problem to be solved and for designing a program to solve that problem.
During the 1970s and into the 80s, the primary software engineering methodology was structured programming . The structured programming approach to program design was based on the following advice: To solve a large problem, break the problem into several pieces and work on each piece separately; to solve each piece, treat it as a new problem which can itself be broken down into smaller problems; eventually, you will work your way down to problems that can be solved directly, without further decomposition. This approach is called top-down programming .
There is nothing wrong with top-down programming. It is a valuable and often-used approach to problem-solving. However, it is incomplete. For one thing, it deals almost entirely with producing the instructions necessary to solve a problem. But as time went on, people realized that the design of the data structures for a program was at least as important as the design of subroutines and control structures. Top-down programming doesn't give adequate consideration to the data that the program manipulates.
Another problem with strict top-down programming is that it makes it difficult to reuse work done for other projects. By starting with a particular problem and subdividing it into convenient pieces, top-down programming tends to produce a design that is unique to that problem. It is unlikely that you will be able to take a large chunk of programming from another program and fit it into your project, at least not without extensive modification. Producing high-quality programs is difficult and expensive, so programmers and the people who employ them are always eager to reuse past work.
So, in practice, top-down design is often combined with bottom-up design . In bottom-up design, the approach is to start "at the bottom," with problems that you already know how to solve (and for which you might already have a reusable software component at hand). From there, you can work upwards towards a solution to the overall problem.
The reusable components should be as "modular" as possible. A module is a component of a larger system that interacts with the rest of the system in a simple, well-defined, straightforward manner. The idea is that a module can be "plugged into" a system. The details of what goes on inside the module are not important to the system as a whole, as long as the module fulfills its assigned role correctly. This is called information hiding , and it is one of the most important principles of software engineering.
One common format for software modules is to contain some data, along with some subroutines for manipulating that data. For example, a mailing-list module might contain a list of names and addresses along with a subroutine for adding a new name, a subroutine for printing mailing labels, and so forth. In such modules, the data itself is often hidden inside the module; a program that uses the module can then manipulate the data only indirectly, by calling the subroutines provided by the module. This protects the data, since it can only be manipulated in known, well-defined ways. And it makes it easier for programs to use the module, since they don't have to worry about the details of how the data is represented. Information about the representation of the data is hidden.
Modules that could support this kind of information-hiding became common in programming languages in the early 1980s. Since then, a more advanced form of the same idea has more or less taken over software engineering. This latest approach is called object-oriented programming , often abbreviated as OOP.
The central concept of object-oriented programming is the object , which is a kind of module containing data and subroutines. The point-of-view in OOP is that an object is a kind of self-sufficient entity that has an internal state (the data it contains) and that can respond to messages (calls to its subroutines). A mailing list object, for example, has a state consisting of a list of names and addresses. If you send it a message telling it to add a name, it will respond by modifying its state to reflect the change. If you send it a message telling it to print itself, it will respond by printing out its list of names and addresses.
The OOP approach to software engineering is to start by identifying the objects involved in a problem and the messages that those objects should respond to. The program that results is a collection of objects, each with its own data and its own set of responsibilities. The objects interact by sending messages to each other. There is not much "top-down" in the large-scale design of such a program, and people used to more traditional programs can have a hard time getting used to OOP. However, people who use OOP would claim that object-oriented programs tend to be better models of the way the world itself works, and that they are therefore easier to write, easier to understand, and more likely to be correct.
You should think of objects as "knowing" how to respond to certain messages. Different objects might respond to the same message in different ways. For example, a "print" message would produce very different results, depending on the object it is sent to. This property of objects—that different objects can respond to the same message in different ways—is called polymorphism .
It is common for objects to bear a kind of "family resemblance" to one another. Objects that contain the same type of data and that respond to the same messages in the same way belong to the same class . (In actual programming, the class is primary; that is, a class is created and then one or more objects are created using that class as a template.) But objects can be similar without being in exactly the same class.
For example, consider a drawing program that lets the user draw lines, rectangles, ovals, polygons, and curves on the screen. In the program, each visible object on the screen could be represented by a software object in the program. There would be five classes of objects in the program, one for each type of visible object that can be drawn. All the lines would belong to one class, all the rectangles to another class, and so on. These classes are obviously related; all of them represent "drawable objects." They would, for example, all presumably be able to respond to a "draw yourself" message. Another level of grouping, based on the data needed to represent each type of object, is less obvious, but would be very useful in a program: We can group polygons and curves together as "multipoint objects," while lines, rectangles, and ovals are "two-point objects." (A line is determined by its two endpoints, a rectangle by two of its corners, and an oval by two corners of the rectangle that contains it. The rectangles that I am talking about here have sides that are vertical and horizontal, so that they can be specified by just two points; this is the common meaning of "rectangle" in drawing programs.) We could diagram these relationships as follows:
DrawableObject, MultipointObject, and TwoPointObject would be classes in the program. MultipointObject and TwoPointObject would be subclasses of DrawableObject. The class Line would be a subclass of TwoPointObject and (indirectly) of DrawableObject. A subclass of a class is said to inherit the properties of that class. The subclass can add to its inheritance and it can even "override" part of that inheritance (by defining a different response to some message). Nevertheless, lines, rectangles, and so on are drawable objects, and the class DrawableObject expresses this relationship.
Inheritance is a powerful means for organizing a program. It is also related to the problem of reusing software components. A class is the ultimate reusable component. Not only can it be reused directly if it fits exactly into a program you are trying to write, but if it just almost fits, you can still reuse it by defining a subclass and making only the small changes necessary to adapt it exactly to your needs.
So, OOP is meant to be both a superior program-development tool and a partial solution to the software reuse problem. Objects, classes, and object-oriented programming will be important themes throughout the rest of this text. You will start using objects that are built into the Java language in the next chapter , and in Chapter 5 you will begin creating your own classes and objects.
Something went wrong!
Some error occured while loading page for you. Please try again.
Review the problem statement, choose a language, enter your code, test your code, submit to see results.
- Check your score
The six steps of problem solving involve problem definition, problem analysis, developing possible solutions, selecting a solution, implementing the solution and evaluating the outcome. Problem solving models are used to address issues that...
When multiplying or dividing different bases with the same exponent, combine the bases, and keep the exponent the same. For example, X raised to the third power times Y raised to the third power becomes the product of X times Y raised to th...
The four steps for solving an equation include the combination of like terms, the isolation of terms containing variables, the isolation of the variable and the substitution of the answer into the original equation to check the answer.
Object-oriented problem solving approach is very similar to the way a human solves daily problems. It consists of identifying objects and how to use these
Object Oriented programming breaks down a program into various tasks which are then assigned to different objects. Considering a real-world example, Mike has
Focus will be on solving problems with Object Oriented. Programming (OOP), and you'll learn some Java along the way. • OOP is not the only way to solve
The world around us is made up of objects, such as people, automobiles, buildings, streets, and so forth. Each of these
The traditional way is to pick a problem and start solving it. Learn and relearn as you go. · Then pick another problem; maybe of greater complexity. Solve that.
So, what is an object? In object-oriented problem solving, we think of an object as something that collects data and capabilities. Typically, the data within
we can use computers to solve them. ○ Design a solution for the problem. ○ Convert the solution to a program (in Java). ▫ We will learn several aspects
This is a programming paradigm that focuses on "objects" that the programmer wants to manipulate on the high-level rather than the detailed
لينك بلاي ليست OOP Problem Solving With (Java) ... vte Object-oriented programming (OOP) is a programming paradigm based on the concept of
The OOP approach to software engineering is to start by identifying the objects involved in a problem and the messages that those objects should respond to. The
Subdomains · Challenge Walkthrough · Review the problem statement · Choose a language · Enter your code · Test your code · Submit to see results.