Classing{js} Tutorial

Abstract Classes

What is an Abstract Class?

an abstract class is a class that cannot be instantiated but can be inherited. Abstract classes are used to define a characterization that some group of classes will share but each of these classes will have a different implementation of one or more aspects of this characterization.

Take, for example, the Quadrilaterals which are polygons with four sides. All quadrilaterals have four sides , a circumference and an area. but each quadrilateral has a different method of claculating its area (like sqaures and rectangles).So, a Quadrilateral is represented with an abstract class and the Square and the Rectangle are childs of it.

How to Define an Abstract Class?

Defining an abstract class is done using classing.Abstract.Class in the following mannar

var ClassName = classing.Abstract.Class({
	/* Your defintion goes here */
});

				

Note that an abstract class must contain at least one abstract method. These abstract methods are those aspects of the characterization that differ among the group of the classes that share it. To mark a method as abstract its body must be empty and its wrapped with the classing.Abstract function (or the Abstract global shortcut) just like what we did with final and static. (If your abstract function is overloaded , each of the instances must have an empty body). Here's an example using the Quadrilateral case:

var Quadrilateral = classing.Abstract.Class({
	protected : {
		side1 : null,
		side2 : null,
		side3 : null,
		side4 : null
	},
	public : {
		Construct : Function.create(xTyped , [
			types(Number,Number,Number,Number),
			function(a,b,c,d) {
				this.side1 = a; this.side2 = b;
				this.side3 = c; this.side4 = d;
			}
		]),
		Circumference : Final(function(){
			return this.side1 + this.side2 + this.side3 + this.side4; 
		}),
		Area : Abstract(function(){})
	}
});

var Rectangle = classing.Class.Extends(Quadrilateral)({
	public : {
		Construct : Function.create(xTyped , [
			types(Number,Number),
			function(x,y) {
				base(x,y,x,y);
			}
		]),
		Area : function() {return this.side1 * this.side2;}
	}
});

var Square = classing.Class.Extends(Quadrilateral)({
	public : {
		Construct : Function.create(xTyped , [
			types(Number),
			function(s) {
				base(s,s,s,s);
			}
		]),
		Area : function(){return this.side1*this.side1;}
	}
});
				

Heads Up!

  • An abstract method cannot be defined in a concrete class.
  • If a concrete class inherits form an abstract class, it must implement all its abstract methods.
  • an abstract class can inherit form another abstrcat class leaving some or all of its abstract methods unimplemented.
  • An abstract method cannot override a concrete method.