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 use Java abstract classes and interfaces

2025-02-25 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article will explain in detail how to use Java abstract classes and interfaces. The editor thinks it is very practical, so I share it for you as a reference. I hope you can get something after reading this article.

Abstract class

What is an abstract class? In real life, when we say "human", we cannot correspond to a specific person. similarly, classes such as "animals" and "graphic classes" that cannot be mapped to concrete objects are abstract classes.

Abstract class is a superset of ordinary class, which means that some abstract class of ordinary class also has, but it has more abstract methods than ordinary class. There can be one or more of these abstract methods.

The purpose of its existence is to let subclasses override its abstract methods, and abstract classes and abstract methods are implemented using the abstract keyword:

At this point, the Sharp class is an abstract class, and you can see that its icon is different from that of a normal class.

Abstract method

Example:

Public abstract void print ()

The class in which the abstract method is located must be an abstract class. Abstract methods have only method declarations, but no method body {}.

Pay attention to distinguish between the cases where there is no method body and when the method body is empty

Public abstract void print (); / / there is no method body.

Public abstract void print () {} / / this is the method body is empty, it is a common method

Three principles of abstract class

1. Abstract classes cannot instantiate objects directly. For example, the Sharp class above, Sharp sharp = new Sharp (); / / this is wrong

two。 The subclass inherits the abstract class and must override all abstract methods in the abstract class (provided that the subclass is a normal class)

Triangle is an ordinary class, and the error is reported without overriding the method. Then we use the alt + enter shortcut key, click on the first line, and then click ok to override the abstract method of the parent class.

But when the subclass is still abstract, you can choose not to override the abstract method

3.final and abstract cannot be used together, private and abstract cannot be used at the same time

The greatest meaning of the existence of an abstract class is to be inherited, and it still satisfies the is a principle of inheritance relations.

Abstract class Person

Class Chinese extends Person √

Class Dog extends Person × / / because of Dog not is a Person

At the same time, abstract classes are still limited by single inheritance, so we introduce interfaces to break these two limitations.

Interface

Java uses the interface keyword to define the interface, in which only global constants and abstract methods (before JDK) JDK8 extends the default method. The subclass implements the interface using implements

General interface naming begins with an uppercase'I 'letter, and subclass naming ends with Impl

Global constant:

Public static final int NUM = 10

Abstract method:

Public abstract String msg ()

Interface usage principle

1.

Public interface IMassage {int NUM = 10ram / global constant String msg (); / / Abstract method}

two。 There is no single inheritance restriction for interfaces, and subclasses can implement multiple parent interfaces at the same time, separated by commas. At this point, the subclass must implement all abstract methods in the parent class interface

Public interface IMassage {int NUM = 10 / global constant String msg (); / / Abstract method} interface INews {void getNews ();} / subclass public class MessageImpl implements IMassage,INews {public String msg () {return null;} public void getNews () {}}

Interface A {void testA ();} interface B {void testB ();} interface C extends A Magi B {}

3. The interface still cannot instantiate the object directly, and needs to be realized through upward transformation.

Public class MessageImpl implements IMassage,INews {public String msg () {return "hello JAVA";} public void getNews () {System.out.println ("hello n");} public static void main (String [] args) {IMassage m = new MessageImpl (); System.out.println (m.msg ());}}

/ / output: hello JAVA

M can only call the msg method, but not the method defined by the INews interface class. It needs to be called by the conversion between the parent classes.

INews n = (INews) m; n.getNews ()

/ / output: hello n ~

4. If a subclass wants to inherit both the class and the interface, it inherits first and then implements the interface

Public class D extends An implements X,Y {}

JDK two built-in interfaces java.lang.Comparable comparison interface

Introduction example: use sorting methods to compare objects in the Student class

Public class Student {private String name; private int age; public Student (String name,int age) {this.name = name; this.age = age;} public String toString () {return "Student {" + "name=" + name+'\'+ ", age=" + age +'}';} public static void main (String [] args) {Student S1 = new Student ("Zhang San", 18) Student S2 = new Student ("Li Si", 20); Student S3 = new Student ("Wangwu", 30); Student [] students = {S3Magne S1 Magazine S2}; Arrays.sort (students); System.out.println (Arrays.toString (students));}}

Running result:

The program reports an error because the Student class is a custom type, and when sorting custom types using the Arrays.sort method, custom types need to implement Comparable in order to be comparable

So let's make the following changes to the above example:

Public class Student implements Comparable {private String name; private int age; public Student (String name,int age) {this.name = name; this.age = age;} public String toString () {return "Student {" + "name=" + name+'\'+ ", age=" + age +'}' } @ Override public int compareTo (Student o) {if (this.age = = o.age) {return 0;} else if (this.age)

< o.age){ return -1; } return 1; } public static void main(String[] args) { Student s1 = new Student("张三",18); Student s2 = new Student("李四",20); Student s3 = new Student("王五",30); Student[] students = {s3,s1,s2};//乱序放入数组 Arrays.sort(students); System.out.println(Arrays.toString(students)); } } //输出结果: [Student{name=张三',age=18}, Student{name=李四',age=20}, Student{name=王五',age=30}] 可以看到数组按照年龄的升序排序,达到了预期效果。如果想要按照年龄降序排列,只需要修改 compareTo 方法中的一和负一 实现Comparable接口,必须覆写它的compareTo方法,该方法返回的数字: =0 表示当前对象等于目标对象 o >

0 means that the current object is equal to the target object o

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