Home Python C Language C ++ HTML 5 CSS Javascript Java Kotlin SQL DJango Bootstrap React.js R C# PHP ASP.Net Numpy Dart Pandas Digital Marketing

Classes and Objects


Java Classes and Objects

In Java, a class is a blueprint or template for creating objects. It defines the properties (fields) and behaviors (methods) that objects of that type will have. Here's a basic example of a Java class:


Class:

Example of a simple class in Java:

    public class Car {
        // Attributes
        String brand;
        String color;
        int year;
    
        // Constructor
        public Car(String brand, String color, int year) {
            this.brand = brand;
            this.color = color;
            this.year = year;
        }
    
        // Method
        public void drive() {
            System.out.println("The " + color + " " + year + " " + brand + " is driving.");
        }
    }      

Object:

Example of creating objects in Java:

    public class Main {
        public static void main(String[] args) {
            // Creating objects of class Car
            Car car1 = new Car("Toyota", "Blue", 2020);
            Car car2 = new Car("BMW", "Red", 2019);
            
            // Accessing object methods
            car1.drive(); // Output: The Blue 2020 Toyota is driving.
            car2.drive(); // Output: The Red 2019 BMW is driving.
        }
    }
  

In this example, Car is a class with attributes like brand, color, and year, and a method drive(). car1 and car2 are objects (instances) of the Car class, each with its own set of attribute values.



Advertisement





Q3 Schools : India


Online Complier

HTML 5

Python

java

C++

C

JavaScript

Website Development

HTML

CSS

JavaScript

Python

SQL

Campus Learning

C

C#

java