Classes and Objects

Java is an object oriented programming language. In this section we learn what it means for a programming language to be object oriented.

We are going to learn about objects, classes, inheritance, interfaces and packages.

What is an Object?

An object contains state and behaviour. Software objects are used to model the real-world objects.

Real-World Object Examples

1. Computer
2. Ball
3. Cat
4. Light Bulb
5. etc
Object States Behaviors
Cat name, color, breed, age meow, nap, purr
Ball color, type, size bounce, roll
Computer price, speed, color, type calculate, startup, shutdown
Light Bulb voltage,type, price on, off

Objects represent state using special type of variables called fields or instance variables, behavior using functions or methods.

When objects hide their internal state and require all interaction to be performed through the object's methods, this is known as encapsulation. Encapsulation is a fundamental principle of object-oriented programming.

When objects are created the process is called instantiation. Objects are instantiated from classes. Classes are the blue prints or templates used to create/instantiate objects.

Light bulb example software object

Object States Behaviors
Light Bulb voltage = 230V ,type = galss halogen, price = $5.50 on, off

Benefits of using Objects

  1. Black Box (Data Hiding): By interacting only with an object's methods, the complexity and internal implementation remains hidden from the outside world.
  2. Code re-use: If an object already exists(written by another programmer), you can use that object in your program.
  3. Modularity: The source code for an object can be written and maintained independently of the source code for other objects.
  4. Plugability and debugging ease: If an object turns out to be problematic, you can remove it from your application and plug in a different object as replacement.

What is Inheritance?

Object-oriented programming allows classes to inherit commonly used state and behavior from other classes.

Take for example tablets, laptops, servers and desktop computers they all share characteristics of computers(memory size, hard drive size, processing speed)

Example computer inheritance hierarchy

Each class is allowed to have one direct superclass, and each superclass has the potential for an unlimited number of subclasses.

In the example above, the superclass is Computer. Laptop, Desktop and Server are subclasses of Computer.

results matching ""

    No results matching ""