Mark As Completed Discussion

Object-Oriented Programming

Object-Oriented Programming (OOP) is a programming paradigm that organizes code into objects, which are instances of classes. In Java, everything is an object, and classes are used to define the properties and behaviors of objects.

One of the key principles of OOP is encapsulation, which means hiding the internal details of an object and providing access to them through public methods. This allows for better control and organization of code, as well as data protection.

Let's take a look at an example of OOP in Java:

TEXT/X-JAVA
1// Example Java code
2public class Person {
3
4    private String name;
5    private int age;
6    
7    // Constructor
8    public Person(String name, int age) {
9        this.name = name;
10        this.age = age;
11    }
12    
13    // Getters and Setters
14    public String getName() {
15        return name;
16    }
17    
18    public void setName(String name) {
19        this.name = name;
20    }
21    
22    public int getAge() {
23        return age;
24    }
25    
26    public void setAge(int age) {
27        this.age = age;
28    }
29    
30    // Method
31    public void sayHello() {
32        System.out.println("Hello, my name is " + name + " and I am " + age + " years old.");
33    }
34}
35
36public class Main {
37    
38    public static void main(String[] args) {
39        // Create an object of the Person class
40        Person person = new Person("John", 25);
41        
42        // Access properties and methods
43        person.sayHello();
44        
45        person.setName("Jane");
46        person.setAge(30);
47        
48        person.sayHello();
49    }
50}

In this example, we have a Person class with private properties name and age. We have also defined a constructor to initialize these properties when creating a new Person object. The class also includes getters and setters to access and modify the properties, as well as a method sayHello() to print a message.

In the Main class, we create a new Person object with the name "John" and age 25. We then call the sayHello() method to output a message. After that, we use the setters to change the name to "Jane" and age to 30, and again call the sayHello() method.

This is just a simple example to illustrate the concept of OOP in Java. In reality, classes and objects can contain much more complex properties and methods, and can be used to build sophisticated and modular code structures.

By using OOP principles in Java, such as encapsulation, inheritance, and polymorphism, you can create well-organized and maintainable code. OOP allows you to break down complex problems into smaller, more manageable pieces, and build reusable components for efficient development. It is a key component of Java programming and essential knowledge for any Java developer.

JAVA
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment