list of dots Digital Research Alliance of Canada logo  NSERC logo  University of Ottawa logo / UniversitĂ© d'Ottawa

User Manual    [Previous]   [Next]   

Abstract Methods

An abstract method is a method declaration with no implementation. These methods are to be implemented in classes with the specific behaviour intended.

Abstract methods can be defined in classes using the keyword "abstract", followed by the method's signature. By declaring a method abstract, the class containing it is abstract as well, meaning no instances of it can be created (the new keyword cannot be used to create an object of the class). The abstract class must have one or more subclasses that have concrete implementations of the abstract method.

An interface can only contain abstract methods, and the keyword is not needed. The usage of the abstract keyword in a trait declares a required method.

Example

//The class Person contains abstract 
//methods, which are inherited and 
//implemented by its subclass Student

//Person is abstract, but Student is a
//concrete class as it has no methods
//that are unimplemented.
class Person {
  abstract void method1();
  abstract void method2();
  void method3() {
    /* Implementation */
  }
}

class Student {
  isA Person;
  
  void method1() {
    /* Implementation */
  }
  void method2() {
    /* Implementation */
  }
}
      

Load the above code into UmpleOnline

 

Another Example

//The class Shape contains an abstract
//method, area, as well as a concrete
//method move, which has its implementation
//shared across all subclasses

//Shape is an abstract class, because it
//contains an abstract method
class Shape {
  color;
  Integer x;
  Integer y;
  
  abstract Double area();
  void move() {
    /* implementation */
  }
}

//Both Square and Circle are concrete
//classes as they implement all inherited
//abstract methods
class Square {
  isA Shape;
  Double width;
  Double height;
  
  Double area() {
    return getWidth()*getHeight();
  }
}

class Circle {
  isA Shape;
  Double radius;
  const Double PI = 3.1416;
  
  Double area() {
    return PI*radius*radius;
  }
}

class A {
  Square s;
  Circle c;
  
  void Test() {
    //The method implemented in Shape is
    //used
    s.move();
    c.move();
  
    //The methods implemented in their
    //respective classes are used
    s.area();
    c.area();
  }
}
      

Load the above code into UmpleOnline

 

Syntax


// Instructs a class or method to be abstract
abstract- : [=abstract] ;