abstract class Flyable {
void fly();
}
class Bird implements Flyable {
@override
void fly() {
print('Bird is flying!');
}
}
class Airplane implements Flyable {
@override
void fly() {
print('Airplane is flying!');
}
}
void main() {
Bird bird = Bird();
Airplane airplane = Airplane();
bird.fly(); // Output: Bird is flying!
airplane.fly(); // Output: Airplane is flying!
}
Explanation
Interface Definition:
The Flyable class is declared as abstract, making it an interface.
It defines a single method, fly(), which must be implemented by any class that implements Flyable.
Class Implementations:
Both Bird and Airplane classes implement the Flyable interface.
They provide their own specific implementations for the fly() method.
Object Creation and Method Calls:
Objects of Bird and Airplane are created.
When bird.fly() and airplane.fly() are called, the respective fly() methods are executed.
What is an Interface?
In Dart, an interface is a way to define a contract that classes can implement. An interface specifies what methods and properties a class must include, but it doesn't provide the implementation. In Dart, all classes can act as interfaces.
In Dart, an interface defines a contract that a class must adhere to.
It specifies a set of methods that a class must implement.
Interfaces themselves cannot have any concrete implementations; they only define the structure.
An interface is created by declaring a class or using the abstract keyword.
Any class can act as an interface by being implemented.
When a class implements an interface, it must override all the methods and properties defined in the interface.
In Dart programming, an interface is a way to define a contract for classes, meaning that any class that implements an interface must provide implementations for all the methods defined in that interface. Dart does not have a special keyword like interface (as in other languages such as Java), but any class can act as an interface. The concept of an interface is based on a class having a set of methods that other classes can implement.
Interfaces in Dart are simply classes that other classes can implement.
A class that implements an interface must provide an implementation for all the methods defined by that interface.
Dart supports multiple interface implementation, so a class can implement multiple interfaces.
Benefits of Interfaces
Enforces Structure: Ensures that classes adhere to a specific contract.
Improved Code Organization: Helps organize code into well-defined modules.
Increased Flexibility: Allows for more flexible and interchangeable components.
Loose Coupling: Promotes loose coupling between classes, making the system more maintainable.
Code Reusability: You can define common behavior that multiple classes can share.
Polymorphism: You can treat objects of different classes in a uniform way (e.g., calling makeSound() on Dog and Cat).
In Summary
Interfaces in Dart provide a powerful mechanism for defining contracts and ensuring that classes adhere to specific behaviors. They promote code organization, flexibility, and maintainability by enforcing a consistent structure across different parts of your application.
Shape class: The class Shape defines an abstract method area() that serves as the interface.
Rectangle and Circle classes: Both of these classes implement the Shape interface and provide their own implementations of the area() method.
main() function: In the main() function, we create objects of type Shape (but instantiate them as Rectangle and Circle) and call the area() method.
Let's walk through a simple example to demonstrate how interfaces work in Dart.
Step 1: Define an Interface
We'll start by defining an interface using a class. In this case, the interface will describe a Shape with a method area().
// Define an interface (class) called Shape
abstract class Shape {
double area(); // Abstract method, must be implemented by any class that implements this interface
}
Step 2: Implement the Interface
Now, let's define two classes (Rectangle and Circle) that implement the Shape interface.
// Rectangle class implementing Shape interface
class Rectangle implements Shape {
double width;
double height;
Rectangle(this.width, this.height);
// Implement the area method
@override
double area() {
return width * height;
}
}
// Circle class implementing Shape interface
class Circle implements Shape {
double radius;
Circle(this.radius);
// Implement the area method
@override
double area() {
return 3.14 * radius * radius;
}
}
Step 3: Using the Interface
Finally, let's create instances of Rectangle and Circle, and use the area() method.
void main() {
// Create objects of Rectangle and Circle
Shape rectangle = Rectangle(5.0, 10.0);
Shape circle = Circle(7.0);
// Print the area of each shape
print('Area of Rectangle: ${rectangle.area()}');
print('Area of Circle: ${circle.area()}');
}
Area of Rectangle: 50.0
Area of Circle: 153.94
Decoupling code: Interfaces allow you to decouple the implementation from the code that uses the interface.
Multiple inheritance: Dart allows a class to implement multiple interfaces, allowing greater flexibility in design.
Example of Multiple Interface Implementation:
// Define another interface
abstract class Drawable {
void draw();
}
class Rectangle implements Shape, Drawable {
double width;
double height;
Rectangle(this.width, this.height);
@override
double area() {
return width * height;
}
@override
void draw() {
print("Drawing Rectangle");
}
}
void main() {
Rectangle rectangle = Rectangle(5.0, 10.0);
print('Area: ${rectangle.area()}');
rectangle.draw();
}
Sure! Here are 10 examples showcasing how to use interfaces in Dart. Dart doesn’t have a dedicated interface keyword; any class can serve as an interface, and classes that implement an interface must provide implementations for its methods.
A simple program where a Printable interface is implemented by multiple classes.
class Printable {
void printDetails();
}
class Document implements Printable {
@override
void printDetails() {
print("Printing document details...");
}
}
class Photo implements Printable {
@override
void printDetails() {
print("Printing photo details...");
}
}
void main() {
Printable doc = Document();
Printable pic = Photo();
doc.printDetails();
pic.printDetails();
}
A class implementing multiple interfaces.
class Drawable {
void draw();
}
class Resizable {
void resize();
}
class GraphicElement implements Drawable, Resizable {
@override
void draw() {
print("Drawing graphic element.");
}
@override
void resize() {
print("Resizing graphic element.");
}
}
void main() {
GraphicElement element = GraphicElement();
element.draw();
element.resize();
}
An interface to handle different payment methods.
class PaymentMethod {
void processPayment(double amount);
}
class CreditCard implements PaymentMethod {
@override
void processPayment(double amount) {
print("Processing credit card payment of \$${amount}");
}
}
class PayPal implements PaymentMethod {
@override
void processPayment(double amount) {
print("Processing PayPal payment of \$${amount}");
}
}
void main() {
PaymentMethod credit = CreditCard();
PaymentMethod paypal = PayPal();
credit.processPayment(100.0);
paypal.processPayment(50.0);
}
A program using an interface for different notification types.
class Notifiable {
void sendNotification();
}
class EmailNotification implements Notifiable {
@override
void sendNotification() {
print("Sending email notification.");
}
}
class SMSNotification implements Notifiable {
@override
void sendNotification() {
print("Sending SMS notification.");
}
}
void main() {
Notifiable email = EmailNotification();
Notifiable sms = SMSNotification();
email.sendNotification();
sms.sendNotification();
}
An interface defining behaviors for different vehicle types.
class Vehicle {
void start();
void stop();
}
class Car implements Vehicle {
@override
void start() {
print("Car started.");
}
@override
void stop() {
print("Car stopped.");
}
}
class Bike implements Vehicle {
@override
void start() {
print("Bike started.");
}
@override
void stop() {
print("Bike stopped.");
}
}
void main() {
Vehicle car = Car();
Vehicle bike = Bike();
car.start();
car.stop();
bike.start();
bike.stop();
}
An interface to calculate area for different shapes.
class Shape {
double area();
}
class Circle implements Shape {
double radius;
Circle(this.radius);
@override
double area() {
return 3.1416 * radius * radius;
}
}
class Rectangle implements Shape {
double width, height;
Rectangle(this.width, this.height);
@override
double area() {
return width * height;
}
}
void main() {
Shape circle = Circle(5.0);
Shape rectangle = Rectangle(4.0, 6.0);
print("Circle area: ${circle.area()}");
print("Rectangle area: ${rectangle.area()}");
}
A program where different authentication methods implement an interface.
class Authenticator {
void authenticate(String username, String password);
}
class EmailAuthenticator implements Authenticator {
@override
void authenticate(String username, String password) {
print("Authenticating $username with Email.");
}
}
class PhoneAuthenticator implements Authenticator {
@override
void authenticate(String username, String password) {
print("Authenticating $username with Phone.");
}
}
void main() {
Authenticator emailAuth = EmailAuthenticator();
Authenticator phoneAuth = PhoneAuthenticator();
emailAuth.authenticate("user1", "password123");
phoneAuth.authenticate("user2", "password456");
}
A program using interfaces for logging.
class Logger {
void log(String message);
}
class ConsoleLogger implements Logger {
@override
void log(String message) {
print("Console log: $message");
}
}
class FileLogger implements Logger {
@override
void log(String message) {
print("Writing '$message' to file.");
}
}
void main() {
Logger consoleLogger = ConsoleLogger();
Logger fileLogger = FileLogger();
consoleLogger.log("Starting application");
fileLogger.log("Application started successfully");
}
A program where different animals implement an interface for making sounds.
class Animal {
void makeSound();
}
class Dog implements Animal {
@override
void makeSound() {
print("Dog barks");
}
}
class Cat implements Animal {
@override
void makeSound() {
print("Cat meows");
}
}
void main() {
Animal dog = Dog();
Animal cat = Cat();
dog.makeSound();
cat.makeSound();
}
An interface for different types of file operations.
class FileOperations {
void readFile();
void writeFile(String content);
}
class TextFile implements FileOperations {
@override
void readFile() {
print("Reading text file...");
}
@override
void writeFile(String content) {
print("Writing to text file: $content");
}
}
class PDFFile implements FileOperations {
@override
void readFile() {
print("Reading PDF file...");
}
@override
void writeFile(String content) {
print("Writing to PDF file: $content");
}
}
void main() {
FileOperations txt = TextFile();
FileOperations pdf = PDFFile();
txt.readFile();
txt.writeFile("Hello, World!");
pdf.readFile();
pdf.writeFile("Hello, Dart!");
}