Home > Java > Javagetting Started > In-depth understanding of abstract classes and interfaces in Java

In-depth understanding of abstract classes and interfaces in Java

青灯夜游
Release: 2019-11-27 16:44:20
forward
2077 people have browsed it

I believe everyone has this feeling: abstract classes and interfaces have too many similarities and too many differences. These two often make beginners confused. Whether in actual programming or during interviews, abstract classes and interfaces are particularly important! I hope that after reading this article, everyone can calmly understand the two...

In-depth understanding of abstract classes and interfaces in Java

What I understand about abstract classes

1. Abstract classes have the same flavor as classes.

1) Abstract classes can be used the same as classes. To inherit

2), abstract classes can have all the components that a class can have [including constructors, static static modification components, etc.]

Abstract class is just as the name defines it, it is also A class

2, abstract method

It is necessary to know first before talking about different charms

Abstract method

1), abstract method has no method body

2), abstract method must be modified with
abstract keyword3), has abstraction The class of the method must be an abstract class
4). The abstract method must be
public or protected. By default, it is public

Abstract classes do not necessarily have abstract methods

3. The strange charm of abstract classes and classes

1) , Abstract classes must be modified with the abstract keyword. Classes modified with abstract are abstract classes!

2), abstract classes may or may not have abstract methods
3), although abstract classes have constructors, they cannot be used to directly create object instances
4), abstract classes cannot use
final, privateModification5) External abstract classes cannot be modified with Static, but internal abstract classes can be declared with static. The code to understand this sentence is as follows:

//定义一个抽象类A
abstract class A{
   //定义一个内部抽象类B
    static abstract class B{  //static定义的内部类属于外部类
        public abstract void saoMethod();
    }
}

class C extends A.B{

    public void saoMethod(){
        System.out.println("======saoMethod方法执行了======");
    }
}
public class StaticDemo {

    public static void main(String[] args) {
        A.B ab = new C();//向上转型
        ab.saoMethod();
    }

}

运行结果:  ======saoMethod方法执行了======
Copy after login

Some children's shoes are confusing.

C extends A.BWhat kind of cool operation is it? Can you still play like this? Yes, when the internal abstract class declared using static is equivalent to an external abstract class, the class name is expressed in the form of "external class.inner class" when inheriting. This kind of cool operation is really safe and skinny.

Abstract class is a special class. There is an essential difference between abstract class and ordinary class

4. Master abstract class

Abstract classes exist for inheritance. If you define an abstract class but do not inherit it, the abstract class created will be meaningless!

Although abstract classes have constructors, they cannot be directly Being instantiated, creating an object involves upward transformation, which is mainly used to be called by its subclasses

There is also the sentence that abstract classes can have no abstract methods. This is just an important thing to remember. Concept, be sure to remember! In actual development, abstract classes generally have abstract methods, otherwise the abstract class will lose its meaning and be no different from an ordinary class!

If an ordinary class A inherits an abstract class B, the subclass A must implement all the abstract methods of the parent class B. If subclass A does not implement the abstract method of parent class B, subclass A must also be defined as an abstract class, that is, an abstract class.

Interface as I understand it

Interface can be said to be a special case of abstract class. Abstract class and interface are two There are too many similarities and too many differences. In contrast, an interface is more like an abstraction of behavior!

1. Interface characteristics

1),

methods in the interface default to public abstractType, the member variable in the interface type is not written and defaults to public static final. 2), the interface has no construction method
3), the interface can implement "multiple inheritance", a class can implement multiple interfaces, the implementation format is to directly separate them with commas.

2. Must know about interfaces

Interfaces can only contain

public static final variables. If not written, the default is public static final, modified with private will cause compilation failure.

All methods in the interface will be implicitly designated as

public abstract methods and can only be public abstract methods, using other keywords, such as Modifications such as private, protected, static, final will fail to compile.

3. Interface misunderstandings

Many articles on the Internet say that all methods in the interface are abstract methods. The blogger went back and did some research and found that in fact it is not enough. Seriously, let’s just look at a simple program

package InterfaceDemo;

interface AA{   //接口AA
   default void hh(){
       System.out.println("123");
   };
}

class BB implements AA{  //实现接口
    
}

public class InterfaceDesign {

    public static void main(String[] args) {
        AA a=new BB(); //通过实现类创建实例
        a.hh();
    }
}
运行结果: 123
Copy after login

显然hh方法并不是抽象方法,但是这样设计就失去接口的意义了,实际开发中不会出现这样的代码,确实有点专牛角尖的韵味,所以我也不否认网上的言论,只是觉得不够严谨,我觉得大家还是注意一下比较好...如果面试官听到你这样的回答,可能对你刮目相看,会认为你是一个对知识极度向往、探索以及有个人思维想法的学习者 ~说白了,就是杠精,这里杠精是褒义词~

抽象类和接口本质区别

抽象类和接口本质区别主要从语法区别和设计思想两方面下手

1、语法区别

1.抽象类可以有构造方法,接口中不能有构造方法。

2.抽象类中可以有任何类型成员变量,接口中只能有public static final变量

3.抽象类中可以包含非抽象的普通方法,接口中的可以有非抽象方法,比如deaflut方法

4.抽象类中的抽象方法的访问类型可以是publicprotected和(默认类型,虽然 eclipse下不报错,但应该也不行),但接口中的抽象方法只能是public类型的,并且默认即为public abstract类型。

5.抽象类中可以包含静态方法,接口中不能包含静态方法

6.抽象类和接口中都可以包含静态成员变量,抽象类中的静态成员变量的访问类型可以任意,但接口中定义的变量只能是public static final类型,并且默认即为public static final类型。

7.一个类可以实现多个接口,但只能继承一个抽象类。

2、设计思想区别

对于抽象类,如果需要添加新的方法,可以直接在抽象类中添加具体的实现(相当于写普通类的普通方法并添加方法体的实现代码),子类可以不进行变更;而对于接口则不行,如果接口进行了变更,则所有实现这个接口的类都必须进行相应的改动。这一点应该很好理解。

从设计角度来讲抽象类是对一种对类抽象,抽象类是对整个类整体进行抽象,包括属性、行为。而接口是对行为的抽象,接口是对类局部(行为)进行抽象。从某一角度来讲,接口更像是抽象的抽象!

怎么理解上面这段话呢?

理解二者设计思想的区别从程序员宜春和花姑娘(一头可爱的小母猪)的故事开始,程序员宜春每天过着三点一线的生活,不是吃就是睡觉,闲暇之余还会敲敲代码,而花姑娘就厉害了,每天都是一点一线的生活,不是吃就是睡觉,闲暇之余不是吃就是睡觉。程序员宜春和花姑娘都过着幸福安逸的生活,突然有一天,风起云涌,天射大便~天色大变~,万恶的产品经理来需求了,要设计一个程序员宜春和花姑娘的一个程序,要求使用抽象类或者接口去设计,这个时候你会怎么去设计,下面给出两个设计方案...

方案一:使用抽象类设计,分别设计eat、sleep、qiaoDaiMa方法,具体代码如下:

abstract class Myclass{
    public abstract void eat();
    public abstract void sleep();
    public abstract void qiaoDaiMa();
  }
Copy after login

方案二:使用接口设计,分别设计eat、sleep、qiaoDaiMa方法,具体代码如下:

interface Myclass{
    public abstract void eat();
    public abstract void sleep();
    public abstract void qiaoDaiMa();
  }
Copy after login

显然,不管是哪个类继承抽象类或者实现上面的接口,都会出现同样的状况:重写它们的抽象方法。
如果有一百个程序员宜春,上面的设计都是很好地得到解决。但是到花姑娘身上就不管用了,花姑娘不会敲代码这种高端操作啊!一百个花姑娘都重写的qiaoDaiMa方法都没有意义啊,显然这样设计有问题。

从上面可以看出,eat、sleep对于qiaoDaiMa方法不是同一范畴内的行为(方法)。实际上我们可以这样设计:定义一个抽象类,包含eat、sleep方法,再定义一个接口包含qiaoDaiMa方法,具体代码如下:

abstract class Myclass{
    public abstract void eat();
    public abstract void sleep();
   }

interface MyclassTwo{
    public abstract void qiaoDaiMa();
  }
  
class YiChun extends Myclass implements MyclassTwo{

          @Override
          public void eat() {
              
          }

          @Override
          public void sleep() {

          }

          @Override
          public void qiaoDaiMa() {

          }
      }
Copy after login

我们只要让一百个程序员宜春继承抽象类并实现接口就好了,而花姑娘就直接继承抽象类就好了。这样一设计,堪称完美...

同样的,这样讲述是很不负责的,为啥捏?因为你会发现,这样设计不管是抽象类还是接口好像没有什么区别,刚才的抽象类换成接口,接口换成抽象类,实现效果也一致,代码如下:

interface Myclass{
    public abstract void eat();
    public abstract void sleep();
   }

abstract class MyclassTwo{
    public abstract void qiaoDaiMa();
  }
Copy after login

所以,为了讲解清晰设计思想区别,程序员宜春和花姑娘的故事不得不继续讲下去...

我们都知道,可爱的小母猪一般都是粉色的对吧,这个时候我们的产品经理又改需求了。啥?产品经理家中一百只小猪有一只是黑白sai的,额...

万恶的产品经理只会无理改需求,可是产品经理永远不会知道他一味逼程序员,程序员自己都不知道自己有多优秀!

我们都知道,可爱的小母猪一般都是粉色的对吧,这个时候我们的产品经理又改需求了。啥?产品经理家中一百只小猪有一只是黑白sai的,额...

万恶的产品经理只会无理改需求,可是产品经理永远不会知道他一味逼程序员,程序员自己都不知道自己有多优秀!

那么这个时候,我们都知道,抽象类和接口都是可以有成员变量的,只不过接口比较苛刻只能是public static final正是因为这一点!抽象类和接口的设计精髓就在这里了,这个时候我们这样设计:

interface Myclass{
    public abstract void eat();
    public abstract void sleep();
   }

abstract class MyclassTwo{
    String color="red";
    public abstract void qiaoDaiMa();
  }
Copy after login

让宜春类这样设计

package AbstractTest;

interface Myclass {
    public abstract void eat();

    public abstract void sleep();
}

abstract class MyclassTwo {
    String color = "red";

    public abstract void qiaoDaiMa();
}

class YiChun extends MyclassTwo implements Myclass {

    @Override
    public void eat() {

    }

    @Override
    public void sleep() {

    }

    @Override
    public void qiaoDaiMa() {

    }
}

public class AbstractDemo {
    public static void main(String[] args) {
        YiChun yc = new YiChun();
    }

}
Copy after login

然而宜春对于color这个属性可以是不理睬的,可以当做不存在,除非宜春不嫌弃自己也是一只红sai佩奇哈哈哈....

而花姑娘类就要注意了!然后让产品经理家中的100只小猪设计代码如下;

package AbstractTest;

interface Myclass {
     public abstract void qiaoDaiMa();
}

abstract class MyclassTwo {
    String color = "red";

    public abstract void eat();
    public abstract void sleep();
  
}

class Pig extends MyclassTwo {

    @Override
    public void eat() {

    }

    @Override
    public void sleep() {

    }

}

public class AbstractDemo {
    public static void main(String[] args) {
        Pig p = new Pig ();
        String color = "blackWhite";
        System.out.println(color);
    }

}
Copy after login

其余的99只花姑娘就直接不用动了也就是不需要String color = "blackWhite";这一句代码,它的color属性默认是red了...

这个时候抽象类和接口就不能更换了,从而抽象类和接口的设计思想就很清晰了,你何识着咩啊~

本文来自 java入门 栏目,欢迎学习!

The above is the detailed content of In-depth understanding of abstract classes and interfaces in Java. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:cnblogs.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