FRIHOST FORUMS SEARCH FAQ TOS BLOGS COMPETITIONS
You are invited to Log in or Register a free Frihost Account!


having difficulties understanding OOP





davidv
so in the near future (roughly 17 days) i'll be starting university and studying computer science. i'm very excited and i can't wait to learn all the cool techniques that people use to formulate amazing software tools. so what i thought was, maybe i should get a bit ahead of the class and learn one of the few languages that we'll be taught over the next 3 - 4 years, JAVA.

i've been reading various ebooks that explain the different concepts of OOP and i must say, i just can't stop reading. however there was one thing that did come up and i really couldn't quite understand it. objects. what are they? what are objects?

i know that everything are within classes and each class has their own set of methods that perform particular tasks and each class has fields which are represented by instance variables within the class but outside of methods. i also understand that objects have attributes based on the classes they're in and how objects behave differently based on those attributes but could anyone pin point to me what the object is? is it a collection methods? is it variable? is it a statement? what is an object?

anyway, thanks. i really appreciate anyone that can answer my incredibly trivial question that i ponder hours over, yet fail to comprehend.
Fire Boar
An object is simply an instance of a class. Don't think of classes as "a collection of related functions", think of them as "a template for an object". An example would be good here.

Imagine a "Dog" class. Something like this.

Code:
public class Dog
{
  public final String name;

  public Dog(String name)
  {
    this.name = name;
  }

  public void bark()
  {
    System.out.println(name + " says woof!");
  }
}


Nice and simple. That's a Java class for a Dog. All dogs have a name that (usually) doesn't change, and all dogs can bark. I'm sure dogs can do other things as well, but our dogs are quite simple creatures.

Now we come to objects. We have a sort of template for a Dog, but no actual dogs. I can't tell the class "okay, go ahead and bark". Instead, we create objects that are instances of Dog.

Code:
Dog dog1 = new Dog("Fred");
Dog dog2 = new Dog("Fido");
Dog dog3 = new Dog("Bessie");


Now we have three objects: dog1, dog2 and dog3. These are all instances of the Dog class, and we can use the methods in the Dog class to perform actions on each individual dog. If we had any methods that have other effects, like maybe a flag to decide whether the dog is hungry or not, each dog would be affected separately. So if we had an extra class variable public boolean isHungry; then dog1.isHungry might not necessarily be the same as dog2.isHungry at any given time.

So, objects are instances of classes that are assigned to variables. (END OF "WHAT IS AN OBJECT" SECTION. LESS BASIC STUFF TO FOLLOW.) In the case of Java, all classes are actually by default a superclass of the Object class, so you can also write

Code:
Object something = new Dog("Timmy");


However, from that point on, Java cannot guarantee that what you're working with is really a Dog, it could just as easily be something else, so you only have access to the methods of Object. To compromise you can use casting:

Code:
Object something = new Dog("Timmy");
something.bark()           // Doesn't work!
((Dog) something).bark();  // Works - you're casting "something" to the type Dog, and it really is a dog.
Dog dog = (Dog) something; // Works - again, casting "something" to the type Dog, this time assigning it to a Dog variable.
dog.bark();                // Works, clearly.


However...

Code:
Object something = new String("This isn't a dog!");
Dog dog = (Dog) something; // Runtime error!


Therefore, when casting make sure you know what type your object is. You can do this sort of thing like so:

Code:
Object something = new String("This isn't a dog!");
if (something instanceof Dog)
{
  ((Dog) something).bark();
}
else
{
  System.out.println("You can't make something that's not a dog do doggy things.");
}


There are code patterns that you'll probably learn about (e.g. the visitor pattern) that allow you to do clever stuff based on the type of something whose type is unknown while avoiding casting, which is generally recommended, but that's more advanced.


One final thing. Earlier I said that dog1, dog2 and dog3 are all objects. I kinda lied. Actually, they are all references to an object. The difference is, if we copy dog1 to another variable dog4:

Code:
Dog dog4 = dog1;


Then it's only the reference that is copied: there is still only one object, it's just being pointed to by two different variables. That is, dog1 and dog4 refer to the same dog, and any changes made using one variable will become visible from the other.

This is a Java-specific quirk, though it turns up in other languages. In C++, however, variables are exactly what you define them to be:

Code:
Dog dog1("Fido");
Dog dog2 = dog1;


Here dog2 is a copy of dog1, because dog1 is the actual dog itself. Making changes to one will not affect the other. More common is the Java approach, which in C++ uses pointers:

Code:
Dog * dog1 = new Dog("Fido");
Dog * dog2 = dog1;


The Dog * type in C++ is "pointer to Dog". So here dog1 and dog2 both "point" to the same dog, and changes to one affect the other. C++ is pretty advanced though - the Java way is simple once you understand it and works well in nearly all practical cases. So don't worry if the bit when I started talking about C++ went over your head.
snowboardalliance
Fire Boar said it best, but I'll just add some advice,

If you are reading all that ahead of time and sort of get it, by the time you are actually taught it, you will finally have an "ah ha" moment and really get it. If it doesn't make sense yet, you'll get it eventually. I remember a similar feeling I had when I tried to read up on OOP before taking a high school course.

Good luck!
davidv
That is indeed, very informative and it really gave me a different view on OOP. There are some slabs of information that I couldn't completely understand but I think I'll get it eventually and like you said have a "ah ha" moment (I love those moments).

So in addition to the original post... I have another question. Static. I've read somewhere that when the word static is used, it would mean that we're able to call a method (i'm assuming a method that has static in it) without creating an object within the class that called it. Now I'm just wondering, is using static only limited to methods? Could I use it in classes? If static allows me to call a method without creating an object, why not just use static in everything?

Also, what is an application object? Is that just the entire application that's being executed?

Is the object the actual line of code that creates the object? e.g.

ClassName ObjectName = new ClassName()

or is the object(s), instances of that line?
noobcake
You're right in that you can use static on other things that aren't methods. One place where you'd use the keyword static is when creating global variables in Java. The idea of static things is that they're shared between all instances of that class. Going back to the earlier example of a dog:

Code:

public class Dog
{
  public final String name;

  public Dog(String name)
  {
    this.name = name;
  }

  public void bark()
  {
    System.out.println(name + " says woof!");
  }

  public static void howl(){
    System.out.println("You hear a frightful howl in the distance.");
  }
}


Here I added a simple howl method. It doesn't need a specific Dog object to do it since there isn't anything specific to a Dog which you need to carry out the action, so it's okay to be static. The following is an example usage of the howl method.

Code:

  Dog.howl();


Note however, that we can't do Dog.bark()

Code:

  //The following will produce a compile error
  Dog.bark();


This is because we need a dog's name to be able to bark. The Dog class doesn't have a name on its own. It's just a template for creating dogs, you see. Although technically you could make the name a static member and never have to instantiate a single instance of Dog. (Please avoid the following, it's just for demonstration.)

Code:

public class Dog
{
  public static String name = "unnamed";

  public static void rename(String name)
  {
    Dog.name = name;
  }

  public static void bark()
  {
    System.out.println(name + " says woof!");
  }

  public static void howl(){
    System.out.println("You hear a frightful howl in the distance.");
  }
}


To use this, you'd do the following:

Code:

Dog.rename("Timmy");
Dog.bark();


To answer the second question, "why can't we use static on everything", it's because we often want our objects to be separated from each other. Say you were making an RTS game and you have two grunts. Each of those grunts have their own HP, location, and so on, so you wouldn't want them having to share any of those. It'd be really messy if you had to do the following to avoid them sharing data, not to mention the fact that you'd have to make a copy of this for each grunt you want to create:

Code:

class Grunt1
{
  static int HP;
  static double x_coordinate;
  static double y_coordinate;
}

class Grunt2
{
  static int HP;
  static double x_coordinate;
  static double y_coordinate;
}


I think from the previous example, it should be clear why you wouldn't want to turn everything into static. There are times when static method and members (variables) are useful. For example, when keeping track of how many Dogs have ever been made, static variables are useful for that. The heart of OOP, though, lies in the fact that objects are distinct from each other. That is, Dog1 shouldn't be affected if Dog2 was changed. It keeps everything clean.

As for the latter question:

What exactly does the following do?
Code:
ClassName ObjectName = new ClassName();


Strictly speaking, it's no different from doing
Code:
int counter = 1;


Let's split it into three parts.
[/code]ClassName ObjectName[/code]
What this does is it tells the compiler that "ObjectName" is a variable of type "ClassName". It's just like "counter" is a variable of type "int".

The = sign is the operator for assignment, we assign whatever follows to the variable "ObjectName".

new ClassName() is the way for Java to create new objects from a class. It also calls the Constructor of the class. Constructors are the functions (a.k.a. methods/subroutines) that initialize your objects, in our Dog example, the constructor assigned a name to the newly created Dog. After the object is initialized, we're given the object, and then the = sign from before binds it to the variable.

I hope I helped.

Edit: Added 'static' to the rename method in one of the examples. Thanks for pointing it out, Fire Boar.
iman
Just a tip, while learning OOP, you should also try to learn functional programming.
Even if OOP is essential for a programmer to survive, OOP is still not the best option for everything.
That's a common misconception among OO programmers.
Fire Boar
noobcake wrote:
Code:
public class Dog
{
  public static String name = "unnamed";

  public void rename(String name)
  {
    Dog.name = name;
  }

  public static void bark()
  {
    System.out.println(name + " says woof!");
  }

  public static void howl(){
    System.out.println("You hear a frightful howl in the distance.");
  }
}


To use this, you'd do the following:

Code:

Dog.rename("Timmy");
Dog.bark();


Oop, careful. There is no static keyword before "void rename" in the class definition, so Dog.rename would produce a compile error here. I'm sure that was just a typo, I just want to clear up potential confusion.

Here's something more interesting though. Taking your example, let's suppose only the variable is static.

Code:
public class Dog
{
  public static String name = "unnamed";

  public void rename(String name)
  {
    Dog.name = name;
  }

  public void bark()
  {
    System.out.println(name + " says woof!");
  }
}


Now let's see what happens.

Code:
Dog dog1 = new Dog();
Dog dog2 = new Dog();
dog1.rename("Timmy");
dog1.bark(); // output: "Timmy says woof!"
dog2.rename("Fido");
dog2.bark(); // output: "Fido says woof!"
dog1.bark(); // output: "Fido says woof!"


So a static variable can really be thought of as a "shared property": something that is the same no matter which object you look at. Not to be confused with something that never changes, which is what "final" means. Anything "final" is set once in the constructor and can never be changed thereafter (but may differ from object to object). On the other hand, combining the two gives "final static" variables, which are constants: hard-coded values that are defined once and once only for the entire class, these cannot be changed at run-time at all. As an example, here is how part of the standard java.lang.Math class might look.

Code:
public class Math
{
  public final static double E = 2.718281828459045;
  public final static double PI = 3.141592653589793;

  // ...
}


In this case, Math.PI would always return 3.141592653589793. In fact, the real java.lang.Math is a "public final class", which means that ALL variables are final.

Here's another example of a final class.

Code:
public final class Rectangle
{
  public int x;
  public int y;
  public int width;
  public int height;

  public Rectangle(int x, int y, int width, int height)
  {
    this.x = x;
    this.y = y;
    this.width = width;
    this.height = height;
  }

  // First attempt:
  /*
  public void doubleSize()
  {
    width = width * 2;   // Compile error! Not allowed to change final width!
    height = height * 2; // Compile error! Not allowed to change final height!
  }
  */

  // Proper way:
  public Rectangle doubleSize()
  {
    return new Rectangle(x, y, width * 2, height * 2);
  }
}


Rectangle here is an immutable class, which means there is no way to modify it. This can be pretty useful: suppose you want to use a Rectangle to describe the dimensions of a window. If you gave a mutable (non-final) object, you'd get something like this.

Code:
MutableRectangle r = frame.getDimensions();
r.doubleSize(); // Uh oh!


Suddenly the getDimensions method has indirectly changed the frame to double its original size. For a "get" method, that's a pretty bad thing to do. But in this case it's okay: if you tried to double the size you'd just get a new rectangle.

Code:
Rectangle r = frame.getDimensions();
r = r.doubleSize(); // This is okay.


After the doubleSize call here, r represents a rectangle with the size doubled as before, but the crucial difference is that now frame.getDimensions will return a rectangle with the old dimensions. So getDimensions cannot be used to change the frame.
lightwate
You'll understand it better thorough experience.

In my case, I started programming in my 7th grade (using Q-Basic). later, I installed visual studio and tried to play with visual basic - you know, like how we all played with microsoft word at first. It's pretty much easier with visual basic because of the drag and drop thing, changing object properties and double clicking those objects to code for events. I was amazed at how fast you can make programs with GUI with it. (of course i didn't know these terms backt then Razz)

Then in my high school, we were introduced to flash. I later realized that the 'symbols' used in flash act the same way as those 'objects' in vb. Two years later was my formal OOP class with java and all my past experiences made me understand OOP better.
Related topics
Portuguese Forum
Laws on Cannabis
How do you deal with a boyfriend's soon to be ex-wife?
Should I whack them up?
Popup when leaving site
What's the oldest book you've read?
What is your view on studying the past?
Up to 20 FriH$ + Bonus to know your favourite Candy
savants
stutter
What lanugage should I learn next?
I'm having problems understanding keys
Teachers, and understanding
How do you learn?
Reply to topic    Frihost Forum Index -> Scripting -> Others

FRIHOST HOME | FAQ | TOS | ABOUT US | CONTACT US | SITE MAP
© 2005-2011 Frihost, forums powered by phpBB.