Three features of Java (encapsulation / Inheritance / polymorphism)
1. Encapsulation
Benefits of encapsulation:
- Hide information (permissions) and provide specific method access
- Easy to add control statements
- Convenient modification and Implementation
Specific performance of packaging:
-
Attributes are decorated with private
-
The method is modified with public
package JavaSE.JavaOOP.fz; public class Book { /* Privatization attribute */ private String name;//title private String author;//author private double price;//price private char ch ;// private Book(){}//Privatization construction method /* public Method to access private properties */ //Gets the object of the Book class public static Book getBookObject(){ if(book==null){ book=new Book(); } return book; } //Modify pricing public void setPrice(double p){ price=p; } //Get pricing public double getPrice(){ return price; } //Revise the title of the book public void setName(String n){ if(n.length()<20&&n.length()>0){ name=n; } } //Get book title public String getName(){ return name; } //Modify author public void setAuthor(String author){ if(a.length()<15&&a.length()>0){ this.author=author; } } //Get author public String getAuthor(){ return author; } //Publication public void publish(){ if(name!=null){ System.out.println(name+"Published"); } else{ System.out.println("Unpublished"); } } //Display various information of books public void display(){ System.out.println("title:"+name+"\r\n author:"+author+"\r\n price:"+price); System.out.println(name+"Published\r\n"); } }
package JavaSE.JavaOOP.fz; //Test case public class test1 { //Singleton mode: in the process of running in the program, only one object is created public static void main(String[] args) { Book b = Book.getBookObject();//Instantiate objects through methods b.setAuthor("strategist of the Warring States period");//Set author b.setName("Sun Tzu's art of war");//Set book title b.setPrice(36.8);//Set pricing b.display();//display information } }
Operation results:
this keyword
- this keyword represents an object of its own class
-
Use the this keyword to reference a member variable
-
Use this keyword to reference member methods
-
When the parameter and member variable in the method have the same name
Use this to distinguish
-
Reference construction method
Note: this keyword must be placed in non static methods
super() calls the construction method of the parent class from the subclass, and this() calls other methods in the same class.
package JavaSE.JavaOOP.Packaging; public class China { /* private Modifier attribute */ private String province;//province private String national;//nation /* public Modification method */ public China(){//Nonparametric construction method System.out.println("China-->Nonparametric construction method"); } public China(int i){//Parametric construction method System.out.println("China-->Parametric construction method"); } //Set Province public void setProvince(String province){ this.province=province; //When the formal parameter and variable have the same name, use this to distinguish, this Variable names represent member variables } //set information public void setInfo(String national){ this.setProvince(province);//Call other methods with this this.national=national; } //pick up information public void getInfo(){ System.out.println(province); System.out.println(national); } }
package JavaSE.JavaOOP.Packaging; public class ChinaTest { public static void main(String[] args) { China c=new China();//create object c.setProvince("Shaanxi");//Set identity c.setInfo("Chinese");//Set nationality c.getInfo();//pick up information } }
Operation results:
2. Succession
Inheritance: derive a new class from an existing class. The new class has all non private member variables and member methods of the parent class
All classes in Java inherit the Object class directly or indirectly
When to use inheritance?
animal:
Cat, dog, pig, sheep
book:
Paper book
e-book
Relationship embodied by inheritance: "is a"
Inheritance is to improve the reusability of code and save cost
Not for inheritance
When class A and class B conform, a is one of B or B is one of a, inheritance can be used at this time
Java only supports single inheritance, not multiple inheritance, as shown in the figure
package Test.extendsdemo; //public class People extends Object //The Object class is the base class (superclass) of all classes in Java //Parent class public class People { //Private property (subclass inaccessible) private String name; private int age; //Both public methods and construction methods can be inherited public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } void sleep(){ System.out.println("sleep"); } //constructor //Nonparametric structure public People() { System.out.println("Parent class parameterless construction"); } //Zone parameter structure public People(String name, int age) { this.name = name; this.age = age; } } //Subclass class Student extends People{ /* Override / override When the parent method does not meet the needs of the subclass, the subclass can override the parent method Note: 1 static method / constructor / member variable cannot be overridden 2 When overriding the parent class method, the structure must be consistent (parameter list, method name, return value) 3 For subclass override methods, access modifier: subclass > = parent */ private String xuehao; //constructor //No reference public Student(){ /* When creating a subclass object, it calls the parent class construction method in the subclass construction method (initializing the parent class first). By default, the first sentence of the subclass construction method calls super() to initialize the assignment of the parent class variable */ System.out.println("Subclass nonparametric construction"); } //Have reference public Student(String name, int age, String xuehao) { super(name, age); /* When explicitly calling super(), the first sentence of the method must be constructed in the subclass Use super() to pass parameters and call the specified constructor */ this.xuehao = xuehao; } //Subclass overrides parent method @Override //Annotation tags in java: overwrite, rewrite // If @ Override is written, an error will be reported if it does not meet the specification during compilation @Override public void sleep() { System.out.println("Students sleep"); } //Subclass specific methods public void learn(){ System.out.println("Student learning"); } }
super:
In calling subclass object constructor
The default super() calls the parameterless construction method of the parent class first. super() must be in the first sentence
It can also be called explicitly
package Test.extendsdemo; //Test case public class PeopleTest { public static void main(String[] args) { People p=new People("Tom",21); Student s = new Student("Danny",21,"s1001"); p.setName("Tony");//Change name System.out.println(p.getName());//Output name p.sleep(); //Parent method s.setAge(31);//Modify age System.out.println(s.getAge());//Get age s.sleep(); s.setXuehao("s1010");//Modify student number System.out.println(s.getXuehao());//Get student number s.learn(); } }
Operation results:
3. Polymorphism
The same thing shows different states at different times
The same interface uses different instances to perform different operations (e.g
The necessary conditions for the existence of polymorphism: 1 Succession 2 Method override (abstract class) 3 The parent class reference points to the child class object, and all three are indispensable
When calling a method in a polymorphic way, first check whether the method exists in the parent class. If not, there will be a compilation error; If so, call the method with the same name of the subclass.
We have slightly modified the original example. The previous example has inheritance and rewriting. Now we can point the parent class reference to the child class object in the test example
package Test.extendsdemo; //public class People extends Object //The Object class is the base class (superclass) of all classes in Java //Parent class public class People { //Private property (subclass inaccessible) private String name; private int age; String s="People";//Non private property //Both public methods and construction methods can be inherited public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } void sleep(){ System.out.println("sleep"); } //Parent class static method public static void staticTest(){ System.out.println("People Static method"); } //constructor //Nonparametric structure public People() { System.out.println("Parent class parameterless construction"); } //Zone parameter structure public People(String name, int age) { this.name = name; this.age = age; } } //Subclass class Student extends People{ /* Override / override Methods of overridable parent and child classes Note: 1 static method / constructor / member variable cannot be overridden 2 When overriding the parent class method, the structure must be consistent (parameter list, method name, return value) 3 For subclass override methods, access modifier: subclass > = parent */ private String xuehao; String s="Student"; //constructor //No reference public Student(){ /* When creating a subclass object, it calls the parent class construction method in the subclass construction method (initializing the parent class first). By default, the first sentence of the subclass construction method calls super() to initialize the assignment of the parent class variable */ System.out.println("Subclass nonparametric construction"); } //Have reference public Student(String name, int age, String xuehao) { super(name, age); /* When explicitly calling super(), the first sentence of the method must be constructed in the subclass Use super() to pass parameters and call the specified constructor */ this.xuehao = xuehao; } //Subclass overrides parent method @Override //Annotation tags in java: overwrite, rewrite // If @ Override is written, an error will be reported if it does not meet the specification during compilation @Override public void sleep() { System.out.println("Students sleep"); } //Subclass overrides static method of parent class public static void staticTest(){ System.out.println("Student Static method"); } //Subclass specific methods public void learn(){ System.out.println("Student learning"); } }
package Test.extendsdemo; //Test case public class PeopleTest { public static void main(String[] args) { People p = new Student();//The parent class references the child class object p.sleep();//Public method /* Members of polymorphic access classes, The parent class method is called during compilation, and the child class is executed during operation: the compilation is on the left, and the operation is on the right For static methods and properties, both compilation and operation are shown on the left */ p.staticTest();//Static method System.out.println(p.s);//attribute } }
We point the reference p of the People class to the Student object. When using p to call the method, you can see that only the method of the parent class People can be called
Run to see the results:
You can see that both the construction method and sleep method execute the of subclasses, and the subclass construction method calls the parent class construction method by default
Static methods and properties access the parent class
For example, People p = new Student(); Called upward transformation
The parent class reference of upward transformation can only call the parent class method and execute the child class method
In order for a parent class to call subclass methods, it must be transformed downward
Implementation method of polymorphism
-
rewrite
-
Abstract methods and abstract classes
-
Interface
We only use general rewriting to realize polymorphism here. The next article introduces abstract classes and interfaces in detail and uses them to realize polymorphism