Lec 02
Lec 02
Programming
Software-Engineering
What is OOP?
Here, fields (variables) and methods represent the state and behavior of
the object respectively.
We have used the new keyword along with the constructor of the
class to create an object. Constructors are similar to methods
and have the same name as the class. For example, Bicycle() is
the constructor of the Bicycle class.
Here, sports Bicycle and touring Bicycle are the names of
objects. We can use them to access fields and methods of the
class.
As you can see, we have created two objects of the class. We can
create multiple objects of a single class in Java.
Access Members of a Class
We can use the name of objects along with the . operator to access
members of a class. For example,
Access Members of a Class
In the above program, we have created a class named Lamp. It contains a variable: isOn
and two methods: turnOn() and turnOff().
Inside the Main class, we have created two objects: led and halogen of the Lamp class. We
then used the objects to call the methods of the class.
led.turnOn() - It sets the isOn variable to true and prints the output.
halogen.turnOff() - It sets the isOn variable to false and prints the output.
The variable isOn defined inside the class is also called an instance variable. It is because
when we create an object of the class, it is called an instance of the class. And, each
instance will have its own copy of the variable.
That is, led and halogen objects will have their own copy of the isOn variable.
Example: Create objects inside the same class