Skip to content

Instantly share code, notes, and snippets.

Created September 8, 2021 18:37
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save MananAmin/74f7b6fc2936d7356127983f3d3cb1bb to your computer and use it in GitHub Desktop.
basics of OOP in java
package com.oop;
import com.oop.encapsulation.EncapsClass;
import java.util.Calendar;
public class Main {
public static void main(String[] args) {
// class properties and methods
Employee em = new Employee(); = "Martin Garrix";
em.birth_year = 1995;
System.out.println( + " is almost "+ em.getAge(true)+ " days old");
// constructor
Employer ey1 = new Employer("Google");
Employer ey2 = new Employer("Facebook");
System.out.println(" Total companies "+Employer.count);
// inheritance
Person p1 = new Person("bob",2000);
Person p2 = new Person("sana",2004);
Person p3 = new Person();
Manager m1 = new Manager("Raj",1996,"Cloud");
Person pm = new Manager("Dinesh",2002,"IT");
System.out.println( +" is "+m1.getAge()+" years old.");
// Encapsulation and access modifiers
/* public everywhere
protected class and child class
default within package
private within class
EncapsClass encap = new EncapsClass();
// Abstraction
Tesla t1 = new Tesla();
// Interfaces
BMW b1 = new BMW();
class Employee {
String name;
int birth_year;
// Compile time polymorphism
int getAge(){
return Math.abs(birth_year - Calendar.getInstance().get(Calendar.YEAR));
int getAge(boolean in_days){
return 365*Math.abs(birth_year - Calendar.getInstance().get(Calendar.YEAR));
class Employer{
String name;
// static use for Class property which shared by all the instances of class
static int count;
// Constructor
public Employer(String name){ = name;
// Inheritance
class Person {
protected String name;
int birth_year;
static int population;
public Person(){
public Person(String name,int year){
this(); = name;
this.birth_year =year;
int getAge() {
return Math.abs(birth_year - Calendar.getInstance().get(Calendar.YEAR));
String walk(){
return +" is walking";
String salary(){
return +" is making "+ this.getSalary()+" a year.";
// only access within class
private int getSalary(){
return 100000;
class Manager extends Person{
String department;
public Manager(String name,int year,String department){
this.department = department;
String walk(){
return +" is walking in "+this.department+" department.";
// abstraction
abstract class Car {
String brand;
protected int price;
abstract String getEngine();
void startCar(){
System.out.println("Car is starting ");
class Tesla extends Car{
void startCar(){
System.out.println("Tesla is started");
public String getEngine(){
return "Electric Engine";
// Interfaces
interface Bike {
void start();
class BMW implements Bike{
public void start() {
System.out.println("BMW is started ");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment