Three main features of Java object-oriented, java object-oriented
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 variables, only accessible to this class
*/
Private String name;
Private int age;
/**
* Constructor, called automatically
*/
Public User (String name, int age ){
This. name = name;
This. age = age;
}
/**
* Private method, only for this class of access
*/
Private void method_1 (){
System. out. println ("I am a" + name + "; my age is:" + age );
}
/**
* It can be inherited, overwritten, and called with the same package.
*/
Protected void method_2 (){
System. out. println ("I am not override ");
}
/**
* Public methods and External Interfaces
*/
Public void api (){
Method_1 ();
Method_2 ();
}
}
Admin file
Public class Admin extends User {
/**
* Constructor
*/
Public Admin (String name, int age ){
// Use the constructor of the parent class
Super (name, age );
}
/**
* Override methods of the same name of the parent class
*/
Protected void method_2 (){
System. out. println ("NO, you are override"); ah
}
/**
* Special subclass 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 public method of the User
User a = new User ("user", 12 );
A. api ();
// Output line breaks to distinguish different codes
System. out. println ();
// Instantiate an Admin object and call the two methods of Admin
Admin admin_me = new Admin ("admin", 23 );
Admin_me.api (); // inherits from the User parent class
Admin_me.power (); // 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.
}
}