Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to understand abstract classes and interfaces in Java

2025-03-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)05/31 Report--

This article mainly introduces "how to understand abstract classes and interfaces in Java". In daily operation, I believe that many people have doubts about how to understand abstract classes and interfaces in Java. Xiaobian consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the doubts about "how to understand abstract classes and interfaces in Java". Next, please follow the editor to study!

What is an abstract class?

We have learned what a class is before, so is an abstract class a kind of class?

It feels so abstract to hear the name. That's right, he's abstract, not concrete. A class that does not contain enough information to describe a concrete object is called an abstract class.

Let's look at an example of an abstract class.

/ / Abstract classes and abstract methods need to be modified by abstract keyword abstract class Shape {/ / methods in abstract classes are generally required to be abstract methods, and abstract methods have no method body abstract void draw ();}

Do you think this abstract class has done nothing? its only method, draw (), is still empty.

If a class like this does not contain enough information to describe a specific object, it will not be possible to instantiate the object. If you don't believe it, look:

Well, since a class cannot be instantiated, what is the meaning of the existence of this abstract class? don't worry. Existence is reasonable. Listen to me slowly.

The significance of Abstract classes in the implementation of Polymorphism

One of the greatest meanings of the existence of abstract classes is to be inherited. When inherited, abstract classes can be used to implement polymorphism.

Let's look at a piece of code.

/ / Abstract classes and abstract methods need to be modified by the abstract keyword abstract class Shape {/ / methods in abstract classes are generally required to be abstract methods, and abstract methods have no method body abstract void draw () } / / when an ordinary class inherits an abstract class, the ordinary class must override the method class Cycle extends Shape {@ Override void draw () {/ / override the draw method System.out.println ("draw a circle") in the abstract class;}} public class Test4 {public static void main (String [] args) {/ / Shape shape = new Shape () Although an abstract class cannot be instantiated directly, it can pass a normal class object to a reference to an abstract class, that is, the parent class reference points to the subclass object Shape shape = new Cycle (); / / this is called: upward transformation / * Cycle cycle = new Cycle () Shape shape = cycle / / this is another way of writing for upward transformation * / shape.draw (); / / call the method overridden by the subclass through the parent class reference}}

After running, you will find a magical scene:

After reading the code, you may have a lot of questions. Don't worry, let's talk about it one by one.

What is upward transformation: the summary is "parent class reference points to subclass object"

Changes after upward transformation

About methods: parent class references can call methods common to both the subclass and the parent class (for example, if the subclass overrides the method of the parent class, then the method of the subclass is called), but the methods specific to the subclass cannot be called.

About attributes: the parent class reference can call the properties of the parent class, but not the properties of the subclass

The role of upward transformation

Reduce some repetitive code

When objects are instantiated, different objects can be instantiated according to different requirements.

In this way, the code above can be understood.

It seems that we can inherit and rewrite abstract classes through subclasses. Abstract classes are really useful!

But what does this have to do with polymorphism? abstract classes are so troublesome to use. I might as well use ordinary classes directly to achieve this effect. I don't have to write a subclass.

Well, if you look at the code below, you'll see the benefits of abstract classes in implementing polymorphism.

Abstract class Shape {public abstract void draw () / / Abstract methods cannot have concrete statements} / / when an ordinary class inherits an abstract class, the abstract method class Cycle extends Shape {@ Override / / in the abstract class must be overridden in this subclass, but it will not report an error if it is not overridden. More secure public void draw () {System.out.println ("draw a circle") with abstract classes }} class Flower extends Shape {/ / different subclasses rewrite the parent class's draw method differently @ Override public void draw () {System.out.println ("draw a flower");}} class Square extends Shape {@ Override public void draw () {System.out.println ("draw a square") }} public class Test4 {public static void main (String [] args) {Cycle cycle = new Cycle (); / / subclass reference cycle Flower flower = new Flower (); / / subclass reference flower Square square = new Square () / / the type of the array is Shape, that is, every element in the array is a parent class reference / / there is actually an upward transformation in this process, rewriting the methods in the abstract class Shape [] shapes = {cycle, flower, square}; / / the parent class reference refers to a different subclass object for (int I = 0; I)

< shapes.length; i++) { Shape shape = shapes[i]; // 父类引用shape指向->

The current corresponding subclass object shape.draw (); / / calls the draw method overridden by the parent class reference}

Calling the same method actually prints out different results. is this the so-called polymorphism?

Are you a little confused? let's explain it.

/ / add to the above code / / maybe you don't quite understand Shape [] shapes = {cycle, flower, square}; but the above code is equivalent to Shape [] shapes1 = new Shape [3]; / / there are three different subclass objects! The subclass reference with an array size of 3 / / (pointing to the-> subclass object) assigns a value to the parent object, which means that the subclass reference points to the subclass object corresponding to->. / / this is another way of writing the upward transformation, because the subclass object Cycle cycle = new Cycle (); shapes1 [0] = cycle has been instantiated earlier. / / if the subclass object is not instantiated before, write as shape1 [0] = new Cycle shapes1 [1] = flower; shapes1 [2] = square

For polymorphism, he has these three elements.

Inheritance (our Cycle class inherits the Shape abstract class)

Override (our subclass overrides the draw method)

The parent class points to the subclass object (that is, shape1 [0] = cycle-- > can also be called upward transition)

Look back at our code to see if it just fits the three elements of polymorphism.

When our parent class reference points to different subclass objects, we output different results when we call the same draw method. (it is actually that the subclass of the method is rewritten in a different form.) this is called polymorphism.

Then why do we have to use abstract classes? Is it not possible for me to implement polymorphism by inheriting ordinary classes from ordinary classes?

Of course, but it's not safe and risky.

But if it's abstract, it's different.

OK, I believe you have a general understanding of abstract classes at this point. Let's make a brief summary.

Abstract classes or methods using abstract-decorated classes or methods

An abstract class cannot describe an object concretely and cannot instantiate an object directly with an abstract class.

The member variables and member methods in an abstract class are the same as ordinary classes, but cannot be instantiated.

When an ordinary class inherits the abstract class, then the ordinary class must override all the abstract methods in the abstract class (we said earlier that the abstract class is not concrete and does not contain enough information to describe an object, so we need to complete it)

But when an abstract class An inherits abstract class B, which is abstract class A, abstract methods in abstract class B can not be overridden.

Final cannot modify abstract classes and abstract methods (because the greatest meaning of the existence of abstract classes is to be inherited, while those modified by final cannot be inherited, final and abstract, they are natural enemies)

Abstract methods cannot be modified by private (abstract methods are usually rewritten. If you are modified by private, how can you rewrite them?)

There may not be abstract methods in an abstract class, but if there are abstract methods in a class, then the class must be abstract.

What is the interface?

Abstract classes are templates abstracted from multiple classes, and if you make this abstraction more thorough, you can extract a more special "abstract class" interface (Interface).

Interface is one of the most important concepts in Java. It can be understood as a special class, except that the members of the interface have no executor and are composed of global constants and common abstract methods.

How do you define an interface? Let's take a look at a chestnut.

/ / the definition format of the interface is basically the same as that of the definition class. If you replace the class keyword with the interface keyword, you define an interface public interface interface name {/ / definition variable int a = 10; / / the member variables in the interface default to public static final / / abstract method public abstract void method1 (); / / public abstract is a fixed collocation, you can not write void method2 () / / the member methods in the interface are all public abstract by default. It is recommended to use the second method to define the method.

You can see that interfaces and classes actually have a lot in common:

The interface also contains abstract methods, so you can't instantiate the interface directly, so how do we use the interface?

It's very simple, can't we just use a common class to implement this interface? the difference is that abstract classes are inherited by subclasses, while interfaces and classes are implemented by the keyword implements.

Just as an ordinary class implements an abstract class, a class that implements an interface must implement an abstract method in that interface, otherwise the class must be defined as an abstract class.

Polymorphisms through interfaces

Just now we used abstract classes to implement polymorphism, so now we can try to use interfaces to implement polymorphism

The interface can be regarded as a special class, which can only be modified with the interface keyword interface IShape {int a = 10; the member variables in the interface default to public static final int b = 23; void draw (); the member methods in the interface can only be abstract methods, and the default is public abstract (before JDK1.8) default void show () {System.out.println ("other methods in the interface") / / other methods in the interface can also be implemented, but modify} public static void test () {System.out.println ("this is a static method in the interface") with default. }} / / an ordinary class can use implement to implement an interface, / / because the interface is also an abstract method, so the class that implements the interface also overrides the abstract method class Cycle implements IShape {@ Override public void draw () {System.out.println ("draw a circle"). } class Square implements IShape {@ Override public void draw () {System.out.println ("draw a square");}} class Flower implements IShape {@ Override public void draw () {System.out.println ("draw a flower");}} public class Test4 {public static void main (String [] args) {/ / IShape iShape = new IShape () The interface cannot directly instantiate Cycle cycle = new Cycle (); Square square = new Square (); Flower flower = new Flower (); / / the IShape interface here is equivalent to the parent class in the abstract class, and the interface type is also a reference type IShape [] iShapes = {cycle, square, flower}. / / this process actually takes place in the upward transformation of for (IShape iShape: iShapes) {/ / enhanced for-each loop, which can also be written as a common for loop form iShape.draw () / / Polymorphism} reference variables cycle and square are both assigned to the reference variable shape of type Shape through rewriting, but when shape.draw () is executed, the java virtual machine calls the rewritten draw method, depending on which object the interface refers to, shape or cycle.

Take a look at the running results.

Let's summarize the main features of interfaces in Java.

Interfaces can contain variables and methods, variables are implicitly specified as public static final, and methods are implicitly specified as public abstract (JDK 1.8d A class can implement multiple interfaces at the same time, and a class that implements an interface must implement abstract methods in that interface, otherwise the class must be defined as an abstract class.

Interfaces support multiple inheritance, that is, an interface can extends multiple interfaces, which indirectly solves the problem that classes in Java can not inherit more than one.

So where is the interface generally used?

In general, the implementation class and its abstract class used to have a "is-a" relationship, but if we want to achieve the same goal, but do not have such a relationship, use the interface.

Because of the single inheritance feature in Java, a class can inherit only one class, but one or more interfaces can be implemented, and interfaces can be used at this time.

Let's take a look at the correct use of the interface: help java implement "multiple inheritance".

Because of the single inheritance feature in Java, a class can inherit only one class, but one or more interfaces can be implemented, and interfaces can be used at this time. Class Animal {String name; / / cannot use private, and the following subclasses should also use the custom constructor of public Animal (String name) {/ / parent class this.name = name;}} interface IFlying {/ / customize multiple interfaces void fly ();} interface IRunning {void run ();} interface ISwimming {void swimming () } / / Duckling can not only run, but also swim and fly. One class inherits its parent class and implements multiple interfaces to indirectly solve the problem of not inheriting much in java class Duck extends Animal implements IRunning, ISwimming, IFlying {public Duck (String name) {/ / subclass constructor super (name) / / must be on the first line of the subclass constructor / / before you give the constructor of the subclass, call the constructor of the parent class with super (), and compare the parent before the child! / / because the parent class defines its own constructor, the compiler does not automatically add super () to the subclass constructor; to implement the parent constructor, we need to implement the abstract method in the interface} / / to rewrite @ Override public void fly () {System.out.println (this.name + "flying with wings"). } @ Override public void run () {System.out.println (this.name + "running on two legs");} @ Override public void swimming () {System.out.println (this.name + "floating on the water") }} the use of the public class interface {/ / need not learn me to use the Chinese name as the class name, I just want to demonstrate the convenience of public static void main (String [] args) {Duck duck = new Duck ("the first duckling"); / instantiate the duck object duck.fly (); / / by referencing the variable name. The method name outputs the rewritten method duck.run (); duck.swimming ();}} some people may say why use the interface. Can't I implement fly, run, swimming properties directly in the parent class Animal, and then different animal subclasses inherit these methods from the parent class? But the question is, can ducks fly and swimming, can the cat fly and swim? Would it be impossible for you to write a subcategory of other animals and use the interface? We just abstract the behavior of flying and swimming. As long as a subclass has this kind of behavior, it can implement the corresponding interface, and the interface is more flexible.

The above code shows the most common use in Java object-oriented programming: a class inherits a parent class and implements multiple interfaces at the same time.

The meaning of inheritance expression is is-a semantics, while the meaning of interface expression is that it has xxx characteristics. The class that can implement the interface does not necessarily have an is_a relationship with the interface, as long as the class has the characteristics of this interface.

A cat is an animal with the ability to run.

A frog is also an animal that can run and swim.

A duck is also an animal. It can run, swim and fly.

What are the benefits of this design? Always keep in mind the benefits of polymorphism and make programmers forget types. With the interface, the user of the class does not have to pay attention to the specific type, as long as the class has this feature.

Take a chestnut.

Class Robot implements IRunning {private String name; public Robot (String name) {this.name = name;} / / A pair of run methods are rewritten @ Override public void run () {System.out.println ("robot" + this.name + "running");}} public class Test4 {public static void main (String [] args) {Robot robot1 = new Robot ("figure") Robot1.run ();}} / / the execution result Robot Graph is coming to an end, and the study on "how to understand abstract classes and interfaces in Java" is over, hoping to solve everyone's doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

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.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report