Classes and Objects

description of image


Java Classes


Before we can create objects, we need to define a class. It acts as a blueprint for the object.

Think of a class as a blueprint of a house. It contains all the details about the floors, doors, windows etc. Based on these
descriptions we build the house. The actual physical house is the object.

In Java, we use the class keyword to Define a class.

For example,

Class ClassName {

}

If you have noticed, we have used the same structure in all of our previous examples.

A class can contain:

Fields – to store data

Methods – to perform tasks on fields



Java Objects


To access the fields and methods of a class, we need to create objects of the class. Create Objects

An object is called an instance of a class. Here’s how we can create an object.

ClassName object = new ClassName();

Let’s create an object from the Bicycle class we created in the last page.

Bicycle bike1 = new Bicycle();

Now, the bike1 objects can access fields and methods of the class. We will see a working example of It next.

Access Fields and Methods using Object

We use the name of objects along with the . operator to access fields and methods of a class



Access Fields and Methods using Object


● We use the name of objects along with the . operator to access fields and methods of a class.


● Here, we have created class named called Bicycle that has field and method



Quiz


Question Text