Java object-oriented features
Java object-oriented features: "encapsulation, inheritance, polymorphism ".
Take this document as an example. variables in the User class are private variables and can only be assigned by creating an object (automatically called by the constructor. The User class can only be accessed through the public method api.
The Admin class inherits the User class, calls its constructor, overwrites the method_1 method, and adds a special method power ().
User File
Public class User {/*** private variable, only accessible to this class */private String name; private int age;/*** constructor, automatically call */public User (String name, int age) {this. name = name; this. age = age;}/*** private method, only for this class */private void method_1 () {System. out. println ("I am a" + name + "; my age is:" + age );} /*** the quilt class can inherit, overwrite, and call the same package */protected void method_2 () {System. out. println ("I am not override");}/*** public method, external interface */public void api () {method_1 (); method_2 ();}}
Admin file
Public class Admin extends User {/*** constructor */public Admin (String name, int age) {// use the constructor super (name, age) of the parent class );} /*** override the method of the parent class with the same name */protected void method_2 () {System. out. println ("NO, you are override");}/*** subclass-Specific Method */public void power () {System. out. println ("admin is powerful ");}}
Main File
Public class Main {public static void main (String [] arg) {// instantiate a User object and call the User's public method User a = new User ("user ", 12);. api (); // output line feed to distinguish different code systems. out. println (); // instantiate an Admin object and call the two Admin Methods Admin admin_me = new Admin ("admin", 23); admin_me.api (); // inherit from the User parent class admin_me.power (); // its own unique method System. out. println ();/*** polymorphism */User test_admin = new Admin ("test_admin", 34); test_admin.api (); // test_admin.power (); // The power method is not declared in the User, so it cannot be used }}