Java Object-Oriented Programming (OOP) is at the core of Java. before you begin writing simple Java programs first we need to understand its basic principles.


The three OOP Principles

  • Encapsulation 
  • Inheritance
  • Polymorphism


Encapsulation - Encapsulation is the mechanism that connects code and the data and keeps both safes from outside interference and misuse. 


Method or variable in a class can be marked as private or public variable or method is accessible outside of the class. In the private case variable or method is only can access in a same class or code.


File structure

example/
┣ Example.java
┗ Person.java

Person.java


package example;

/**
 *
 * @author Rathorji
 */
public class Person {

    private String name;
    private String idNum;
    private int age;

    public int getAge() {
        return age;
    }

    public String getName() {
        return name;
    }

    public String getIdNum() {
        return idNum;
    }

    public void setAge(int newAge) {
        age = newAge;
    }

    public void setName(String newName) {
        name = newName;
    }

    public void setIdNum(String newId) {
        idNum = newId;
    }
}


Example.java

package example;

/**
 *
 * @author Rathorji
 */
public class Example {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        Person person = new Person();

        person.setName("Rathorji");
        person.setAge(22);
        person.setIdNum("testId23");

        System.out.print("Name : " + person.getName() + " Age : " + person.getAge());
    }

}

Output:

Name : Rathorji Age : 22

I am using Netbeans IDE





Inheritance: This is the process in which one object acquires the properties of another object.


Use the extend Keyword


Syntax

class ClassA{
   .....
   .....
}
class ClassB extends ClassA{
   .....
   .....
}



Polymorphism: This is a feature that allows one interface to be used for a general class of action


Example:

public interface Person{}
public class Animal{}
public class Lion extends Animal implements Person{}

We will learn more about polymorphism in later