Tertius Posted February 21, 2009 Share Posted February 21, 2009 hi, everyone, do you have any good example of good points of using Abstract classes? I wish to know more about why use Abstract Class. Link to comment https://forums.phpfreaks.com/topic/146292-solved-usage-of-abstract-classes/ Share on other sites More sharing options...
Mchl Posted February 21, 2009 Share Posted February 21, 2009 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 https://forums.phpfreaks.com/topic/146292-solved-usage-of-abstract-classes/#findComment-768059 Share on other sites More sharing options...
GingerRobot Posted February 21, 2009 Share Posted February 21, 2009 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 Link to comment https://forums.phpfreaks.com/topic/146292-solved-usage-of-abstract-classes/#findComment-768062 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.