In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
Today, the editor will share with you the relevant knowledge points inherited by Java. The content is detailed and the logic is clear. I believe most people still know too much about this knowledge, so share this article for your reference. I hope you can get something after reading this article. Let's take a look at it.
Introduction to inheritance
Inheritance is a cornerstone of java object-oriented programming technology because it allows the creation of hierarchical classes. It describes the ownership relationship between things, which is: the relationship of is-a.
Inheritance: the subclass inherits the properties and behavior of the parent class, so that the subclass object (instance) can directly have the same properties and behavior as the parent class. Subclasses can directly access non-private properties and behaviors in the parent class.
Inheritance in life
Rabbits and giraffes belong to herbivores, tigers and lions belong to carnivores. Herbivores and carnivores belong to animals.
Are rabbits, giraffes, tigers and lions all animals? The answer is yes! Although herbivores and carnivores are both animals, their properties and behaviors are different, so the subclasses will have the general characteristics of the parent class and will also have their own characteristics. When we have the same attributes and behaviors in multiple classes, we can extract these contents into a single class, so that multiple classes no longer need to define these attributes and behaviors, just inherit that class.
The benefits of inheritance
Improve code reusability (reduce code redundancy and reuse the same code).
It creates a relationship between classes.
The subclass has properties and methods of the parent class that are not private.
Subclasses can have their own properties and methods, that is, subclasses can extend the parent class.
Subclasses can implement the methods of the parent class in their own way.
Improve the coupling between classes (the disadvantage of inheritance, the higher the degree of coupling, the closer the relationship between the code, the worse the code independence).
Java inheritance is single inheritance, but can be multiple inheritance, single inheritance is a subclass can only inherit one parent class, multiple inheritance is, for example, class B inherits class A, class C inherits class B, so according to the relationship, class B is the parent of class C, and class An is the parent of class B, which is a feature that distinguishes Java inheritance from C++ inheritance.
Inherited format
In Java, you can declare that a class inherits from another class through the extends keyword, as follows:
Class parent class {
}
Class subclass extends parent class {
}
It is important to note that Java does not support multiple inheritance, but supports multiple inheritance. It is as follows:
Class A {
}
Class B extends A {(right)
}
Class C extends A, B {(wrong)
}
Class C extends B {(right)
}
The top-level parent is the Object class. All classes inherit Object by default as the parent class.
Inherited demo
Write a parent class and its corresponding subclass information
The structure is as follows:
The code is as follows:
Parent class Person:
Package com.nz.pojo;public class Person {private String name; private int age; 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;}}
The subclass Student has no additional properties and methods:
Package com.nz.pojo;/** * inherits Person-specific name, age, * no additional unique properties and methods * / public class Student extends Person {}
The subclass Teacher adds a salary attribute and a unique teaching method:
Package com.nz.pojo;/** * inherits Person's unique name, age, * its own unique salary attribute and unique teaching method * / public class Teacher extends Person {/ / salary private double salary; / / unique method public void teach () {System.out.println ("the teacher is teaching seriously!") ;} public double getSalary () {return salary;} public void setSalary (double salary) {this.salary = salary;}}
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 ("favorite canned fish"); 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 ("canned"); student.setAge (12); / / student.setSalary (1999.99); / / student has no salary attribute, report an error! System.out.println (student.getName ()); System.out.println (student.getAge ());}}
The results are as follows:
I like canned fish best.
eighteen
1999.99
The teacher is teaching seriously!
Canned
twelve
As a result, if the subclass inherits the parent class, you can directly get the member variables and methods of the parent class. Subclasses can write some unique properties and methods, but can they inherit all the components?
Content that subclasses cannot inherit
Not all the contents of the parent class can be inherited by the subclass:
Super and this keywords
Here, these two keywords, super and this, are used frequently in inheritance relations.
Super keyword: we can access the members of the parent class through the super keyword, which is used to reference the parent class of the current object.
This keyword: a reference to your own class.
The complete uses of super and this are as follows:
This. Member variables-- for this class
Super. Member variable-- parent class
This. Member method name ()-- for this class
Super. Member method name ()-- of the parent class
To demonstrate, create a test InheritDemo2:
Package com.nz;public class InheritDemo2 {public static void main (String [] args) {Animal a = new Animal (); a.eat (); Cat cat = new Cat (); cat.eatFish ();}} class Animal {void eat () {System.out.println ("animal: eat") }} class Cat extends Animal {void eat () {System.out.println ("cat: eat");} void eatFish () {this.eat (); / / this calls its own method super.eat (); / / super calls parent method}}
The call result is as follows:
Animal: eat
Cat: eat
Animal: eat
Note:
There is a default super () in each constructor of the subclass, which calls the empty parameter construction of the parent class. Manually invoking the parent construction overrides the default super ().
Both super () and this () must be on the first line of the constructor, so they cannot appear at the same time.
Constructors cannot be inherited
A subclass cannot inherit the constructor (constructor or constructor) of the parent class, it just calls (implicit or explicit). Because subclasses have their own constructors. It is worth noting that subclasses can inherit the private members of the parent class (member variables, methods), but the subclasses cannot access them directly, and the private member variables of the parent class can be accessed through the getter/setter method.
If the constructor of the parent class takes parameters, the constructor of the parent class must be explicitly called through the super keyword in the constructor of the subclass with the appropriate parameter list.
If the parent class constructor has no parameters, the parent class constructor does not need to be called with the super keyword in the subclass constructor, and the parent class's no-parameter constructor is automatically called.
Demo 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 San"); System.out.println ("- Student class inheritance -"); Student student = new Student () Student student2 = new Student ("Zhang San San");}} / parent class class Person {private String name; Person () {System.out.println ("No parameter constructor of parent class: Person ()");} Person (String name) {System.out.println ("Parametric constructor of parent class: Person (String name)"); this.name = name }} / / the Teacher subclass inherits Personclass Teacher extends Person {private String name; Teacher () {/ / automatically calls the parent class's parameterless constructor because there will be a default super (); System.out.println ("Teacher");} public Teacher (String name) {super ("favorite canned fish") / / call constructor System.out.println with parameters in parent class ("Teacher (String name):" + name); this.name = name;}} / / Student subclass inherits Personclass Student extends Person {private String name; Student () {super ("heihei"); / / calls constructor System.out.println with parameters in parent class ("SubClass2") } public Student (String name) {/ / automatically calls the parent class's parameterless constructor System.out.println ("Student (String name):" + name); this.name = name;}}
The results are as follows:
-Teacher class inheritance-
The no-parameter constructor of the parent class is called: Person ()
Teacher
The parameter constructor of the parent class is called: Person (String name)
Teacher (String name): Zhang San
-Student class inheritance-
The parameter constructor of the parent class is called: Person (String name)
SubClass2
The no-parameter constructor of the parent class is called: Person ()
Student (String name): Zhang Sansan
Final-decorated classes cannot be inherited
The final keyword is mainly used in three places: variables, methods, and classes.
Modifier class: indicates that this class cannot be inherited
Modification method: indicates that the method cannot be overridden
Modifier variable: indicates that the variable can only be assigned once and the value cannot be modified (constant).
Characteristics of final:
For a final variable, if it is a variable of a basic data type, its value cannot be changed once initialized; if it is a variable of a reference type, it cannot point to another object after initialization.
When you modify a class with final, it indicates that the class cannot be inherited. All member methods in the final class are implicitly specified as final methods.
There are two reasons for using the final method. The first reason is to lock the method to prevent any inherited class from changing its meaning; the second reason is efficiency. In earlier versions of the Java implementation, the final method was converted to an inline call. But if the method is too large, you may not see any performance gains from embedded calls (the current version of Java no longer needs to use the final method for these optimizations). All private methods in the class are implicitly specified as final.
Let's test whether the decorated 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' shows that there is no way to inherit Fu//}
The result: you can see that the Fu class modified by final cannot be inherited, and it will report an error during compilation and cannot be run.
Introduction to method rewriting
When a method that is exactly the same as the parent class appears in the subclass (the return value type, method name, and parameter list are all the same), an override effect occurs, also known as overriding or overwriting. The declaration remains the same and will be reimplemented.
Use scenarios and cases
A relationship that occurs between child parent classes. The subclass inherits the method of the parent class, but the subclass feels that the method of the parent class is not enough to meet its own needs, and 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 the subclass object Cat lanMao = new Cat (); / / call the method lanMao.run () inherited from the parent class; / / call the method lanMao.sing () overridden by the subclass }} class Animal {public void sing () {System.out.println ("all animals can sing!") ;} public void run () {System.out.println ("any animal can run!") ;} class Cat extends Animal {public void sing () {System.out.println ("Let's bark like cats, let's meow together! let's spoil together");}}
Running result:
Animals can run!
Let's learn to bark like a cat and meow together! Let's get spoiled together.
As you can see, the blue cat calls the overridden sing method.
@ Override rewrite comments
@ Override: comment, rewrite comment check!
This annotated method indicates that the method must be a method that overrides the parent class, otherwise an error is reported at compile time.
It is recommended to add this comment to the rewrite, which can improve the readability of the code on the one hand and prevent rewriting errors on the other!
The code form of the subclass is as follows:
The class Cat extends Animal {/ / declaration remains the same, reimplementing / / the method name is the same as the parent class, but the function in the method body is rewritten! @ Override public void sing () {System.out.println ("Let's meow together, let's meow together");}} points for attention
Method rewriting is a relationship that occurs between child parent classes.
The subclass method overrides the parent method, and you must ensure that the permission is greater than or equal to the parent permission.
The subclass method overrides the parent method and returns the same value type, function name, and parameter list.
These are all the contents of the article "what are the knowledge points inherited by Java". Thank you for reading! I believe you will gain a lot after reading this article. The editor will update different knowledge for you every day. If you want to learn more knowledge, please pay attention to the industry information channel.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.