web analytics

Java OOP

Object-oriented programming (OOP) is a programming paradigm that focuses on the concept of “objects” as the fundamental unit of programming. In OOP, an object is a self-contained entity that contains both data and behavior.

Java is an object-oriented programming language, meaning that it is based on the OOP paradigm. In Java, objects are created from templates called “classes”. A class defines the structure and behavior of an object, including its data fields (also called instance variables) and methods.

Here is an example of a simple class in Java:

public class Student {
// instance variables
private String name;
private int age;
private String major;

// constructor
public Student(String name, int age, String major) {
this.name = name;
this.age = age;
this.major = major;

// method
public void study() {
System.out.println(name + " is studying for their " + major + " degree.");

This class defines a Student object with three instance variables: name, age, and major. It also has a constructor, which is a special method that is used to create a new instance of the Student class. The constructor takes three arguments: name, age, and major, and assigns them to the corresponding instance variables.

The class also has a method called study(), which prints a message to the console indicating that the student is studying for their degree.

To create a new Student object, you can use the new keyword and the constructor:

Student s1 = new Student("Alice", 21, "Computer Science");

This creates a new Student object with the name “Alice”, age 21, and major “Computer Science”.

To call the study() method on the Student object, you can use the following syntax:


This will print the message “Alice is studying for their Computer Science degree.” to the console.

OOP allows you to model real-world objects in your code and encapsulate their data and behavior into self-contained entities. It also enables you to create relationships between objects, such as inheritance (where one object is a subclass of another object and inherits its behavior) and polymorphism (where different objects can respond to the same method call in different ways).