Introduction to Object-Oriented Programming
Introduction to Object-Oriented Programming
Oriented Programming, to understand the world of object-oriented programming, look at the world
around you for a moment. You might see vacuum cleaners, coffee makers, ceiling fans, and a
host of other objects. Everywhere you look, there are objects surround you. Some of these
objects, such as cameras, operate independently. Some, such as telephones and answering
machines, interact with one another. Some objects contain data that persists between uses, like
the address book in a cell phone. Some objects contain other objects, like an icemaker inside of
the freezer. Many objects are similar in function but different in purpose. Bathtubs and kitchen
sinks, for example, both provide water and are used for cleaning. But it is a rare occasion when
you will take a bath in the kitchen sink or wash your dishes in the tub. However, the bathtub and
the kitchen sink in your house probably share the same plumbing. Certainly, they share a
common interface: hot and cold water knobs, a faucet, and a drain. When you think about it, what
is the difference between a sink and a bathtub? The location? The size of the basin? Their heights
off the ground? How many more similarities are there than differences?
To create a class, use the keyword class:
Create a class named "Main" with a variable x:
public class Main {
int x = 5;
}
Create an Object
In Java, an object is created from a class. We
have already created the class named Main, so
now we can use this to create objects.
To create an object of Main, specify the class
name, followed by the object name, and use the
keyword new:
Create an object called "myObj" and print the
value of x
:
public class Main {
int x = 5;