email me at borlaj@portlandschools.org

Loading
notes previous (10/<10) submit the dump links  
 

Classes and objects

 

Objects

Objects are just things, like a ball, submarine, or a dog are actual objects. Object-oriented programming like C++ and Java sort all there program in objects.

There are many advantages to program in this way:

  • More natural - just like the real world, where we sort things by what they are. Ie, in this room, there are 25 computers, 30 chairs etc.
  • Scalable - objects can extend other objects, just like the real world. German shepherd extends dog which extends animal. This also is a very natural relationship.
  • Allows code to be more sharable. One dog defined somewhere will be the same as a dog needed else where.
  • Great for large programming projects. People can tackle different objects.

Ways we could use objects:

  • In our game, if we wanted to have multiple evil guys, we could have had an evil guy class and made several instances of it.
  • In an akeroid? game where you have multiple blocks, that would be a pain to keep draw and keep track of each block, so we could use an object array.

Classes

A class is a definition of a object. Just like Java has built in types like String. We can define our own type of variable or object using classes. They are blueprints for objects.

Classes can have fields and methods. Fields store class information, such as Dog's age, color, gender, etc. Methods perform action.

 

For example: my dog Luna is an example of dog. The idea of a dog is not an actual animal, but just an idea, while Luna is a real example of a dog.

In this case we would define a class Dog and Luna would be an instance of dog.

 

Dog luna = new Dog();

luna.age=2;
luna.weight=55;
luna.name="luna";
luna.color="blue";

luna.bark();
luna.eatFood(.5);
luna.dump(); //this might return .3 lbs            
            

Lets make this happen in BlueJ. Create a class Dog that will keep track of all these things and have these methods.

 

Lets create a class Kennel that will create instances of 2 dogs.