Java object-oriented three major features: "Encapsulation, inheritance, polymorphism."
For example, the variables in the user class are private variables and can only be assigned by creating objects, which are called automatically by the constructor method. The user class can only be accessed by the Public method API ().
The Admin class inherits the user class, invokes its construction method, and overrides the Method_1 method, adding a proprietary method, power ().
User File
public class User { /** * Private variable, only this class access * / private String name; private int age; /** * Construction method, automatic call * /Public User (String name, int age) { this.name = name; This.age = age; } /** * Private method, limited to this class access */ private void Method_1 () { System.out.println ("I am a" + name + "; My age was: "+ age"; } /** * Can be overridden to inherit, overwrite, and call the same package */ protected void Method_2 () { System.out.println ("I am not override"); } /** * Public method, external interface */Common void API () { method_1 (); Method_2 (); }}
Admin file
public class Admin extends User { /** * Construction Method * /Public Admin (String name, int age) { //Use Parent class constructor method Super (name, age); } /** * Overrides the parent class with the same name method */ 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{ publicly static void Main (string[] arg) { //instantiates a user object and invokes the user's common method, User A = new User ("User ", a); A.api (); Output line wrapping, convenient to distinguish different code System.out.println (); Instantiate an Admin object and call Admin two methods Admin Admin_me = new Admin ("admin", "at"); Admin_me.api (); Inherit from user parent class admin_me.power (); Its own unique method of System.out.println (); /** * Polymorphism * * /User test_admin = new Admin ("Test_admin"); Test_admin.api (); test_admin.power ();//user does not declare power this method, so cannot use }}
Three main features of Java object-oriented