Skip to main content

classes in dart

Skeliton of classes in Dart


classes in dartclass ClassName {

  // Fields (properties) go here
  type propertyName;

  // Constructor(s) go here
  ClassName(this.propertyName); // Constructor shorthand


  // Methods go here
  returnType methodName(parameters) {

    // Method body
  }
}

Example
class Person {
  String name;
  int age;

  // Constructor
  Person(this.name, this.age);

  // Method
  void sayHello() {
    print("Hello, my name is $name, and I am $age years old.");
  }
}

void main() {
  // Creating an instance of the Person class
  var person = Person("Alice", 30);

  // Accessing fields and calling methods
  print(person.name); // Output: Alice
  print(person.age);  // Output: 30
  person.sayHello();  // Output: Hello, my name is Alice, and I am 30 years old.
}

Extending a Class in Dart

Certainly! In object-oriented programming, there are several important concepts related to classes and their behavior. Two of these concepts are polymorphism and abstraction. Let’s explore them in more detail:

  1. Polymorphism:

    Polymorphism is the ability of different objects or classes to respond in a unique way to the same message or method call. It allows you to write code that can work with objects of different classes in a consistent manner. Polymorphism is achieved through inheritance and interfaces (in languages like Dart, interfaces are called abstract classes).

    There are two main types of polymorphism:

    • Compile-time Polymorphism (Static Binding): This is also known as method overloading. It occurs when you have multiple methods with the same name in a class, but they differ in the number or types of their parameters. The appropriate method to be called is determined at compile time based on the method signature.
    class Calculator {
      int add(int a, int b) {
        return a + b;
      }
    
      double add(double a, double b) {
        return a + b;
      }
    }
    
    • Run-time Polymorphism (Dynamic Binding): This is also known as method overriding. It occurs when a subclass provides a specific implementation for a method that is already defined in its superclass. The method that gets executed is determined at runtime based on the actual object’s type.
    class Animal {
      void makeSound() {
        print('Some generic animal sound');
      }
    }
    
    class Dog extends Animal {
      @override
      void makeSound() {
        print('Bark');
      }
    }
    
    class Cat extends Animal {
      @override
      void makeSound() {
        print('Meow');
      }
    }
    

    Polymorphism allows you to treat objects of different classes as instances of a common superclass or interface, which promotes code reusability and flexibility.

  2. Abstraction:

    Abstraction is the process of simplifying complex systems by breaking them into smaller, more manageable parts and focusing on the relevant details while hiding unnecessary complexities. In object-oriented programming, abstraction is often achieved through abstract classes and interfaces.

    • Abstract Class: An abstract class is a class that cannot be instantiated on its own and may contain abstract methods (methods without an implementation). Subclasses of an abstract class must provide implementations for these abstract methods.
    abstract class Shape {
      double getArea(); // Abstract method without an implementation
    }
    
    class Circle extends Shape {
      double radius;
    
      Circle(this.radius);
    
      @override
      double getArea() {
        return 3.14 * radius * radius;
      }
    }
    
    • Interface: In Dart, interfaces are defined using abstract classes. An interface defines a contract that implementing classes must adhere to, ensuring that specific methods or properties are present in those classes.

    Abstraction allows you to define a common structure or interface that multiple classes can adhere to while allowing each class to provide its own unique implementation. It helps in managing complexity and enforcing a consistent structure in your code.

Polymorphism and abstraction are fundamental principles of object-oriented programming and play a significant role in creating flexible, maintainable, and extensible software systems.
what happend if i don’t use @override method in Dart
In Dart, using the @override annotation is not strictly required, but it is highly recommended when you intend to override a method from a superclass or implement a method from an interface (abstract class). While your code will still work without @override, using it has several benefits:

  1. Code Clarity: Adding @override makes your code more explicit and clear. It indicates your intention to override a method, which can be helpful for you and other developers who read the code.

  2. Compiler Warnings: When you use @override, the Dart analyzer (a tool that checks your code for errors and warnings) can provide warnings if the method you intended to override doesn’t match the method in the superclass or interface. This can help catch errors early in the development process.

  3. Documentation: It serves as a form of documentation, indicating that a method is intended to override a superclass method or implement an interface method. This can be useful for documentation generation tools and code editors.

Here’s an example to illustrate the importance of @override:

class Animal {
  void makeSound() {
    print('Generic animal sound');
  }
}

class Dog extends Animal {
  void makeSound() {
    print('Bark');
  }
}

In this example, the Dog class is intended to override the makeSound method from the Animal class. However, if you make a mistake in the method name or signature in the Dog class, the Dart analyzer won’t catch it without @override. For example:

class Dog extends Animal {
  void makeSounds() {
    // This is a mistake, but Dart won't give you a warning without @override
    print('Bark');
  }
}

In the above code, the makeSounds method in the Dog class does not actually override the makeSound method in the Animal class, but Dart won’t provide any warnings or errors. Using @override helps detect such issues:

class Dog extends Animal {
  @override
  void makeSounds() {
    // Now, Dart will give you a warning because @override doesn't match the superclass method
    print('Bark');
  }
}

In summary, while not using @override won’t cause your code to break, it’s considered a best practice in Dart to use it when you intend to override methods to catch potential errors and improve code clarity.

Comments

Popular posts from this blog

Is Dart easy for Beginners?

Lets look up few question on dart which help us to understand whether dart is easy or not. Introduction: Dart syntax are derived from java,c++ and mostly from javascript.It has c like syntax .Hence it is beginner friendly untill you understand the concept of classes. Hence here are few Questions on Dart programming language. Dart Question Question on Dart 1) For what iterable Collection in dart? Ans : The iterable Collection in dart :The  Iterable  class—for example  List  and  Set.  Iterables are basic building blocks for all sorts of Dart applications, and you’re probably already using them, even without noticing. This codelab helps you make the most out of them. 2 )What are type of loops in dart programming? Ans :/ for in loop ,switch Dart programming language supports several types of loops for controlling the flow of execution. Here are the main types of loops in Dart: For Loop: The for loop is used to iterate a specific number of times. It consists...

How To Change The Owner Of A Directory Using Python?

Introduction: To change the permission of a directory or file in python you needed to know two thing your user name and user group you wanted to change I will going to describe in detail how to know your users on your computer and user group present on your computer, whether you are the window or linux or mac. Syntax : There are three main commands we can use are 1st command(main command) os.chown(directory_name,userid,groupid) Parameters: userid - user id is the parameter used to specify the user id. groupid - Is the group id used for specifying the group of the group id. 2nd command: usr.getpwnam(new_owner_user).pw_uid Above function returns user id. when username is passed as argument. 3rd Command: grp.getgrnam(new_owner_group).gr_gid Above function returns group id. when groupname is passed as argument. Sample Program : Python3 import os # Directory path you want to change ownership for directory_path = '/tmp/directory' # New owner user and group new_owner_user = 'ch...

Best Linux distros of 2023

  Introduction Linux, the open-source operating system, has a plethora of distributions tailored to diverse user needs. These distributions, or "distros," vary in design, focus, and functionalities, making Linux a versatile choice. In this article, we'll explore ten noteworthy Linux distributions and delve into their unique features and capabilities. Distro 1 - Ubuntu Ubuntu is one of the most popular Linux distributions. It's known for its user-friendly interface and robust community support. Ubuntu is based on Debian and offers a balance between ease of use and powerful features. Features of Ubuntu: Desktop Environment : Utilizes the intuitive GNOME desktop environment, providing a clean and efficient interface. Software Repository: Offers an extensive software repository accessed through the APT package manager, ensuring a vast selection of applications. Security and Updates: Regularly provides updates and security patches to enhance system stability and protect ...