Three characteristics of Java object orientation

  • 2020-04-01 03:54:29
  • OfStack

Java object - oriented three characteristics: "encapsulation, inheritance, polymorphism." For more information about Java technology, please visit the official website of crazy software education. WeChat search WeChat ID: crazy software, participate in the 2015 promotional activities, have the opportunity to get the promotional and proxy.

In this case, the variables in the User class are private and can only be assigned by creating an object (at which point the constructor is automatically called).

The User class can only be accessed by the outside world through the public method API ().

The Admin class inherits the User class, invokes its constructor, and overrides the method_1 method, adding a unique method, power().

The User files


  public class User {
  
  private String name;
  private int age;
  
  public User(String name, int age){
  this.name = name;
  this.age = age;
  }
  
  private void method_1(){
  System.out.println("i am a " + name + " ; my age is: " + age);
  }
  
  protected void method_2(){
  System.out.println("i am not override");
  }
  
  public void api() {
  method_1();
  method_2();
  }
  }
  Admin file 
  public class Admin extends User {
  
  public Admin(String name, int age) {
  //Use the parent class's constructor
  super(name, age);
  }
  
  protected void method_2() {
  System.out.println("NO, you are override"); ah 
  }
  
  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 invoke the public method of the User
  User a = new User("user", 12);
  a.api();
  //Output line feed, easy to distinguish different code
  System.out.println();
  //Instantiate an Admin object and invoke the two methods of Admin
  Admin admin_me = new Admin("admin", 23);
  admin_me.api(); //Inherits from the User parent class
  admin_me.power(); //Its own unique method
  System.out.println();
  
  User test_admin = new Admin("test_admin", 34);
  test_admin.api();
  // test_admin.power(); // User There is no declaration in power This method cannot be used 
  }
  }

The above is all the content of this article, I hope you can enjoy it.


Related articles: