Object Oriented Programming

Programming, for all ages and all languages.
Post Reply
the.future.zone

Object Oriented Programming

Post by the.future.zone »

Hi folks. Novice programmer trying to learn @ all cost is here with a question: I notice some languages are called object oriented languages( and there are other types too, I believe), and I've googled its meaning multiple times, but seem unable to grasp the concept.
Can someone plz, explain, with insightful examples what object oriented languages are?
Thanks for the contribution.
User avatar
Pype.Clicker
Member
Member
Posts: 5964
Joined: Wed Oct 18, 2006 2:31 am
Location: In a galaxy, far, far away
Contact:

Re:Object Oriented Programming

Post by Pype.Clicker »

the concept is you declare methods that will operate on the members of your structures, and that only those methods can manipulate members variable directly.

Typically, methods offers abstract operations that would otherwise have required coordinated manipulation of several members.

Then come classes and inheritance. I'd say go to your local library and grab a pocket book like "teach yourself C++ in 10 days" or "Java Programming".
Schol-R-LEA

Re:Object Oriented Programming

Post by Schol-R-LEA »

To be honest, this isn't unusual, especially if you are looking at several languages at once - every language has a different view or model of what objects are, and while there is a set of underlying concepts in common with them all, it can be hard to see them through the differences.

Also, while OOP can be used for any type of programming, it isn't necessarily suited to all kinds of programs; there are times when some other paradigm (a particular way of looking at programs and how they are organized) is a better fit. This is true of all paradigms, except procedural, which is equally mediocre for all purposes. OOP is especially well suited for problems where there are a limited number of discrete, well-defined items which fall into a set of subcategories, such as GUI programming or game programming. It tends to work poorly for large amounts of fine-grained data, or data which doesn't consistently fit a fixed category.

Finally, there are different ways of viewing OO, and which of them is easiest to grasp varies from person to person. One way of looking at object-oriented programming, if you are familiar with procedural programming, is to think of an object as a data structure plus the procedures that go with it, bundled up together. Classes in this view are user-defined data types; once you have one defined, you can use it to declare variables just as if they were a part of the language all along.

Another way to look at it which is a bit closer to the original intention of OOP is to think of it as if you were building (or simulating) an actual physical device: the object has certain inherent properties, such as mass, height, length, etc., and can perform certain functions. To get it to do these functions, you send the device a message telling it what you want it to do and giving it the information it needs to do it. For example, in a real-world car, to make it accelerate, you would press on the accelerator with a certain amount of pressure, which tells the car to accelerate by such and such an amount. Note that it is the car that is the active agent: once you've told it what to do, it then does the requested action. The method is not (conceptually anyway) a function that acts on the object; it is an action that the object is able to take, with the method itself just defining how it does it, and the message (i.e., the method call) being just a request to do it. Similarly, you do not see the objects instance variables or properties as data; you see them as a representation of the object properties or state, and for most of them. Thus, a [tt]Car[/tt] object may have an instance variable holding it current velocity; you could use the speedometer method to see what it currently it, and the accelerator or brake methods to change it. However, it wouldn't make sense to just change it as a regular directly, because as far as you (the person operating the car) are concerned, the speed is a part of the current state of the car, not a piece of data that you can fiddle with.

The instance variables may also represent components of an object, that is, the smaller objects from which it is built. This is what is referred to as composition. For example, a [tt]Car[/tt] object may have an [tt]Engine[/tt] object, [tt]Door[/tt] objects, and [tt]Wheel[/tt] objects, which have their own instances and methods that the [tt]Car[/tt] object uses when performing it's own methods.

Some methods may have more than one form; these overloaded methods may have default arguments,

or different kinds of arguments. For example, the method [tt]accelerate()[/tt] may have a version that takes a fixed amount to accelerate to, and a different version that takes an amount by which to increase of decrease by relative to the current velocity, and another which always accelerates it by 10%. In most languages, the compiler or interpreter determines which one to use depending on the types and number of the arguments given; thus, the first version might take a value of a [tt]Velocity[/tt] type, the second a value of a [tt]DeltaV[/tt] type, and the third no arguments at all. Since they all represent the same concept or type or action (accelerating), it makes sense to be able to call them the same name, even though they do somewhat different things.

I'm out of room here, so I'll continue in the next message. HTH.
Schol-R-LEA

Re:Object Oriented Programming

Post by Schol-R-LEA »

A class, then, is like a blueprint for an object, or perhaps a factory for them: it defines what the properties of that type of objects are, and what other objects they are comprised of, and what things they can do. Not all OOP languages use classes - some use 'prototypes', where you define a single object and then make copies of it - but most use classes as a practical means of grouping similar object together. This is why the variables representing an object are called 'instance' variables: they represent a specific instance of a class, and only apply to that one instance.

Since classes (in principle) are objects themselves, they can also have values and methods which apply to the class as a whole. For example, if it is possible to have only a limited number of objects of a given class at one time, then the class might have a counter that keeps track of how many there are. These class variables and class methods (also called static variables and static methods) are part of the class itself, not part of the objects of the class. One class method all classes have is the constructor method, which is the one which actually creates the object for you. In some languages (primarily C++), there are also destructor methods for getting rid of an object as well.

A class can also be a subclass of another class, a process call inheritance. For example, if you define a class Vehicle, you could then define a subclass [tt]Car[/tt] as a type of [tt]Vehicle[/tt]. The properties of the parent class are automatically a part of it's subclasses; thus, if a [tt]Vehicle[/tt] has a [tt]speed[/tt] instance variable and an [tt]accelerate()[/tt] method, and [tt]Car[/tt] is a subclass of [tt]Vehicle[/tt] then [tt]Car[/tt] inherits them and doesn't need to define them again. However, subclasses can add their own newer methods and instances, and can override the methods of the parent class (that is, replace them with one that looks the same but does something different) or overload them.

There is a rule of thumb called the Liskov Substitution Principle that says any message that can be sent to a class should also make sense to a subclass; thus, the class [tt]Vehicle[/tt] might define a method [tt]move()[/tt] (that being a defining ability of all vehicles), but you wouldn't want to define methods [tt]drive()[/tt], [tt]fly()[/tt] or [tt]submerge()[/tt], because those would only apply to certain types of Vehicles. The subclasses [tt]Car[/tt], [tt]Airplane[/tt] and [tt]Submarine[/tt] might define those methods, but the parent class shouldn't unless it applies to all of it's subclasses. Unfortunately, it is all too easy to break this rule unintentionally, which is one of the things that makes OO programming so hard.

Another thing that confuses a lot of people is the difference between inheritance and composition; the general rule of thumb is that if you can say that an object of a class is a a member of a broader type, then it is inheritance, whereas, if you can say that on object of that class has a part of another class, then it is composition. For example, a [tt]Car[/tt] may have a door, wheels, and an engine, but it is not itself a [tt]Door[/tt], a [tt]Wheel[/tt], or an [tt]Engine[/tt] - those are the parts it has. However, you can say that a [tt]Car[/tt] is a [tt]Vehicle[/tt], thus it would make sense to have class [tt]Car[/tt] inherit from class [tt]Vehicle[/tt].

This is, as I said, only one way of looking at object-oriented programming; I hope that it has helped, but YMMV.
chasetec

Re:Object Oriented Programming

Post by chasetec »

OOP means designing a program out of small reusable software components(objects). The components can be identified by highlighting all the nouns in a requirements analysis document.

Most C++/Java/C# programming books don't take much time to teach OO concepts, mostly they teach syntax with a dash of concepts. Java is the most popular OO language if you are trying to decide which one to learn. Take a look at http://en.wikipedia.org/wiki/Object-ori ... rogramming

While OOP works well for solving most business problems it isn't suited(in my opinion) for operating system development which is mostly procedural and event driven.
Schol-R-LEA

Re:Object Oriented Programming

Post by Schol-R-LEA »

Now that you know what object-oriented programming is (I hope), I should explain what an object-oriented language is. Simply put, it is one which has built-in support for classes, method overloading, inheritance, and so on, all the things you need to write OO programs. Most languages these days have at least some support for this, though not all of them. Some languages have support for similar things which can be used in place of objects (e.g., closures in Scheme), but using an OOP language makes it easier to write programs in this manner.

Just so you are aware, there are several other paradigms (styles of program deasign), each with it's advantages and disadvantages. The most common one, other than OOP, is procedural (or imperative): this is the familiar approach of writing a program as a series of step-by-step instructions, divided into procedures which act on passive data structures. This is the oldest style of programming, and because it applies to all kinds of problems equally (poorly, but equally), it tends to be the 'default' style of programming for a lot pf coders. Other paradigms include functional (designing programs so that they behave like mathematical functions), logical (programs consist of a set of logical assertions, which are then used to determine a given result) and relational (having to do with the relationships between tables of data). There are languages which are specifically designed for one particular paradigm, such as C, Haskell, or SQL, and other which are 'multi-paradigm', such as Python, Io, or Leda.

Getting back to OOP, here is a simple example of a class definition in Python (if you don't know Python, see this tutorial for a quick introduction to it - don't worry, it should only take a few minutes):

Code: Select all

class Car:
   "class for modelling the behavior of cars"
   
   cars = 0   # class variable holding a count of all cars
   
   # constructors and destructors
   def __init__(self, location, direction, driver):
      "Special method for creating new Car objects and initialize state"
      "self is a special variable that refer to the object itself."
      self.location = location
      self.direction = direction
      self.driver = driver
      self.speed = 0     
      Car.cars += 1

   def __del__(self):
      "special method for deleting a Car object called by the garbage collector"
      "only needed if you have to do some special clean-up"
      Car.cars -= 1


    # general methods
   def accelerate(self, delta_v):
      "Change the speed of the car by delta_v MPH"
      "use a negative delta_v to decelerate"
      self.speed += delta_v
      
   def turn(self, degrees):
      "Turn the car by a certain number of degrees"
      "Positive for left, negative for right."
      self.direction += (self.direction + degrees) % 360
Unfortunately, quite a bit of this is specific to the way Python handles objects and classes, but that would be true in most languages (Ruby would probably be better, but I'm only just learning it myself; I'll post a Ruby version later if I get a chance). Also, for simplcity's sake, I've left all of the instance variables public (that is, they can be viewed and changed from the outside), something you usually wouldn't do in OOP.

In this example, I've defined a class [tt]Car[/tt] which has the methods [tt]accelerate()[/tt] and [tt]turn()[/tt], as well as a constructor [tt]__init__()[/tt] and destructor [tt]__del__()[/tt]; the names of those last two are special, as I will explain. It also has a class variable, [tt]cars[/tt], and four instance variables, [tt]driver[/tt], [tt]speed[/tt], [tt]direction[/tt], and [tt]location[/tt], which keep track of the state of the car. To access either the instance variables or the methods, you use the name of the object followed by a period, followed by the name of the instance or method and (in the case of methods) the argument list.

As I said, the method [tt]__init__()[/tt] is a special constructor method, which is used to create the objects for the class. To create an object, you would use the name of the class and the arguments used to initialize the object:

Code: Select all

****_turpin = Car("Tadfield", 0, "Newton Pulsiver")
In Python, the first argument passed to a method is a reference to the object itself (usually called [tt]self[/tt]); when the method is actually used, the method is treated as a part of the object. In the case of the constructor, since there's no object created yet, it refers to the object that is being initialized. Within the class, [tt]self[/tt] is used to refer to the object's instance variables.

Code: Select all

****_turpin.turn(90)  # turn hard left
Schol-R-LEA

Re:Object Oriented Programming

Post by Schol-R-LEA »

Here is a (rather silly) example of this class being used:

Code: Select all

from Car import Car
   
# demo program
# show that there are no cars yet
print "Right now there are ", Car.cars, "cars"

# create some Car objects
****_turpin = Car("Tadfield", 0, "Newton Pulsiver")

ultracar = Car("SEMME HQ", 45, "Joe Rosenthal")
print "After creating **** Turpin and Ultracar, there are", Car.cars, "cars."

print "The alleged car **** Turpin is being driven by", ****_turpin.driver
print "After some sarcastic comments, Ultracar is allowing", ultracar.driver, "to drive him."

print "**** Turpin is going",  ****_turpin.speed, "MPH (that figures...)."
ultracar.accelerate(1000)   # only Ultracar could do this...

print "Ultracar is speeding along at", ultracar.speed, "MPH."
a
****_turpin.driver = "Anathema Device"
print "**** Turpin now is being driven by", ****_turpin.driver

# show what happens when you explicitly destroy a Car
del ****_turpin

print "After finally scrapping **** Turpin, there is", Car.cars, "car left"
When run, this program prints:

Code: Select all

Right now there are  0 cars
After creating **** Turpin and Ultracar, there are 2 cars.
The alleged car **** Turpin is being driven by Newton Pulsiver
After some sarcastic comments, Ultracar is allowing Joe Rosenthal to drive him.
**** Turpin is going 0 MPH (that figures...).
Ultracar is speeding along at 1000 MPH.
**** Turpin now is being driven by Anathema Device
After finally scrapping **** Turpin, there is 1 car left
I know that this probably confuses you more than helps, but I am hoping that it will point you in the right direction.
chasetec

Re:Object Oriented Programming

Post by chasetec »

hehe for some strange reason I have this mental picture of someones head blowing up like a balloon and popping. :)
Schol-R-LEA

Re:Object Oriented Programming

Post by Schol-R-LEA »

Yeah, Chase, people tend to respond to my postings that way :)

I said I'd try to make a Ruby version for comparison, so here goes:

Code: Select all

class Car
  # class for modelling the behavior of cars
  
  @@cars = 0   # class variable holding a count of all cars
   
  # constructor and destructor
  
  def initialize(location, direction, driver)
  # Special method for creating new Car objects and initialize state
  # cls and self are special variables that refer to the class and the object.
    @location = location
    @direction = direction
    @driver = driver
    @speed = 0
    @@cars += 1
  end
  
  def Car.del
  # Ruby doesn't really have destructor methods
  # but we can fake it by nulling the object reference and calling 
  # the garbage collector. I only include this as a comparison
  # to the Python version of the program.
    @@cars -= 1
    ObjectSpace.garbage_collect
  end

  # accessor methods
  #
  
  attr_reader :location, :direction, :driver, :speed

  def Car.cars
  # class accessor for the variable 'cars'
    @@cars
  end


  # general methods
  #
  
  def accelerate(delta_v)
  # Change the speed of the car by delta_v MPH
  # use a negative delta_v to decelerate
    @speed += delta_v
  end
  
  def turn(degrees)
  # Turn the car by a certain number of degrees
  # Positive for left, negative for right.
    @direction = (@direction + degrees) % 360
  end

  def change_driver(driver)
  # needed as mutator, since Ruby instance vars are always private
    @driver = driver
  end
end
And the demo program:

Code: Select all

# demo program
# show that there are no cars yet
require 'Car'

puts("Right now there are " + Car.cars.to_s + " cars")

# create some Car objects
****_turpin = Car.new("Tadfield", 0, "Newton Pulsiver")

ultracar = Car.new("SEMME HQ", 45, "Joe Rosenthal")
puts("After creating **** Turpin and Ultracar, there are " + Car.cars.to_s + " cars.")

puts("The alleged car **** Turpin is being driven by " + ****_turpin.driver)
puts("After some sarcastic comments, Ultracar is allowing " + ultracar.driver + " to drive him.")

puts("**** Turpin is going " + ****_turpin.speed.to_s + " MPH (that figures...).")
ultracar.accelerate(1000)   # only Ultracar could do this...

puts("Ultracar is speeding along at " + ultracar.speed.to_s + "MPH.")

****_turpin.change_driver("Anathema Device")
puts( "**** Turpin now is being driven by " + ****_turpin.driver)

# show what happens when you explicitly destroy a Car
****_turpin = nil
Car.del

puts("After finally scrapping **** Turpin, there is  " + Car.cars.to_s + " car left")
There are probably some minor differences in the way the program actually works, but as far as how it behaves it is pretty much the same. As I say, I'm new to Ruby myself, and I probably have made at least one egregious error along the way, so bear with me (for that matter, I know I missed a few things one would usually do in the Python version, but I was trying to keep things simple).
Cheery

Re:Object Oriented Programming

Post by Cheery »

If you choose bad abstraction in object oriented programming, you end up coding much more than you'd really need to. And the resulting program looks like a set of crap tied together with a spagetti. OOP efficiently prevents you from changing the abstraction you choosed, which may be a horrifying mistake for the development of project you work on. Thought, if you know the solution already, OOP is not a problem. But if you know the solution already, you are just copy/pasting code. OOP is not therefore valid if you have good and efficient open source environment where you don't need to duplicate code&ideas whenever you work.
User avatar
Kevin McGuire
Member
Member
Posts: 843
Joined: Tue Nov 09, 2004 12:00 am
Location: United States
Contact:

Re:Object Oriented Programming

Post by Kevin McGuire »

http://www.eventhelix.com/RealtimeMantr ... _Oriented/

I remember reading this, and although I forgot most of them they did give me a good clue as to the proper way to do OOP. Someone gave me these links once and I guess this could help here too.
http://www.eventhelix.com/RealtimeMantr ... nciple.htm
http://www.eventhelix.com/RealtimeMantr ... nciple.htm
http://www.eventhelix.com/RealtimeMantr ... ntract.htm
http://www.eventhelix.com/RealtimeMantr ... nciple.htm

You can also do a google on "open and close", "liskov..","design by..", and "dependence.." principles for better information.
Post Reply