Object Oriented Features

Three characteristics of object-oriented: encapsulation, inheritance, polymorphism

1. Package:

  • is the main characteristic of the concept of objects and classes
  • Encapsulate objective things into abstract classes, and classes can operate their own data and methods only by trusted classes or objects, and hide untrustworthy ones.

2. Inheritance

  • Inheritance refers to the ability to use all the functionality of an existing class and extend those functionality without having to rewrite the original class.
  • New classes created through inheritance are called "subclasses" or "derived classes". The class that is inherited is called the "base class", "parent class" or "super class".

3. Polymorphism

  • Polymorphism means that a subclass object can be directly assigned to a parent class variable, but the behavior characteristics of the subclass are still displayed at runtime, which means that objects of the same class may exhibit different behavior characteristics at runtime.
  • In OO methods, it often means that properties or operations defined in a general class can have different data types or exhibit different behaviors after being inherited by a special class.
  • Early binding: Binding before the program runs, implemented by the compiler and linker, also known as static binding. Such as static methods and final methods.
  • Late binding: Binding according to the type of the object at runtime is done by the runtime system. Also called dynamic binding or runtime binding.
  • Code example :

 

// car interface   
interface Car {   
    // car name   
    String getName();   
  
    // get the price of the car   
    int getPrice();   
}   
  
// BMW   
class BMW implements Car {   
    public String getName() {   
        return "BMW";   
    }   
  
    public int getPrice() {   
        return 300000;   
    }   
}   
  
// Chery QQ   
class CheryQQ implements Car {   
    public String getName() {   
        return "CheryQQ";   
    }   
  
    public int getPrice() {   
        return 20000;   
    }   
}   
  
// car dealership   
public class CarShop {   
    // car sales revenue   
    private int money = 0;   
  
    // sell a car   
    public void sellCar(Car car) {   
        System.out.println("车型:" + car.getName() + "  单价:" + car.getPrice());   
        // Increase the revenue from the selling price of the car   
        money += car.getPrice();   
    }   
  
    // total car sales revenue   
    public int getMoney() {   
        return money;   
    }   
  
    public static void main(String[] args) {   
        CarShop aShop = new CarShop();   
        // sell a BMW   
        aShop.sellCar(new BMW());   
        // sell a Chery QQ   
        aShop.sellCar(new CheryQQ());   
        System.out.println("Total revenue: " + aShop.getMoney());   
    }   
}  

 

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326718801&siteId=291194637