Java

Java - Object & Classes

Java - Object & Classes

Java is an object-oriented language featuring classes that allow developers to model real-world objects and their associated behaviors. 

Objects: 
In Java, an object is an instance of a class. An object has a state and behavior. The state of an object is represented by its fields (also known as instance variables), and the behavior of an object is represented by its methods. 
For example, a car object has the state of its current speed, color, and fuel level. The behavior of a car object would be to start the engine, accelerate, and brake. 

Creation of Object: 
The object is created by using the “new" keyword, followed by the class name and parentheses. 
Example: 

Car myCar = new Car();

This creates a new object of the class "Car" and assigns it to the variable "myCar". 

Classes: 
A class is a blueprint for creating objects. A class defines the fields (instance variables) and methods that an object of that class can have. A class can also define constructors, which are methods used to create objects of that class 

Example: ”Car" might define the fields "speed", "color", and "fuelLevel" and the methods "startEngine", "accelerate", and "brake" 
Creation of Class: 

class Car { 
// class body goes here 
} 

Speed, colour, fuelLevel are the fields in the class Car. 

class Car { 
int speed; 
String colour; 
double fuelLevel; 
// other fields and methods 
} 

Methods 
Methods are used to define the behavior of an object. Methods are defined inside the class body, just like fields. 

class Car { 
// fields 
void startEngine() { 
// code to start the engine 
} 
void accelerate() { 
// code to accelerate 
} 
void brake() { 
// code to brake 
} 
} 

 

Top course recommendations for you

    Turbo C++
    1 hrs
    Beginner
    13.6K+ Learners
    4.44  (494)
    Dev C++ Tutorial
    1 hrs
    Beginner
    5.6K+ Learners
    4.46  (202)
    Hashing in Java
    2 hrs
    Intermediate
    5.7K+ Learners
    4.42  (130)
    Eclipse Tutorial
    1 hrs
    Beginner
    2.6K+ Learners
    4.45  (107)
    NoSQL Database
    2 hrs
    Beginner
    9.1K+ Learners
    4.56  (394)
    What is SQL Triggers?
    1 hrs
    Intermediate
    10.9K+ Learners
    4.44  (383)
    WordPress with Docker
    1 hrs
    Beginner
    7.1K+ Learners
    4.49  (292)
    C++ Tutorial
    2 hrs
    Beginner
    43.9K+ Learners
    4.46  (2124)
    OOPs Concepts in C++
    2 hrs
    Beginner
    27.6K+ Learners
    4.46  (1517)
    Robotic Process Automation
    3 hrs
    Beginner
    10.8K+ Learners
    4.62  (487)