search
HomeJavaWhen to use abstraction and when to use interfaces?

php editor Zimo will take you to explore the use opportunities of abstract classes and interfaces in Java. In Java programming, choosing when to use abstract classes and when to use interfaces is an important decision. This article will answer this common question for you and help you better understand how to choose the appropriate abstract class or interface in different situations.

Question content

I vaguely understand the difference between abstraction and interface, but what I simply cannot understand is when to use abstraction and when to use interface. What variables do I need to select an interface abstraction and vice versa? Most of the answers online are meant to show the difference, but even I understand them. I don’t know when is more appropriate.

Solution

The general old rule is: stick with interfaces until you are forced to write abstract classes.

interface in java is a non-instantiable type that defines a public interface that other types can choose to comply with.

    Interfaces can declare public methods, which must be defined by their implementers. All such methods are implicitly
  • abstract, so you do not need to use the word abstract.
  • In older versions of java, interfaces cannot have default implementations, so each method is
  • abstract. This is no longer the case, interfaces can now have a default implementation used in implementing classes unless replaced.
  • In the latest version of java, interfaces can declare
  • private helper methods. These can help with default implementations.
  • Interfaces can never have constructors or instance variables.
  • A class can
  • implement multiple interfaces.

abstract class is just a class that cannot be instantiated. Abstract classes do not need to define any abstract methods, although you will often want to do so.

    Abstract classes can declare methods with any visibility:
  • public, private, protected, and package-private.
  • Abstract classes can implement methods or keep them as
  • abstract. Methods in abstract classes are not implicit abstract and must be marked as such.
  • Abstract classes can have constructors,
  • extending classes must use super to call the constructor in its own constructor. Abstract classes can have instance variables of any visibility and they work just like instance variables in any parent class.
  • A class can only
  • extend one class, which can be an abstract class or a concrete class. The abstractness of a class does not change the number of superclasses it is allowed to have.

abstract classes should be the exception rather than the norm. You should use abstract classes if you need to maintain some internal state while also letting subclasses define your own behavior. A good example comes from the java swing gui library: AbstractButton. abstractbutton is an abstract parent for things that behave vaguely like buttons in windows, including buttons, toggle buttons, and items in menus. Anyone can subclass abstractbutton and implement its members to define a button-like display. But abstractbutton also has to maintain a lot of internal state (much of it from jcomponent) in order to communicate with the window and the overall swing api.

If you want to define a public interface for a collection of types, use

interface. If you want to provide a default implementation for some of these methods and use a java version released after 2014, use an interface. If you need a default implementation but are still stuck in the 2000s, use abstract classes. Regardless of java version, if you need private state (such as instance variables) or custom initialization (such as constructors), use abstract classes.

interface:

Suppose you have an interface, for example:

interface animal {
  string makenoise();
}

And several classes that implement animal:

class cat implements animal {
    string makenoise() {
        return "meow";
    }
}

class dog implements animal {
    string makenoise() {
        return "woof";
    }
}

Now you can use interfaces as return types, so methods can return

cat or dog.

string makeanimalmakenoise(int animalid) {
    animal animal = pretendanimalservice.getdogorcat(animalid);

    animal.makenoise();
}

Abstract class:

Suppose you have an abstract class:

abstract class animal {
    public string makenoise() {
        return "whistle";
    }

    abstract public string getname();
}

Now, any class that extends it needs to implement the

getname method:

class Cat extends Animal {
    String getName() {
        return "Pussy";
    }
}

class Dog extends Animal {
    String getName() {
        return "Fido";
    }
}

Both of the above classes implement the required

getname method, but they also have access to the parent class makenoise method, which can also be overridden if desired.

It is also important to note other differences, they are:

    You can only extend one abstract class, but you can implement multiple interface.
  • Interfaces should be used when different types should have the same method signatures; abstract classes should be used when implementations share common behavior.
  • They are not mutually exclusive.
  • Interfaces can only have public methods, while abstract classes can have public methods and protected methods.

The above is the detailed content of When to use abstraction and when to use interfaces?. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:stackoverflow. If there is any infringement, please contact admin@php.cn delete

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment