Want to read Slashdot from your mobile device? Point it at m.slashdot.org and keep reading!


Forgot your password?
DEAL: For $25 - Add A Second Phone Number To Your Smartphone for life! Use promo code SLASHDOT25. Also, Slashdot's Facebook page has a chat bot now. Message it for stories and more. Check out the new SourceForge HTML5 Internet speed test! ×

Journal FortKnox's Journal: Object Oriented Programming 101: intro 17

Due to a lack of understanding of OOP by gmhowell in his <A HREF="http://slashdot.org/~gmhowell/journal/18764">journal</A>, I'm gonna write a beginners lessons in OOP.  It isn't something for someone that doesn't know how to code, but someone that is comfy with procedural coding, and wants to understand OOP.  BTW - I'm terrible with HTML, so sorry about the HREF tag that isn't a hyperlink.  I'm putting this entire entry into the 'code' format so it'll be easier to read.

Lesson 1:

OK, allow me to throw stuff into the water and get your feet wet in OOP.
I'll use pseudo code that looks an aweful lot like Java, to help you out.

Lets say you want to create a 'TV' in code.  We'll do it in procedural type first.
We'll need a picture, volume, and channels.

So we make a structure:
structure TV
   Display picture;
   int     volume;
   int     channel;

So, to change the channel, you'll need a function to do that:
void changeChannel( Structure TV, int newChannel )
   TV.channel = newChannel;

What OOP does is wrap all this stuff up together (variables AND functions).  This gives us an advantage.  We don't need to put the structure into the function, because the variables and the function belong to the same structure.  So, we make a new special structure called a 'class'.

class TV
   int     channel;
   int     volume;
   Display picture;

   void changeChannel( int newChannel )
      channel = newChannel;

And, to use this new class, you create an object like so:

void main()
   TV tvObject = new TV();  //just allocating mem
   tvObject.changeChannel( 2 );

This discussion has been archived. No new comments can be posted.

Object Oriented Programming 101: intro

Comments Filter:
  • Good intro. However I think you need to give 'em a bit more. Anyone can read what you wrote and say "oh yeah, I can do that!" Which is good! We want to get peoples confidences up!

    But I had a question at my review session this weekend- here's the set up:

    Class Person (Name, SSN, and get and set methods)
    Class Student extends Person (School name, gpa)
    CLass HSstudent extends Student (graduation date)
    Class College Student extends Student (Credits, Major)

    Every class has a "read" function that will read in from the command line values for its internal data types.

    You are writing a program that will take in data on students. Everyone is either A Highschool student or a College student.
    The input MUSt be taken in this order:
    Then if the word "University" or "College" is somewhere in the School string, ask for
    otherwise assume they are a HS student and ask for
    Graduation Date
    What is the most OO way of implementing this?
    What is the best way of doing this?

    Instantiating a Student, calling Student1.read();
    then query the SchoolName value to decide HS or College, then query those additional fields, then construct a CollegeStudent with ALL of the values?

    Have a ReadWhatsLeft() method in HS and College student to figure out what internal variables have already been initialized?

    Or have 6! (6 factorial) constructors for College Student, where whatever values aren't passed in on the parameter list query the user and are asked for on the command line?

    Any takers?

    • WoWoWoWoooo. Nice shootin, Tex!

      This is just an intro on what classes are. Next lesson is encapsulation, then inheritance, then polymorphism.
      Then I'll get into Java, and talk about syntax, constructors, copy constructors, etc etc etc... you're like 10 lessons ahead ;-)
    • The short answer is: I always check user input through the UI layer. They don't get to create a new Student unless they provide all the right info from the get-go :) Of course, sometimes your "user" is an automated process (i.e. another computer) so I guess stopping them at the UI layer is not always an option.

      As far as the "read" method: I think the answer you are looking for is actually found in the Static Factory pattern.

      I speak java so this is how I would solve it:

      First, you would make the Person structure an Interface.

      For your static factory, you make a class called

      Registrar in package Education (or whatever)

      that has methods like

      Registrar.getCollegeStudent(arg1, arg2, art_etc)
      Registrar.getHSStudent(arg1, arg2, arg_etc)
      and of course
      and let's not forget

      which in all cases return instances of Person.

      Furthermore, instead of making the other data fields simple String data types, you make them their own data object classes, perhaps

      RegistrationInfo {
      List classes;
      Major major;

      int classesCount(){
      return List.size();

      String getMajor(){
      return major.getName();

      (hmmm...maybe I'm making it too complicated here....)

      Then, when the new Student is initialized, if some fields are not provided by the "client" (this might be an automated process as well, don't forget) then you make those fields Null Objects. For example

      class NullRegistrationInfo extends RegistrationInfo { ...

      int getClassesCount {
      return 0;

      String getMajor() {
      return "Not signed up for any classes.";

      Finally, you could always throw an Exception from the static constructor if the client doesn't provide the right number of arguments.

      I am not an professional java programmer, just working my way up to that point...so if anyone wants to critique my answer please go crazy!
      • I always check user input through the UI layer. They don't get to create a new Student unless they provide all the right info from the get-go :)

        That's my leaning- get the data from the user, assume they are baboons banging on the keyboard, and massage. Only after it has been inspected will I fold the data into my data structures.

        But I'm interested in this Static Factory pattern- but I don't entirely understand.

        Is the static factory (our Registrar class) an extension of the User Interface idea?
        For example, the Registrar class has a "getDataFromUser()" method that gets the data, and based upon what is or isn't null then calls getCollegeStudent( p1, p2, p3, p4)?

        AFter that, I like how they are all "held" as Students- thats nice and OO.
        • Is the static factory (our Registrar class) an extension of the User Interface idea?
          For example, the Registrar class has a "getDataFromUser()" method that gets the data, and based upon what is or isn't null then calls getCollegeStudent( p1, p2, p3, p4)?

          (All this following assumes we're talking about java. I don't know much about C++ except that it's hard :) )

          The static factory is like a function that returns whatever object you want to create. That way you can throw exceptions -IllegalArgumentException - or whatever when the user doesn't provide enough info. You can't throw exceptions from class constructors (in java). So yeah it is like the UI concept. However ideally you still want to have a layer of abstraction that checks the user input before it even gets to the Static Factory.

          The static factory examines the arguments passed to it (be they strings, a Person object, or nothing for a default) and "builds" the corresponding correct object. The object returned always has the same type (a common interface or superclass) regardless of the parameters, so, in java, you sometimes have to cast it back up to the expected class (someone want to correct me on this one?).

          You can also have static factories accept type codes instead of parameters, for example,

          Person hsStudent = Registrar.getStudent(Education.HIGH_SCHOOL)
          Person clgStudent = Registrar.getStudent(Education.COLLEGE)

          I should say that I haven't created commercial APIs, I've just used the Java class libraries, so somebody else will have to pick up from here.

          • Okay- I dig it now.

            Super-dupe. I didn't realize that about exceptions not allowed in constructors... very sneaky- I like it a lot.

            Yes, you have to cast UP, but not down(towards Object)- that's implicit. like when you grab stuff from vectors- you cast.

            When using pointers in C, you do more casting than an anxious fisherman.
  • I think GM's question was more of a "why bother" question rather than a "what is it" question.

    Of course, anybody who has waded through pages of spaghetti code knows the advantages of oop over procedural code intuitively.

    Still, you might want to take a look at this guy's [slashdot.org] site [geocities.com] and all the arguments he makes against OOP. I would be interested to hear your reaction.
    • I have read Tablizers stuff (well, skimmed over it), and he makes some solid points, but I haven't taken time to really study it enough to give my opinion. Perhaps this weekend I'll look into it more.
  • I could get into this. I'm feeling more and more like a procedural guy living in a OO world :)

    I've done some OO programming, mainly in school, but when I need to turn out code, I end up going procedural, cause OO just seems like such overkill for most of what I'd want to do. I could use a refresher :)
  • My language of choice is Objective C. It implements most of the true OO features --- objects, encapsulation, polymorphism, inheritance, etc. --- while remaining closer to C (IMHO) than either C++ or Java do, and while changing less overall.

    • I love Objective C, but I don't know if it's features far outweigh Java. Java is almost better supported and about as fast. It's got broader support and , unless your using OS X w/NS classes, Java has a better native API. Things like Apache XML support, web services support, development enviornments... etc.

      Also, I just hate header files. Java is nice that way.

      It's probably the language that should of been, especially over C++.

  • void main()
    TV tvObject = new TV(); //just allocating mem
    tvObject.changeChannel( 2 );
    To create a second tv:
    TV tvObject2 = new TV()
    (to make sure I've got the syntax right for what you are 'splainin') To change channel on second tv:
    tvObject2.changeChannel( 2 );
    • And if you don't know how many objects you are going to create you can do the following

      import java.util.*;

      Class TvDemo {

      Class Tv {

      public static void main(String args[]){

      boolean keepAddingTVs;
      List tvroom;

      List tvroom = new ArrayList();

      keepAddingTVs = true

      tvroom.add(new TV());
      // The new TV() is an instance of an "anonymous" object. In java the virtual machine keeps track of the distinct object for you.

      keepAddingTVs = AskUser_KeepAddingTVs();
      // Query user if you want to continue (Use your imagination).

      System.out.println("Wow, you have " + tvroom.size() + " tvs in your tv room.");


      By using Lists, Vectors and similar data structures you can avoid having to clutter your code with confusing names like tv1, tv2 ad nauseum. I don't think procedural languages have List strucutres, do they? If they do, it is in the form of arrays which typcially have to be statically dimensioned at coding. Someone correct me if I'm wrong.
      • Yeah, the pseudo code works, but I'm not talking about collections or anything advanced like that. Remember, this is just an intro to OOP (I haven't even gotten into hardcore Java syntax, yet).
    • yup, you got the idea.

panic: kernel trap (ignored)