Home > Java > javaTutorial > body text

How to master Java abstract classes and interfaces?

WBOY
Release: 2023-05-08 08:16:07
forward
1106 people have browsed it

    abstract

    abstract introduction: can be used to modify: class (abstract class), method (abstract method)

    abstract modified class :

    ①This class cannot be instantiated (that is, objects of this class cannot be created)

    ②Although it cannot be instantiated by itself, the subclass will call the constructor of the parent class, so the abstract class There must be a constructor in

    abstract modified method

    ①The abstract method only has the declaration of the method but no method body, and the class it belongs to must be an abstract class. Because if a class is not abstract, then this class can create objects, and if it can create objects, it can be called. On the contrary, there can be no abstract methods in abstract classes.

    ② If the subclass rewrites all the abstract methods of the parent class, it can be instantiated. If not all are rewritten, then the subclass is also an abstract class and needs to be modified with abstract.

    ③Abstract cannot be used to modify private methods, static methods, methods modified with the final keyword, and classes modified with the final keyword.

    Final clearly cannot be inherited, but abstract requires subclass inheritance so it cannot be used, because if both methods are static, the two methods are not considered to be overridden or overridden, so abstract is used to modify static methods. Cannot be overridden.

    Abstract application

    Template method design pattern. When implementing an algorithm in software development, the overall steps are very fixed and common. These steps are written in the parent class, and some volatile and uncertain parts can be abstracted for implementation by subclasses.

    Anonymous subclass object of abstract class

    public static void main(String[] args){
        //匿名对象
        eat(new son());
        //非匿名类的非匿名对象
        son John=new son();
        eat(John);
        //匿名子类对象
        father f=new father(){//抽象类造对象必须要重写方法,了解看得懂就ok了。
            @Override
            public void work() {
            }
            @Override
            public void info(father i) {
            }
        };
    }
    //普通方法
    public static void eat(father f){
        System.out.println("吃饭");
    }
    //父类
    public abstract static class father{
        String name;
        int age;
        public abstract void work();//抽象方法不能有方法体
        public abstract void info(father i);
    }
    //子类
    public class son extends father{//继承
        String name;
        int age;
        @Override
        public void work(){
            System.out.println("上学");
        }
        @Override
        public void info(father i) {
            System.out.println("name:"+i.name+" age:"+i.age);
        }
    }
    //接口的匿名对象
    非匿名的对象可以被多次调用,匿名的对象只能使用一次
    Computer com=new Computer();//创建了接口的非匿名实现类(子类)的非匿名对象,类和对象都是有名的
    Flash flash = new Flash();
    //2.创建了接口的非匿名实现类的匿名对象,对象匿名了
    com.transferData(new Printer());
    //3创建了接口的匿名实现类的非匿名对象,就是类是匿名的,就不知道是接口中的哪个实现类,所以 需要重写方法进行说明
    USB  phone = new USB{
        public void start(){
            ...
        }
    };
    //4.创建了接口的匿名实现类的匿名对象
    com.transferData(new USB(){
        public void start(){
            ...
        }  
        });
    Copy after login

    final keyword

    final modified class: This class cannot be inherited by other classes, such as: String, System, StringBuffer

    Final modification method: This method can no longer be overridden, such as: getClass() in the Object class

    static final is used to modify properties: global constants

    final modification variables : The variable at this time is called a constant

    final modified attribute: You can consider the location of assignment: explicit initialization, initialization in the code block, initialization in the constructor

    final modified local variable : Especially when modifying the formal parameter with final, it indicates that the formal parameter is a constant. When calling this method, assign actual parameters to the constant formal parameter. Once assigned, the formal parameter can only be used in the method body, but cannot be reassigned

    Interface

    Interface is defined using Interface, which is in parallel relationship with class

    Definition of interface and members in interface:

    Interface related rules

    1. All methods in the interface are abstract.

    2. Even if the members in the interface are not explicitly marked as public, they are of public access type.

    3. The variables in the interface are marked as public static final by default, so the variables defined in the interface Variables are global static constants.

    4. You can define a new interface and use extends to inherit an existing interface.

    5. You can define a class and use implements to implement all methods in an interface.

    6. You can define an abstract class and use implements to implement some methods in an interface.

    Characteristics of interfaces

    1. The interface cannot be instantiated

    2. The implementation class must implement all methods of the interface

    3. The implementation class can Implement multiple interfaces

    4. The variables in the interface are all static constants

    If the class covers all the abstract methods in the interface, you can create an instance; if the class does not cover all the abstract methods in the interface abstract method, the class is still an abstract class. Java classes can implement multiple interfaces - making up for the shortcomings of single inheritance

    class AA extends BB implements CC,DD,EE

    between interfaces and interfaces Intermediate inheritance is possible, and multiple inheritance is possible. The use of interfaces reflects polymorphism. An interface is a specification, programming for interfaces.

    Similarities and differences between abstract classes and interfaces

    Same points: they cannot be instantiated, both can contain abstract methods

    Differences:

    1. Put abstract classes And the definition and internal structure explanation of interface (java7, java8)

    2. Class: single inheritance, interface: multiple inheritance.

    Exercises on abstract classes and interfaces

     abstract class Door {
        //开门
        public abstract void openDoor();
        //关门
        public abstract void closeDoor();
    }
     interface Lock {
        public static final int num = 200;
        //开锁
        public abstract void openLock();
        //上锁
        public abstract void closeLock();
    }
    class LockDoor extends Door implements Lock {
        public void openDoor() {
            System.out.println("开门");
        }
        public void closeDoor() {
            System.out.println("关门");
        }
        public void openLock() {
            System.out.println("开锁");
        }
        public void closeLock() {
            System.out.println("上锁");
        }
      }
    public class TestLockDoor {
        public static void main(String[] args) {
            LockDoor lockDoor = new LockDoor();
            lockDoor.openLock();
            lockDoor.openDoor();
            lockDoor.closeDoor();
            lockDoor.closeLock();
        }
    }
    Copy after login

    Application of interfaces

    Two design modes

    -Agent mode

    Agent design is Provide a proxy for other objects to control access to this object

    Application scenarios: security proxy, remote proxy, lazy loading

    Category: static proxy, dynamic proxy

    - Factory pattern

    realizes the separation of creators and callers

    interface A{
        int x=0;
    }
    class B{
        int x=1;
    }
    class C extends B implements A{
        public void pX(){
            System.out.println(x);
        }
        public static void main(String[] args){
            new C().pX();
        }
    }
    //问题:编译期不知道是要输出哪个x
    System.out.println(super.x);//这个调用的是父类中的
    System.out.println(A.x);//这个调用的是接口中的
    Copy after login

    New interface features in java8

    JDK8: In addition to global constants and abstract methods, you can also define static methods and Default method (default keyword modification)

    public interface CompareA{  
      public static void method1(){
      //静态方法        
      System.out.println("CompareA:北京");   
       }   
        public default void method2(){
        //默认方法        
        System.out.println("CompareA:上海");   
         }
      }
    Copy after login

    The static method defined in the interface can only be called through the interface, interface.method.

    By implementing the object of the class, you can call the default method in the interface, object.method.

    If the implementation class overrides the default method in the interface, the overridden method will still be called when calling.

    If the subclass (or implementation class) inherits the parent class and the implemented A method with the same name and the same parameters is declared in the interface. If the subclass does not override this method, it will call the method in the parent class——Class Priority Principle

    如果实现类实现了多个接口,而这个多个接口中定义了同名同参数的默认方法,在实现类没有重写方法的情况下会报”接口冲突“错误,此时需要重写。

    如何在子类(或者实现类)调用父类、接口中被重写的方法? 接口.super.方法。

    内部类

    需要关注的问题:如何实例化成员内部类的对象:外部类Person,静态内部类Brain,非静态内部类Lungs,静态成员内部类:new 外部类.内部类()

    Person.Brain brain=new Person.Brain();
    Copy after login

    非静态成员内部类:先造对象,对象.new 内部类()

    Person p=new Person();
    p.Lungs lungs=p.new Lungs();
    Copy after login

    如何在成员内部类中区分调用外部类的结构

    形参直接调,所在类的用this.结构,外部类的用外部类.this.结构

    成员内部类和局部内部类在编译以后都会生成字节码文件

    成员内部类:外部类.内部类名.class

    局部内部类:外部类.数字 内部类名.class

    在局部内部类的方法中,如果调用局部内部类所在的方法中的局部变量,该局部变量必须用final关键字修饰(JAVA8之后可以不写出来,但仍然还是final的)

    public void Person(){
        int num=10;
        class AA{//局部内部类
            public void show(){//局部内部类的方法
                num=20;//试图修改会报错
                System.out.println(num);//调用局部内部类所在的方法中的局部变量
            }
        }
    }
    Copy after login

    开发中局部内部类的使用

    常用的局部内部类:

    //方式一
    public Comparable getCompareble(){
        class MyComparable implements Comparable{//局部内部类
    
            public int compareTo(Object o){
                return 0;
            }
        }
        return new MyComparable();
    }
    //方式二
    public Comparable getCompareble(){
        return new Comparable(){
    
            public int CompareTo(Object o){
                return 0;
            }
        };
    }
    Copy after login

    Java允许将一个类A声明在另一个类B中,A为内部类,B为外部类

    内部类的分类:成员内部类、局部内部类(方法内,代码块内,构造器内)

    成员内部类

    作为外部类的成员:可以调用外部类的结构,可以被static修饰

    作为一个类:可以定义属性、方法、构造器,可以用final、abstract修饰,可以被继承

    this.name//内部类的属性

    Person.this.name//外部类的属性

    The above is the detailed content of How to master Java abstract classes and interfaces?. For more information, please follow other related articles on the PHP Chinese website!

    Related labels:
    source:yisu.com
    Statement of this Website
    The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
    Popular Tutorials
    More>
    Latest Downloads
    More>
    Web Effects
    Website Source Code
    Website Materials
    Front End Template