In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)05/31 Report--
In this article Xiaobian for you to introduce in detail "Java abstract classes and interfaces how to use", the content is detailed, the steps are clear, the details are handled properly, I hope this "Java abstract classes and interfaces how to use" article can help you solve doubts, the following follow the editor's ideas slowly in-depth, together to learn new knowledge.
What is an abstract class?
What is an abstract class? As the name implies, an abstract class is abstract, that is, when we don't have enough information to describe the class, we don't have to describe it first.
Take the code as an example:
Class Shape {public void draw () {System.out.println ("I want to draw graphics!") ;} class circle extends Shape {@ Override public void draw () {System.out.println ("I want to draw a circle!") ;} class rect extends Shape {@ Override public void draw () {System.out.println ("I want to draw a rectangle!") ;} public class TestDemo3 {public static void drawShape (Shape shape) {shape.draw ();} public static void main (String [] args) {drawShape (new circle ()); drawShape (new rect ());}}
Just to review polymorphism through this little case, we create a Shape parent class, and then create two subclasses, rect class and cirle class, and then use the two classes to use the same method, and the resulting form is different, but this is polymorphism.
We can find that I only use these two subclasses to draw graphics are circle and rectangle, I did not call the parent class to implement this method, why? Because this parent class can not draw a graph, then the implementation of the parent class's draw method is useless. I just need the parent class to have this method, which can be overridden by the child class, and does not need the parent class method to have a specific implementation.
Yes, this brings us to our topic abstract class today.
The draw method of the parent class above is useless because its concrete implementation is useless, so we don't have to write it, which is exactly in line with the definition of the abstract class, when there is not enough information to describe it, then we call it the abstract class.
Abstract class syntax
The draw method of the parent class above can be called an abstract method without a concrete implementation. Using abstract to modify
Public abstract void draw ()
But why would it be wrong?
The reason is that the method modified by abstract is called abstract method, if there is an abstract method in a class, then the class must be abstract, so the class must also be modified by abstract.
But on the contrary, must there be abstract methods in the abstract class?
The compiler does not report errors, so the answer is not necessarily. Abstract classes may or may not have abstract methods.
Can abstract classes be instantiated?
Therefore, abstract classes cannot be instantiated.
Can abstract classes define member variables and methods and construct methods like ordinary classes?
The difference between an abstract class and an ordinary class is that it cannot be instantiated from an abstract class, and other defining member variables, member methods, constructors, and so on are the same.
Since an abstract class cannot be instantiated, what is the meaning of its existence?
Old iron is reasonable to think, in fact, the greatest significance of an abstract class is to be inherited, because an abstract class cannot instantiate an object and can only rely on subclasses to rewrite the methods of the parent class (that is, the abstract class) to complete the business requirements.
How to inherit abstract classes? What are the points for attention?
Why does this kind of inheritance go wrong? The reason is that when the subclass inherits the abstract class, the subclass needs to override all the methods of the parent class or the subclass needs to be modified with abstract (the abstract class is inherited by the abstract class or the subclass overrides all methods of the abstract class (parent class)).
That's right.
Also note here that when we do not override the method of the parent class, we modify it with abstract. When you inherit this subclass, that is, the subclass becomes the parent class, the next subclass will continue to override the method of the parent class and the method of the parent class of the parent class.
Can abstract methods be modified by static and final?
Abstract methods cannot be modified by static and final because subclasses override the methods of the parent class and can omit the access modifier qualifier, which is public by default.
Summarize the abstract classes:
We call a class that cannot describe an object clearly enough as an abstract class.
The method modified by abstract is called abstract method, and the class modified by abstract is called abstract class.
Abstract methods must be in the abstract class, that is, as long as there are abstract methods, the class name must also be modified with abstract. On the contrary, there can be no abstract methods or abstract methods in the abstract class.
Abstract classes cannot be instantiated, except that they can define member variables, member methods, constructors, and so on, just like ordinary classes. Both constructor and class methods (methods modified by static) cannot be modified by abstract
The access modifier qualifier for abstract methods cannot be private, if omitted defaults to public, and abstract methods cannot be modified by final.
When a subclass inherits an abstract class, the subclass must override all the methods of the abstract class and have a concrete implementation of the method. If the rewrite subclass is still an abstract class, it must be modified with abstract.
Methods in abstract classes have no concrete implementation and are implemented in subclasses through subclass overrides.
A class can inherit only one abstract class
Interface
What do we think of when it comes to interfaces? At the beginning, I thought of the charging interface, plug-in, and so on, such as the charging interface, as long as it meets the standard of that socket, we can use that interface to charge. This is to unify the standards, and then people can use different interfaces according to different standards. For example, the interfaces of iPhone and Android phones are different, they are two different standards. Android phones use Android interface, Apple uses Apple interface, which unifies the standard.
The same is true in Java. We call this standard or a common specification an interface, and we can use it as long as it conforms to the standard of this interface.
Listen to this abstract concept, you may still not quite understand what this is, I'm going to take the code as an example:
Class Animal {public String name; public int age; public void eat () {System.out.println (this.name+ "eat * *!") ;}}
Here I define an animal that has a name, age, and eating behavior.
Class Animal {public String name; public int age; public void eat () {System.out.println (this.name+ "eat * *!") ;} public void swim () {System.out.println ("I want to swim ~");}} class Fish extends Animal {}
Then I define a fish (subclass) to inherit this animal class (parent class). I want this fish to have this swimming behavior, but there will be a problem. I define a swim method in the parent class, and then I have to define many classes. Do all classes have to have this swimming behavior? The answer is no. So we can't define this swim method in the parent class, then we can define this method in the subclass (fish), which is consistent, but if I have to define 1000 animals that can swim, do I have to write this swimming method in my own class? It is obviously not feasible to do so. So what should we do?
We can provide a common interface, which is also a standard, as long as it meets this standard, we can use this interface or implement this function.
After reading the above example, we should know what the interface is for. Next, let's learn the syntax of the interface.
How to define an interface
The interface keyword is used to define the interface:
/ / create an interface / / create an interface if you use the interface keyword interface name preferably an adjective other can also interface IFlying {/ / this is a flying interface}
Member variables in the interface:
This will report an error, and the member variables in the interface are constant, so they must be initialized, and the member variables in the interface will be implicitly specified as public static final decorated.
The member variables in the interface IFlying {/ / interface are constant modified by public static final by default. / the member variables here cannot be changed, public static final int a = 10;}
Member methods in the interface:
The member methods in the interface IFlying {/ / interface are all abstract methods. The default is public abstract / / where public abstract can be omitted / / member methods in the interface cannot have a specific implementation public abstract void eat (); / / it is generally written as: / / void eat () If you want to implement the method in the default void sleep () {/ / interface, you need to add default decoration} / / the interface can have the specific implementation of static method public static void method () {System.out.println ("I am a static method!");}}
Can the interface be instantiated?
Interfaces cannot be instantiated.
How to use the interface?
The interfaces implemented are as follows:
Interface IFlying {void eat ();} interface IRunning {void run ();} interface ISwimming {void swim ();} interface IClimbing {void climb () } / / create an Ant class / / use the implements keyword to implement the interface / / A class can implement multiple interfaces, and the interface uses comma connections / / to realize that the interface must rewrite the methods in the interface / / rewrite method shortcuts: mouse over the implements keyword and then alt+enterclass Ant implements IClimbing,IRunning {public String name @ Override public void run () {System.out.println (this.name+ "to run");} @ Override public void climb () {System.out.println (this.name+ "mountain climbing");}}
When the interface is used, the implements keyword is used to connect with the class, and the class and the interface are connected by implements.
A class can implement multiple interfaces, which are connected by commas.
Class Ant implements IClimbing,IRunning. Ant class can perform two functions, which can both climb and run.
When a class implements an interface, you must override the methods in the interface. If you don't rewrite the class or the abstract class, use abstract to decorate it.
Can the interface have static methods and code blocks?
There can be no static code blocks and constructors in the interface.
Inheritance between interfaces
Let's summarize the relationship between classes and interfaces here.
The relationship between a class and a class is an inheritance relationship that uses extends to connect to represent that the subclass inherits the parent class
Implements is used to connect the class to the interface, which means that the class can implement a function.
The interface can also be connected with each other, and the function of interface B is expanded by using extends interface An and interface B interface An enxtends B to represent interface A.
Here, let's talk about inheritance between interfaces.
We use the extends keyword to connect the two interfaces, thus realizing the inheritance between interfaces.
For example:
Interface IRunning extends IFlying {/ / Class IRunning extends the function of IFlying void run (); / / after inheritance between interfaces, IRunning extends the function of IFlying / / classes with the function of IRunning should also override the method IFlying}
Class IRunning expands the function of IFlying
IRunning expands IFlying function after inheriting from interface to interface.
Classes with the function of IRunning also need to override the IFlying method
Several important interfaces comparable
Let me give you an example:
For example, we are going to sort a student, and we have learned the sort method of Arrays before, so let's try this method to sort the students.
Class Student {public String name; public int age; public double score; public Student (String name, int age, double score) {this.name = name; this.age = age; this.score = score } @ Override public String toString () {return "Student {" + "name='" + name +'\'+ ", age=" + age + ", score=" + score +'}';}} public class TestDemo {public static void main (String [] args) {Student [] student = new Student [4] Student [0] = new Student ("Zhang San", 18jue 88); student [1] = new Student ("Li Si", 98jue 98); student [2] = new Student ("Wang er Ma Zi", 8pr 18); student [3] = new Student ("Zhao Laoba", 58jue 38); System.out.println (Arrays.toString (student)); Arrays.sort (student); System.out.println (Arrays.toString (student)) }}
From here, it is found that the Arrays.sort method is more specific in numerical size, but we have not specified the object of comparing students here. What on earth do we rely on to compare this student object? at present, this student has a name, score, age, what comparison we rely on is based on our needs, so how do we compare a certain student of the student object specifically? The error message is the exception. We need to provide the comparable interface and override the comparable method.
How to provide interface?
We implement an interface based on the class using the keyword implements to connect.
Then use the comparable interface and write the classes you want to sort in angle brackets.
Okay, so we implement this interface, and of course, if you look at the red line in front of you, you can see that there will be an error, that is, when we implement an interface, we have to override the methods in this interface, and then Alt+enter rewrites the methods in this interface.
Well, we rewrote such a method, for example, we want to compare ages in ascending order:
Then you can sort it by calling the Arrays.sort method.
We can also sort by name:
Since the name is the String type, that is, the reference type, we will call the compareTo method to compare.
Similarly, we can also sort the student object according to the score.
Comparator Interface-comparator
We just used comparable this interface will have a defect, for example, when we have already sorted by age, but someone suddenly changed his name to comparison, if it is a future project development, it will cause a lot of trouble to programmers, afraid that one day someone will modify that code, so we have this comparator comparator, we still package it. You don't have to modify it in the class of going to students.
Sort the age of the students:
Class AgeComparator implements Comparator {@ Override public int compare (Student o1, Student O2) {return o1.age-o2.age;}}
Sort student scores:
Class ScoreComparator implements Comparator {@ Override public int compare (Student o1, Student O2) {return (int) (o1.score-o2.score);} sort student names: class NameComparator implements Comparator {@ Override public int compare (Student o1, Student O2) {return o1.name.compareTo (o2.name);}}
We can compare this parameter by adding a comparator to the Arrays.sort method.
Public static void main (String [] args) {Student [] student = new Student [4]; student [0] = new Student ("Zhang San", 188,88); student [1] = new Student ("Li Si", 98J.98); student [2] = new Student ("Wang er Ma Zi", 881); student [3] = new Student ("Zhao Laoba", 58pl 38); System.out.println (Arrays.toString (student)) AgeComparator ageComparator = new AgeComparator (); Arrays.sort (student,ageComparator); System.out.println (Arrays.toString (student));}
In this way, we will sort according to what, instantiate the corresponding object, through the object call override comparator method can be compared, do not have to worry about being modified in the class.
Cloneable interface in-depth understanding of deep copy and shallow copy
We have learned the method of cloning in an array before, which is to copy all the contents of one array to another.
The cloneable interface we learned today can copy the properties of one object to another.
How to use the cloneable interface
We create a person class, which has two attributes, one is the score, and the other is the smartphone object (reference type).
Class SmartPhone {public int money = 9999;} class Person {public int score = 96; SmartPhone smartPhone = new SmartPhone ();} public class TestDemo {public static void main (String [] args) {Person person1 = new Person ();}}
We are now going to implement the person class to the cloneable interface, using the implements connection, and again we are going to override the methods in the cloneable interface.
Here we should pay attention to overriding the method cloneable, whose return type is that object,object is the parent of all classes in Java.
OK, after completing the operation of the interface, we then finish the cloning work. How can we use clone to clone?
Shallow copy: / / shallow copy class SmartPhone {public int money = 9999;} class Person implements Cloneable {public int score = 96; SmartPhone smartPhone = new SmartPhone (); @ Override protected Object clone () throws CloneNotSupportedException {return super.clone () } @ Override public String toString () {return "Person {" + "score=" + score + ", smartPhone=" + smartPhone +'}';}} public class TestDemo {public static void main (String [] args) throws CloneNotSupportedException {Person person1 = new Person (); Person person2 = (Person) person1.clone () System.out.println (person1.smartPhone.money); System.out.println (person2.smartPhone.money); person1.smartPhone.money=9; System.out.println ("= after copy ="); System.out.println (person1.smartPhone.money); System.out.println (person2.smartPhone.money);}}
What is the reason? Draw a picture and understand it.
This is the shallow copy, which passes values to the basic data types and makes a reference-passing copy of the reference data types. This
Is a shallow copy. As long as the moneyvalue is modified, the money values of both objects are changed, and there is no complete copy.
Deep copy / / Deep copy class SmartPhone implements Cloneable {public int money= 9999; @ Override protected Object clone () throws CloneNotSupportedException {return super.clone ();} @ Override public String toString () {return "SmartPhone {" money= "+ money +'}';}} class Person implements Cloneable {public int score = 96; SmartPhone smartPhone = new SmartPhone () @ Override protected Object clone () throws CloneNotSupportedException {Person tmp = (Person) super.clone (); tmp.smartPhone= (SmartPhone) this.smartPhone.clone (); return tmp;} @ Override public String toString () {return "Person {" + "score=" + score + ", smartPhone=" + smartPhone +'}' }} public class TestDemo {public static void main (String [] args) throws CloneNotSupportedException {Person person1 = new Person (); Person person2 = (Person) person1.clone (); System.out.println (person1.smartPhone.money); System.out.println (person2.smartPhone.money); person1.smartPhone.money=9; System.out.println ("= after copy ="); System.out.println (person1.smartPhone.money) System.out.println (person2.smartPhone.money);}}
At this time, it is a deep copy, and a thorough copy has been made. It is a deep copy to pass a value to the basic data type, to create a new object for the reference data type, and to copy its contents.
After reading this, the article "how to use Java abstract classes and interfaces" has been introduced. If you want to master the knowledge points of this article, you still need to practice and use it yourself. If you want to know more about related articles, please follow 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.