Java object and classes examples

Java Class and Objects

Java is an object-oriented programming language. The core concept of the object-oriented approach is to break complex problems into smaller objects.

An object is any entity that has a state and behavior. For example, a bicycle is an object. It has

  • States: idle, first gear, etc
  • Behaviors: braking, accelerating, etc.

Before we learn about objects, let’s first know about classes in Java.

Java Class

A class is a blueprint for the object. Before we create an object, we first need to define the class.

We can think of the class as a sketch (prototype) of a house. It contains all the details about the floors, doors, windows, etc. Based on these descriptions we build the house. House is the object.

Since many houses can be made from the same description, we can create many objects from a class.

Create a class in Java

We can create a class in Java using the class keyword. For example,

Here, fields (variables) and methods represent the state and behavior of the object respectively.

For our bicycle object, we can create the class as

In the above example, we have created a class named Bicycle . It contains a field named gear and a method named braking() .

Here, Bicycle is a prototype. Now, we can create any number of bicycles using the prototype. And, all the bicycles will share the fields and methods of the prototype.

Note: We have used keywords private and public . These are known as access modifiers. To learn more, visit Java access modifiers.

Java Objects

An object is called an instance of a class. For example, suppose Bicycle is a class then MountainBicycle , SportsBicycle , TouringBicycle , etc can be considered as objects of the class.

Creating an Object in Java

Here is how we can create an object of a class.

className object = new className(); // for Bicycle class Bicycle sportsBicycle = new Bicycle(); Bicycle touringBicycle = new Bicycle();

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. To learn more, visit Java Constructors.

Here, sportsBicycle and touringBicycle 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.

Note: Fields and methods of a class are also called members of the class.

Access Members of a Class

We can use the name of objects along with the . operator to access members of a class. For example,

class Bicycle < // field of class int gear = 5; // method of class void braking() < . >> // create object Bicycle sportsBicycle = new Bicycle(); // access field and method sportsBicycle.gear; sportsBicycle.braking();

In the above example, we have created a class named Bicycle . It includes a field named gear and a method named braking() . Notice the statement,

Bicycle sportsBicycle = new Bicycle();

Here, we have created an object of Bicycle named sportsBicycle . We then use the object to access the field and method of the class.

  • sportsBicycle.gear — access the field gear
  • sportsBicycle.braking() — access the method braking()
Читайте также:  Org junit assert java

We have mentioned the word method quite a few times. You will learn about Java methods in detail in the next chapter.

Now that we understand what is class and object. Let’s see a fully working example.

Example: Java Class and Objects

class Lamp < // stores the value for light // true if light is on // false if light is off boolean isOn; // method to turn on the light void turnOn() < isOn = true; System.out.println("Light on? " + isOn); >// method to turnoff the light void turnOff() < isOn = false; System.out.println("Light on? " + isOn); >> class Main < public static void main(String[] args) < // create objects led and halogen Lamp led = new Lamp(); Lamp halogen = new Lamp(); // turn on the light by // calling method turnOn() led.turnOn(); // turn off the light by // calling method turnOff() halogen.turnOff(); >>
Light on? true Light on? false

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

Note that in the previous example, we have created objects inside another class and accessed the members from that class.

However, we can also create objects inside the same class.

class Lamp < // stores the value for light // true if light is on // false if light is off boolean isOn; // method to turn on the light void turnOn() < isOn = true; System.out.println("Light on? " + isOn); >public static void main(String[] args) < // create an object of Lamp Lamp led = new Lamp(); // access method using object led.turnOn(); >>

Here, we are creating the object inside the main() method of the same class.

Table of Contents

Источник

Java Classes and Objects

Everything in Java is associated with classes and objects, along with its attributes and methods. For example: in real life, a car is an object. The car has attributes, such as weight and color, and methods, such as drive and brake.

A Class is like an object constructor, or a «blueprint» for creating objects.

Create a Class

To create a class, use the keyword class :

Main.java

Create a class named » Main » with a variable x:

Remember from the Java Syntax chapter that a class should always start with an uppercase first letter, and that the name of the java file should match the class name.

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.

Читайте также:  Java exceptions good practices

To create an object of Main , specify the class name, followed by the object name, and use the keyword new :

Example

Create an object called » myObj » and print the value of x:

Multiple Objects

You can create multiple objects of one class:

Example

Create two objects of Main :

Using Multiple Classes

You can also create an object of a class and access it in another class. This is often used for better organization of classes (one class has all the attributes and methods, while the other class holds the main() method (code to be executed)).

Remember that the name of the java file should match the class name. In this example, we have created two files in the same directory/folder:

Main.java

Second.java

When both files have been compiled:

You will learn much more about classes and objects in the next chapters.

Источник

Java object and classes examples

  • Introduction to Java
  • The complete History of Java Programming Language
  • C++ vs Java vs Python
  • How to Download and Install Java for 64 bit machine?
  • Setting up the environment in Java
  • How to Download and Install Eclipse on Windows?
  • JDK in Java
  • How JVM Works – JVM Architecture?
  • Differences between JDK, JRE and JVM
  • Just In Time Compiler
  • Difference between JIT and JVM in Java
  • Difference between Byte Code and Machine Code
  • How is Java platform independent?
  • Decision Making in Java (if, if-else, switch, break, continue, jump)
  • Java if statement with Examples
  • Java if-else
  • Java if-else-if ladder with Examples
  • Loops in Java
  • For Loop in Java
  • Java while loop with Examples
  • Java do-while loop with Examples
  • For-each loop in Java
  • Continue Statement in Java
  • Break statement in Java
  • Usage of Break keyword in Java
  • return keyword in Java
  • Object Oriented Programming (OOPs) Concept in Java
  • Why Java is not a purely Object-Oriented Language?
  • Classes and Objects in Java
  • Naming Conventions in Java
  • Java Methods
  • Access Modifiers in Java
  • Java Constructors
  • Four Main Object Oriented Programming Concepts of Java
  • Inheritance in Java
  • Abstraction in Java
  • Encapsulation in Java
  • Polymorphism in Java
  • Interfaces in Java
  • ‘this’ reference in Java

Источник

What is Class and Object in Java OOPS? Learn with Example

Classes and Objects in Java are the fundamental components of OOP’s. Often there is a confusion between classes and objects. In this tutorial, we try to tell you the difference between Class and Object in Java.

First, let’s understand what they are,

What is Class in Java?

Class are a blueprint or a set of instructions to build a specific type of object. It is a basic concept of Object-Oriented Programming which revolve around the real-life entities. Class in Java determines how an object will behave and what the object will contain.

Syntax of Class in Java

What is Object in Java?

Object is an instance of a class. An object in OOPS is nothing but a self-contained component which consists of methods and properties to make a particular type of data useful. For example color name, table, bag, barking. When you send a message to an object, you are asking the object to invoke or execute one of its methods as defined in the class.

From a programming point of view, an object in OOPS can include a data structure, a variable, or a function. It has a memory location allocated. Java Objects are designed as class hierarchies.

Object Syntax in Java

ClassName ReferenceVariable = new ClassName();

What is the Difference Between Object and Class in Java?

A Class in object oriented programming is a blueprint or prototype that defines the variables and the methods (functions) common to all Java Objects of a certain kind.

Читайте также:  Assigning array to array php

An object in OOPS is a specimen of a class. Software objects are often used to model real-world objects you find in everyday life.

Click here if the video is not accessible

Understand the concept of Java Classes and Objects with an example.

Let’s take an example of developing a pet management system, specially meant for dogs. You will need various information about the dogs like different breeds of the dogs, the age, size, etc.

You need to model real-life beings, i.e., dogs into software entities.

Java Classes and Objects

Moreover, the million dollar question is, how you design such software?

Here is the solution-

First, let’s do an exercise.

You can see the picture of three different breeds of dogs below.

Java Classes and Objects

Stop here right now! List down the differences between them.

Some of the differences you might have listed out maybe breed, age, size, color, etc. If you think for a minute, these differences are also some common characteristics shared by these dogs. These characteristics (breed, age, size, color) can form a data members for your object.

Java Classes and Objects

Next, list out the common behaviors of these dogs like sleep, sit, eat, etc. So these will be the actions of our software objects.

Java Classes and Objects

So far we have defined following things,

  • Class – Dogs
  • Data members or objects– size, age, color, breed, etc.
  • Methods– eat, sleep, sit and run.

Java Classes and Objects

Now, for different values of data members (breed size, age, and color) in Java class, you will get different dog objects.

Java Classes and Objects

You can design any program using this OOPs approach.

While creating a class, one must follow the following principles.

  • Single Responsibility Principle (SRP)- A class should have only one reason to change
  • Open Closed Responsibility (OCP)- It should be able to extend any classes without modifying it
  • Liskov Substitution Responsibility (LSR)- Derived classes must be substitutable for their base classes
  • Dependency Inversion Principle (DIP)- Depend on abstraction and not on concretions
  • Interface Segregation Principle (ISP)- Prepare fine grained interfaces that are client specific.

Classes and Objects in Java Example Programs

// Class Declaration public class Dog < // Instance Variables String breed; String size; int age; String color; // method 1 public String getInfo() < return ("Breed is: "+breed+" Size is:"+size+" Age is:"+age+" color is: "+color); >public static void main(String[] args) < Dog maltese = new Dog(); maltese.breed="Maltese"; maltese.size="Small"; maltese.age=2; maltese.color="white"; System.out.println(maltese.getInfo()); >>
Breed is: Maltese Size is:Small Age is:2 color is: white

Java Object and Class Example: main outside class

In previous program, we are creating main() method inside the class. Now, we create classes and define main() method in another class. This is a better way than previous one.

// Class Declaration class Dog < // Instance Variables String breed; String size; int age; String color; // method 1 public String getInfo() < return ("Breed is: "+breed+" Size is:"+size+" Age is:"+age+" color is: "+color); >> public class Execute < public static void main(String[] args) < Dog maltese = new Dog(); maltese.breed="Maltese"; maltese.size="Small"; maltese.age=2; maltese.color="white"; System.out.println(maltese.getInfo()); >>
Breed is: Maltese Size is:Small Age is:2 color is: white

Summary:

  • Java Class is an entity that determines how Java Objects will behave and what objects will contain
  • A Java object is a self-contained component which consists of methods and properties to make certain type of data useful
  • A class system allows the program to define a new class (derived class) in terms of an existing class (superclass) by using a technique like inheritance, overriding and augmenting.

Источник

Оцените статью