Short Encapsulation Example in Java
Encapsulation is demonstrated as an OOPs concept in Java. Here, the variable “name” is kept private or “encapsulated.”
package com.javatpoint;
public class Student {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name
}
}
//save as Test.java
package com.javatpoint;
class Test {
public static void main(String[] args) {
Student s = new Student();
s.setName(“vijay”);
System.out.println(s.getName());
}
}
Example of Inheritance in Java
It’s quite simple to achieve inheritance as an OOPs concept in Java. Inheritance can be as easy as using the extends keyword:
class Mammal {
}
class Aardvark extends Mammal {
}
Short Example of Polymorphism in Java
In the example below of polymorphism as an OOPs concept in Java, we have two classes: Person and Employee. The Employee class inherits from the Person class by using the keyword extends. Here, the child class overrides the parent class.
class Person {
void walk() {
System.out.println(“Can Run….”);
}
}
class Employee extends Person {
void walk() {
System.out.println(“Running Fast…”);
}
public static void main(String arg[]) {
Person p = new Employee(); //upcasting
p.walk();
}
}
Leave A Comment