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
What is an Object?
An object contains
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
|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
instance variables, behavior using
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
Objects are instantiated from
classes. Classes are the
blue prints or
templates used to create/instantiate objects.
Light bulb example software object
|Light Bulb||voltage = 230V ,type = galss halogen, price = $5.50||on, off|
Benefits of using Objects
Black Box(Data Hiding): By interacting only with an object's methods, the complexity and internal implementation remains hidden from the outside world.
Code re-use: If an object already exists(written by another programmer), you can use that object in your program.
Modularity: The source code for an object can be written and maintained independently of the source code for other objects.
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
In the example above, the
Computer. Laptop, Desktop and Server are
subclasses of Computer.