Jump to content

[SOLVED] Usage of Abstract Classes


Tertius

Recommended Posts

Abstract classess provide common interface for concrete classess that extend them. This is useful in many design patterns, where the user does not have to know what is the exact concrete class of the object it interacts with.

 

For example

 

<?php

//Used for connection to database
abstract class dbConnection {
  abstract public function connect();
}

//Used for connection to MySQL
class mysqlConnection extends dbConnection{
  public function connect() {
     //connect to MySQL
  }
}

//Used for connection to PostgreSQL
class pgsqlConnection extends dbConnection{
  public function connect() {
    //Connect to PostgreSQL
  }
}

 

Now, other objects, classess etc. don't need to know, if we're connecting to MySQL or PostgreSQL. They just need to know, that the class has type 'dbConnection' and as such has all the methods defined by this class.

 

Link to comment
Share on other sites

I personally liked the example given in my java lecture last week. Consider a set of shape classes - Square, Circle etc. Now, we want certain methods to be common to all shapes. We might have a draw() method. We also want to be able to call this method without knowing what shape we're drawing. One approach might be to have a parent class - Shape, which defines the methods we want the classes to have in common and all other shapes to inherit and overload. For example:

 

class Shape{
void draw(){
	//draw method
}
}

class Circle extends Shape{
void draw(){
	//special information for drawing a circle
}
}

class Square extends Shape{
void draw(){
	//special information for drawing a square
}
}

 

However, we have a problem. What should happen if you call draw() on a Shape class? What does a general shape look like? In order to prevent confusion and miss-use of the classes, you might define Shape to be an abstract class and draw to be an abstract method, or you might make Shape an interface. In either case, the method draw() can't be called unless you have a particular shape.

 

It helped me understand a bit anyway :P

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.