The vast sea of millions, thank you for this second you see here. Hope my article can be helpful to you! ‘!
May you keep your love and go to the mountains and seas in the coming days!
Java Basics (encapsulation and inheritance)
A. Packaging
So what is encapsulation?
In object-oriented programming, Encapsulation refers to a method of wrapping and hiding the implementation details of an abstract function interface.
1.1 Purpose of encapsulation
- Direct manipulation of class objects does not require a thorough understanding of the implementation, making the implementation of class attributes and methods invisible to the outside world. Not only convenient but also protective.
- The main feature of encapsulation is that we can modify our own implementation code without modifying the snippets that call our code.
- Proper encapsulation makes code easier to understand and maintain, and also enhances code security.
1.2 Benefits of encapsulation
- Good encapsulation reduces coupling.
- The structure inside the class can be modified freely.
- You can have more precise control over member variables.
- Hide information and implement details.
1.3 Steps of encapsulation
-
Modify the visibility of a property to restrict access to the property (typically private), for example:
public class Person { private String name ; / / name private String gender ; / / gender private int age; / / age } Copy the code
This code hides the information by making the name, sex, and age properties private and accessible only to this class and no other class.
-
Provide external public method access for each value attribute, that is, create a pair of assignment methods for accessing private attributes, such as:
public class Person { private String name ; / / name private String gender ; / / gender private int age; / / age public void setName(String name) { this.name = name; } public String getName(a) { return name; } public void setGender(String gender) { this.gender = gender; } public String gender(a){ return gender; } public void setAge(int age) { this.age = age; } public int getAge(a) { returnage; }}Copy the code
Use the this keyword to call attributes in the class, that is, member variables in the class. The main purpose is to resolve conflicts between instance variables (private String name) and local variables (name variable in setName(String name)) with the same name.
1.4 Examples of encapsulation
-
Create a User class User:
The code is as follows:
package com.nz.pojo; public class User { private String username; / / user name private String password; / / password public String getUsername(a) { return username; } public void setUsername(String username) { this.username = username; } public String getPassword(a) { return password; } public void setPassword(String password) { this.password = password; }}Copy the code
-
Write test User demo: EncapsulationDemo
The code is as follows:
package com.nz; import com.nz.pojo.User; public class EncapsulationDemo { public static void main(String[] args) { User user = new User(); user.setUsername("Prince Nezha"); user.setPassword("520"); System.out.println("username: " + user.getUsername() + "-- -- -- -- -- -- -- -- -- -- -" + "password: "+ user.getPassword()); }}Copy the code
The result is as follows:
Username: Prince Nezha -----------password520Copy the code
1.5 summary
Encapsulation actually hides some information about a class inside the class and does not allow external programs to access it directly. Instead, methods provided by the class are used to access and manipulate the hidden information. It’s about exposing methods that we want to provide to the outside world so that the outside world can call us.
2. Inheritance
2.1 Introduction to Inheritance
Inheritance is a cornerstone of Java object-oriented programming techniques because it allows the creation of hierarchical classes. It describes the ownership relationship between things, which is: is-A relationship.
Inheritance: A subclass inherits the attributes and behaviors of its parent class, so that a subclass object (instance) can directly have the same attributes and behaviors as the parent class. Subclasses have direct access to non-private properties and behaviors in their parent class.
2.2 Inheritance in life
Rabbits and giraffes are herbivores, and tigers and lions are carnivores. Herbivores and carnivores are animals.
Are rabbits, giraffes, tigers and lions animals? The answer is yes! Although both herbivores and carnivores are animals, they differ in their attributes and behaviors, so the subclass will have the general characteristics of its parent and will have its own characteristics. If we have the same properties and behaviors in multiple classes, we can extract them into a single class, so that multiple classes don’t have to define these properties and behaviors anymore, just inherit from that one class.
2.3 Benefits of inheritance
- Improve code reuse (reduce code redundancy, reuse the same code).
- Makes relationships between classes.
- A subclass has attributes and methods that are not private for its parent class.
- Subclasses can have their own properties and methods, that is, they can extend their parent class.
- Subclasses can implement the methods of their parent class in their own way.
- Improved coupling between classes (the downside of inheritance is that higher coupling results in tighter code connections and less code independence).
- Java inheritance is single inheritance, but it can be multiple inheritance. Single inheritance means that A subclass can inherit only one parent class. Multiple inheritance means that, for example, class B inherits class A, and class C inherits class B. This is a feature that distinguishes Java inheritance from C++ inheritance.
2.4 Inherited format
In Java, the extends keyword makes it possible to declare that a class extends from another class.
classThe parent class{}classA subclassextendsThe parent class{}Copy the code
One thing to note: Java does not support multiple inheritance, but it does. Is the following:
class A {}class B extends A {(right)}class C extends A.B {(false)}class C extends B {(right)}Copy the code
The top parent class is the Object class. All classes inherit Object as their parent by default.
2.5 Inherited Demo
-
Write a parent class and its corresponding subclass information
The structure is as follows:
The code is as follows:
The parent class Person:
package com.nz.pojo; public class Person { private String name ; private int age ; public String getName(a) { return name; } public void setName(String name) { this.name = name; } public int getAge(a) { return age; } public void setAge(int age) { this.age = age; }}Copy the code
Subclass Student has no additional attributes and methods:
package com.nz.pojo; /** * inherits Person's unique name, age, and no additional unique attributes and methods public class Student extends Person{}Copy the code
Subclass Teacher has a salary attribute and a unique teaching method:
package com.nz.pojo; /** * inherits Person's unique name, age, * more unique salary attributes and unique teaching methods */ public class Teacher extends Person{ / / salary private double salary ; // unique method public void teach(a){ System.out.println("The teacher is working hard!"); } public double getSalary(a) { return salary; } public void setSalary(double salary) { this.salary = salary; }}Copy the code
-
Write test code:
package com.nz; import com.nz.pojo.Student; import com.nz.pojo.Teacher; public class InheritDemo { public static void main(String[] args) { Teacher teacher = new Teacher(); teacher.setName("Prince Nezha"); teacher.setAge(18); teacher.setSalary(1999.99); System.out.println(teacher.getName()); System.out.println(teacher.getAge()); System.out.println(teacher.getSalary()); teacher.teach(); Student student = new Student(); student.setName("Which zha"); student.setAge(12); / / student. SetSalary (1999.99); // Student does not have a salary attribute.System.out.println(student.getName()); System.out.println(student.getAge()); }}Copy the code
The results are as follows:
Prince Nezha18 1999.99The teacher is teaching hard! Which zha12 Copy the code
As a result, a subclass inherits its parent class and gets its member variables and methods directly. Subclasses can write special attributes and methods, but can they inherit all of them?
2.6 What subclasses cannot inherit
Not everything in a parent class can be inherited by subclasses:
2.6.1 super and this keyword
Here, the two keywords, super and this, are frequently used in inheritance relationship.
-
Super keyword: We can use the super keyword to access the member of the parent class, which refers to the parent class of the current object.
-
This keyword: a reference to its own class.
The full uses of super and this are as follows:
this. Member variables -- of this classsuper. Member variables -- of the parent classthis.member method name () -- of this classsuper.member method name () -- parent classCopy the code
-
Create test InheritDemo2
package com.nz; public class InheritDemo2 { public static void main(String[] args) { Animal a = new Animal(); a.eat(); Cat cat = newCat(); cat.eatFish(); }}class Animal { void eat(a) { System.out.println("animal : eat"); }}class Cat extends Animal { void eat(a) { System.out.println("cat : eat"); } void eatFish(a) { this.eat(); // this calls its own method super.eat(); // super calls the superclass method}}Copy the code
The result is as follows:
animal : eat cat : eat animal : eat Copy the code
-
Note:
A subclass has a default super() in each constructor that calls the empty argument constructor of the parent class. Manually calling the superclass construct overrides the default super().
Both super() and this() must be on the first line of the constructor, so they cannot occur together.
2.6.2 Constructors cannot be inherited
-
A subclass cannot inherit a constructor (constructor or constructor) from its parent; it simply calls (implicitly or explicitly). Because subclasses have their own constructor. It is important to note that subclasses can inherit private members of their parent class (member variables, methods), but they cannot access them directly. They can access private member variables of their parent class through getter/setter methods.
-
If the parent class’s constructor takes parameters, the parent class’s constructor must be explicitly called in the subclass’s constructor via the super keyword with the appropriate argument list.
-
If the superclass constructor has no arguments, then there is no need to call the superclass constructor in the subclass’s constructor with the super keyword, and the system automatically calls the no-arguments constructor of the superclass.
-
Demonstration process:
package com.nz; public class InheritDemo3 { public static void main(String[] args) { System.out.println("------Teacher class inheritance ------"); Teacher teacher = new Teacher(); Teacher teacher2 = new Teacher("Zhang"); System.out.println("------Student class inheritance ------"); Student student = new Student(); Student student2 = new Student("Jonathan"); }}/ / parent class class Person { private String name; Person(){ System.out.println("The parent class's no-argument constructor was called: Person()"); } Person(String name) { System.out.println("The argument constructor of the parent class was called: Person(String name)"); this.name = name; }}// Teacher subclass Person class Teacher extends Person{ private String name; Teacher(){ // Automatically call the parent class's no-argument constructor because there is a default super(); System.out.println("Teacher"); } public Teacher(String name){ super("Prince Nezha"); // Call the constructor with arguments in the parent class System.out.println("Teacher(String name):"+name); this.name = name; }}// Subclass Student inherits Person class Student extends Person{ private String name; Student(){ super("heihei"); // Call the constructor with arguments in the parent class System.out.println("SubClass2"); } public Student(String name){ // Automatically calls the parent class's no-argument constructor System.out.println("Student(String name):"+name); this.name = name; }}Copy the code
The results are as follows:
------Teacher calls the parameterless constructor of the parent class from ------ : Person() Teacher calls the parameterless constructor of the parent class: Person(String name) Teacher(String name): ------Student (------) Person(String name) SubClass2 calls the parent class's no-argument constructor: Person() Student(String name): zhang SANCopy the code
2.6.3 Final modified classes cannot be inherited
The final keyword is used in three main places: variables, methods, and classes.
- Modifier class: indicates that the class cannot be inherited;
- Modifier: indicates that a method cannot be overridden;
- Modifier variable: Indicates that a variable can only be assigned once and its value cannot be modified (constant).
Final features:
- For a final variable, if it is of a primitive data type, its value cannot be changed once initialized; If a variable is a reference type, it cannot be made to point to another object after it is initialized.
- When you modify a class with final, it indicates that the class cannot be inherited. All member methods ina final class are implicitly specified as final methods.
- There are two reasons to use the final method. The first reason is to lock the method in case any inherited classes change its meaning. The second reason is efficiency. In earlier Versions of Java implementations, final methods were converted to inline calls. But if the method is too large, you may not see any performance gains from inline calls (these optimizations with final methods are no longer required in current Java versions). All private methods ina class are implicitly specified as final.
Let’s test whether the modified class can inherit:
package com.nz;
public class InheritDemo4 {}/ / parent class
final class Fu {
private String name;
}
//class Zi extends Fu{// Cannot inherit from final 'com.nz.Fu
/ /}
Copy the code
Result: You can see that Fu classes modified by final cannot be inherited, and that an error is reported at compile time and cannot be run.
2.7 Method Rewriting
2.7.1 introduction
An override effect, also known as overwriting or overwriting, occurs when a subclass has a method that is identical to the parent class (the return type, method name, and argument list are the same). Declaration unchanged, re-implement.
2.7.2 Application Scenarios and Cases
Relationships that occur between child and parent classes. The subclass inherits the method of the parent class, but the subclass feels that the method of the parent class is not sufficient for its needs. The subclass rewrites a method with the same name as the parent class to override the method of the parent class.
Write a test case:
package com.nz;
public class InheritDemo5 {
public static void main(String[] args) {
// Create a subclass object
Cat lanMao = new Cat();
// Call the method inherited from the parent class
lanMao.run();
// Call the subclass overridden methodlanMao.sing(); }}class Animal{
public void sing(a){
System.out.println("Animals can sing!");
}
public void run(a){
System.out.println("Animals can run!"); }}class Cat extends Animal {
public void sing(a){
System.out.println("Let's meow, meow, meow, meow! Let's do it together."); }}Copy the code
Running results:
Animals can run! Let's meow, meow, meow, meow! Let's do it togetherCopy the code
As you can see, the blue cat calls the rewritten sing method.
2.7.2 @override overrides the annotation
-
Override: Annotation, rewrite annotation verification!
-
This annotation indicates that the method must override the parent class, otherwise an error will be reported at compile time.
-
It is recommended to add this annotation to all rewrite, on the one hand to improve the readability of the code, on the other hand to prevent rewrite errors!
The subclass code is as follows:
class Cat extends Animal { // Declare the same, re-implement // The method name is the same as the parent class, but the function in the method body is overwritten! @Override public void sing(a){ System.out.println("Let's meow, meow, meow, meow! Let's do it together."); }}Copy the code
2.7.3 Precautions
- Method overrides occur in relationships between child and parent classes.
- Subclass methods override superclass methods. Ensure that the permissions are greater than or equal to the permissions of the superclass.
- The subclass method overrides the parent method, with the same return value type, function name, and argument list. ,
2.8 summary
Inheritance is the technique of using the definition of an existing class as a basis to create a new class. The definition of a new class can add new data or new functions, or use the functions of the parent class, but can not selectively inherit the parent class. Using inheritance makes it very easy to reuse old code.
Note: If there are any mistakes and suggestions, please leave a message! If this article is helpful to you, I hope you will pay attention to it for three times. Thank you very much! We can also search prince Prince Ne Zha public number for private chat me, thank you!