Oops concept in java

GOCOURSE

 OOPS concepts:

Object-Oriented Programming (OOP) is centered on creating classes and objects in Java.

Type of oops concept in java:

  1. classes and object
  2. Inheritance
  3. Polymorphism
  4. Abstraction
  5. Encapsulation

Classes and Object

A blueprint for making objects is a class. It specifies the attributes and actions that should be present in objects belonging to that class. An instance of a class is an object.

Example:

public class Person {    // create class
    private String name;
    private int age;
    
    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }
    
    public String getName() {
        return name;
    }
    
    public int getAge() {
        return age;
    }
    
    public void sayHello() {
        System.out.println("Hello, my name is " + name + " and I am " + age + " years old.");
    }
}

public class Main {
    public static void main(String[] args) {
        Person person1 = new Person("John", 30); // create object
        Person person2 = new Person("Jane", 25);
        
        System.out.println(person1.getName() + " is " + person1.getAge() + " years old.");
        System.out.println(person2.getName() + " is " + person2.getAge() + " years old.");
        
        person1.sayHello();
        person2.sayHello(); // calling
    }
}

Output:

John is 30 years old.
Jane is 25 years old.
Hello, my name is John and I am 30 years old.
Hello, my name is Jane and I am 25 years old.


Our website uses cookies to enhance your experience. Learn More
Accept !

GocourseAI

close
send