Static Abstract and Interface Classes
Moderator: General Moderators
Static Abstract and Interface Classes
Ok, I've been reading and re-reading books and articles all over the internet to try and understand these but just can't.
I vaguely understand static methods and properties, It's so that you can access methods and properties from outside the class without having to class the class and create and object of it. Is that right?
But then it moves on to abstract and i just get lost. you create an abstract class, that can't get called as an object but that can have other classes extend of from it. Is that right? And if so what's the point? You then have to create an abstract method in the class and the 'children classes' HAVE to call that method or be called abstract themselves????
Then interface classes, i might have a better understanding of these once i can get my head around abstract ones. But from the examples I've seen interface classes are just filled with abstract methods??
Can someone please shed some light on this??
Many Thanks for your time.
Chris
I vaguely understand static methods and properties, It's so that you can access methods and properties from outside the class without having to class the class and create and object of it. Is that right?
But then it moves on to abstract and i just get lost. you create an abstract class, that can't get called as an object but that can have other classes extend of from it. Is that right? And if so what's the point? You then have to create an abstract method in the class and the 'children classes' HAVE to call that method or be called abstract themselves????
Then interface classes, i might have a better understanding of these once i can get my head around abstract ones. But from the examples I've seen interface classes are just filled with abstract methods??
Can someone please shed some light on this??
Many Thanks for your time.
Chris
-
letseatfood
- Forum Newbie
- Posts: 9
- Joined: Mon Aug 02, 2010 3:50 pm
Re: Static Abstract and Interface Classes
Hi @ChrisBull -
I have struggled quite a bit in this area myself.
I am no expert, but hopefully I can help your understanding some. In my experience, I didn't start to understand the necessity of static methods, abstract classes, and interfaces until I started working on multiple projects at a time which were similar, but not the same.
Important Note: I rarely start building a static method, abstract class, or interface from the start (well now I do, but it's taken a while). More commonly, I realize that a regular class that I have spent some time constructing can be modified or re-factored into these things, and I try my best to do so, because I'll thank myself when working on future projects.
Static Methods
I typically realize I need to turn a method into a static method when I realize that it does something really useful that I need in numerous places outside of the class or in sub-classes of the class. For example, I have a function that "swaps" two array values:
I would use the above class like this:
A couple points about the `swap()` method above:
The above "non-static" version of the `swap()` method is cumbersome in use, as it will take two lines to use it:
While it may seem trivial in this example, the extra line of code just so I can use my swap() method is aggravating during development, especially when I might need that method in numerous places in one project.
Abstract Classes
I often realize after I have written a class that is specific to a current problem/project that I can make an abstract version of it. So, if I can't figure out how to write a useful abstract class when I start a project, I just start working on the project with the intent to abstract the classes at a later time.
Abstract classes are truly incredible, but in my opinion, they shine mostly when I am working on large projects. It is important to note that I currently work independently, so I don't work with a team, but I understand that abstract classes also really shine when working on a team. I have come to realize, though, that working independently is like working with different people (my past, present, and future self). This is because, after I work on a project, let's call it project "A", then, a few days later, I have to switch mental gears and work on project "B", and then a few days later work on project "A" again, it is often like looking a totallly different individual's work when I return to that first project at a later time. Abstract classes have helped me to clarify the usage and intent of classes when I have not worked on a project in a while and don't have time or energy to read the code line-by-line to figure it out.
Okay, on to an example...
Recently, I have been using PHP to write some content management systems for websites which have multiple pages, each with different and unique content (how novel, I know
). Now, it would be tedious, easy to make errors, and time-wasting to have to re-write or copy and paste the same chunks of HTML code on every single page of the website. And, when I moved on to another, similar, website project, I'd have to start this tedious process all over again. The solution here is an abstract class. I sat down and thought about every part of a basic HTML page that would be needed on every (or most) of the pages in my current project. I then created an abstract class that contained these re-usable chunks of HTML, with the intent to sub-class this abstract class on each unique page.
Here is an example (really simplified for this example) of an abstract HTML page:
Now, one point about the `AHTMLPage` class above is that it is useless on it's own. I made it very generalized and I think of it as a template for projects that require HTML pages.
Now, I will start to get more specific and sub-class AHTMLPage for a specific project:
That's it! Now, to display the StartPage class I do this:
I will only need to override the body() method for each unique page of the Car Mechanic website. I will be saved from writing tons of the same HTML over and over again. This also ensures that less errors in typing the HTML occur.
Well, I don't have enough steam to continue on with interfaces. Hopefully that helps some!
I have struggled quite a bit in this area myself.
I am no expert, but hopefully I can help your understanding some. In my experience, I didn't start to understand the necessity of static methods, abstract classes, and interfaces until I started working on multiple projects at a time which were similar, but not the same.
Important Note: I rarely start building a static method, abstract class, or interface from the start (well now I do, but it's taken a while). More commonly, I realize that a regular class that I have spent some time constructing can be modified or re-factored into these things, and I try my best to do so, because I'll thank myself when working on future projects.
Static Methods
I typically realize I need to turn a method into a static method when I realize that it does something really useful that I need in numerous places outside of the class or in sub-classes of the class. For example, I have a function that "swaps" two array values:
Code: Select all
//Sill class name just for the example
class MyClass
{
//This method "swaps" or "exchanges" the value at $list[$indexA] with the value at $list[$indexB]
public static function swap($list, $indexA, $indexB)
{
$valueA = $list[$indexA];
$list[$indexA] = $list[$indexB];
$list[$indexB] = $valueA;
return $list;
}
}
Code: Select all
//Here is a list (array) of values
$myList = array('first', 'second', 'third', 'fifth', 'sixth', 'fourth');
//I need to swap the 'fifth' and 'fourth' string values
//Call the 'swap' function
$list = MyClass::swap($myList, 3, 5);
- It is "generic", meaning it does not contain any unique values, data, or usage. It is a general use method that can be used on any array to swap any two of that array's values. So, if I store `MyClass` in a single directory on my computer, I can include that class in many different projects where I would need to swap two array values.
- It takes only one line of code to call the `MyClass::swap()` method, instead of multiple lines, which a non-static, public method would take (Example below)
Code: Select all
class MyClass2
{
public function swap($list, $indexA, $indexB)
{
$valueA = $list[$indexA];
$list[$indexA] = $list[$indexB];
$list[$indexB] = $valueA;
return $list;
}
}
Code: Select all
//You have to create an instance of the MyClass2 class first:
$myClass2Instance = new MyClass2();
//After MyClass2 has been instantiated, then you can call the `swap()` method:
$list = $myClass2Instance->swap($list, 3, 5);
Abstract Classes
I often realize after I have written a class that is specific to a current problem/project that I can make an abstract version of it. So, if I can't figure out how to write a useful abstract class when I start a project, I just start working on the project with the intent to abstract the classes at a later time.
Abstract classes are truly incredible, but in my opinion, they shine mostly when I am working on large projects. It is important to note that I currently work independently, so I don't work with a team, but I understand that abstract classes also really shine when working on a team. I have come to realize, though, that working independently is like working with different people (my past, present, and future self). This is because, after I work on a project, let's call it project "A", then, a few days later, I have to switch mental gears and work on project "B", and then a few days later work on project "A" again, it is often like looking a totallly different individual's work when I return to that first project at a later time. Abstract classes have helped me to clarify the usage and intent of classes when I have not worked on a project in a while and don't have time or energy to read the code line-by-line to figure it out.
Okay, on to an example...
Recently, I have been using PHP to write some content management systems for websites which have multiple pages, each with different and unique content (how novel, I know
Here is an example (really simplified for this example) of an abstract HTML page:
Code: Select all
//Notice the `abstract` keyword.
//Also, I always prepend my abstract class names with an A, as a message to myself that the class is abstract
abstract class AHTMLPage
{
protected $title;
//meta() is intended to be overridden in sub-classes and called within the head() method
//You could use it to include project-specific references to JavaScript and CSS files in the <head> section of your HTML
abstract protected function meta();
//head() is intended to be overridden in sub-classes with project-specific HTML code
abstract protected function head();
//body() is intended to be overridden in sub-classes with project-specific HTML code
abstract protected function body();
//foot() is intended to be overridden in sub-classes with project-specific HTML code
abstract protected function foot();
//This is the method that you can use to display your HTML page
public function display()
{
$this->head();
$this->body();
$this->foot();
}
}
Now, I will start to get more specific and sub-class AHTMLPage for a specific project:
Code: Select all
class CarMechanicWebsiteHTMLPage extends AHTMLPage
{
//Notice I do not need to re-write the class property `$title`, it is inside of the AHTMLPage parent class and, since it is not private, is accessible to this class
//Constructor method to define the $title property
public function __construct($title)
{
$this->title = $title;
}
//Use this to describe CSS and JavaScript references
protected function meta()
{
?>
<link type="text/css" src="css/style.css" media="screen" />
<?php
}
//This method overrides the AHTMLPage::head() method, meaning it takes precedence over the one in AHTMLPage.
protected function head()
{
?>
<html>
<head>
<title><?php echo $this->title; ?></title>
</head>
<body>
<div id="header">
<h1>Car Mechanic Website</h1>
<p>Located on Some Street, in Baltimore, MD.</p>
</div>
<div id="main">
<?php
}
//Notice I do not override AHTMLPage::body() in this class. I will do so in another sub-class
//foot() is overriding AHTMLPage::foot()
protected function foot()
{
?>
</div>
<div id="footer">
<p>Copyright © 2010, Michael T. Moore, All Rights Reserved. http://www.miketmoore.com</p>
</div>
</body>
<?php
}
//No need to override AHTMLPage::display(), since I'll use it as is
}
Code: Select all
class StartPage extends CarMechanicWebsiteHTMLPage
{
protected function body()
{
?>
<h2>Welcome to Car Mechanic Website</h2>
<p>Relevant info about us here.</p>
<?php
}
}
Code: Select all
$htmlPage = new StartPage();
$startPage->display();
Well, I don't have enough steam to continue on with interfaces. Hopefully that helps some!
Re: Static Abstract and Interface Classes
Wow, this is the most detailed answer i have ever seen!
Thanks for your reply, i am working independently like you, and am about to start a large personal project but thought it best to read some more php books and articles before hand.
O.K, I understand static now thanks, and i think i understand abstract as well, It sort of acts as a template to the sub classes to make sure they have the same sort of functionality unlike normal subclasses which can choose to implement certain methods, is that right?
Thanks again for your reply, it was extremely helpful and i can imagine must have taken you a while.
Thanks for your reply, i am working independently like you, and am about to start a large personal project but thought it best to read some more php books and articles before hand.
O.K, I understand static now thanks, and i think i understand abstract as well, It sort of acts as a template to the sub classes to make sure they have the same sort of functionality unlike normal subclasses which can choose to implement certain methods, is that right?
Thanks again for your reply, it was extremely helpful and i can imagine must have taken you a while.
-
letseatfood
- Forum Newbie
- Posts: 9
- Joined: Mon Aug 02, 2010 3:50 pm
Re: Static Abstract and Interface Classes
No problem!
Re: Static Abstract and Interface Classes
Sorry, one last thing, the book i have, says that
The book is 'PHP Objects, patterns and practice' - I don't want to be breaking copyright laws or something.
But whats the point in having an abstract class that doesn't have any abstract methods? Seems like you would just use a normal class.'In most cases, an abstract class will contain at least one abstract methods.'
The book is 'PHP Objects, patterns and practice' - I don't want to be breaking copyright laws or something.
Re: Static Abstract and Interface Classes
The purpose of both abstract classes and interfaces is semantic more than anything else. It is a way to document your intent with code, though it provides some type checks (such as the instanceof keyword). In the case of the abstract class, the meaning is that a class should not be used as is, and you must extend it to use it.
An example of that would be a database table abstraction. All the methods can be concrete methods, however you must extend it and declare the table name for it to be usable. A good example of that would be the Zend_Db_Table_Abstract class from the Zend Framework.
An example of that would be a database table abstraction. All the methods can be concrete methods, however you must extend it and declare the table name for it to be usable. A good example of that would be the Zend_Db_Table_Abstract class from the Zend Framework.
Last edited by Eran on Fri Aug 20, 2010 12:32 pm, edited 1 time in total.
-
letseatfood
- Forum Newbie
- Posts: 9
- Joined: Mon Aug 02, 2010 3:50 pm
Re: Static Abstract and Interface Classes
Well, it's important to remember that, in PHP, an abstract class can contain abstract methods, but does not have too.
Why would an abstract class not have any abstract methods?
I'll use the AHTMLPage class as the start here.
Think of the AHTMLPage class as the most abstract (farthest away from concrete implementation). It has to be sub-classed to be used, since you cannot instantiate an abstract class directly.
If I create an abstract class named AJohnDoesWebsiteHTMLPage that extends AHTMLPage, I might override all of the methods from AHTMLPage inside of AJohnDoesWebsiteHTMLPage. But, since AJohnDoesWebsiteHTMLPage is still abstract, I have to sub-class it.
I do this so that all of the pages I am creating for John Doe's website are consistent in HTML structure, which is made possible by specifying the implementation within each of the methods ind AJohnDoesWebsiteHTMLPage. BUT - I might only partially implement one of the methods. For example, the body() method. I might add in some basic HTML code that will be in all of the body() methods (but could be changed in special cases.
Partial example:
Now, I can sub-class AJohnDoesWebsiteHTMLPage for each page in John Doe's website and just copy and paste the body() method that is partially implemented and then fill in the remaining information.
Honestly, though, I don't think this is the best example, but it would work. Ideally, you would create a class method for each of those <div> tags in the body() method.
Why would an abstract class not have any abstract methods?
I'll use the AHTMLPage class as the start here.
Think of the AHTMLPage class as the most abstract (farthest away from concrete implementation). It has to be sub-classed to be used, since you cannot instantiate an abstract class directly.
If I create an abstract class named AJohnDoesWebsiteHTMLPage that extends AHTMLPage, I might override all of the methods from AHTMLPage inside of AJohnDoesWebsiteHTMLPage. But, since AJohnDoesWebsiteHTMLPage is still abstract, I have to sub-class it.
I do this so that all of the pages I am creating for John Doe's website are consistent in HTML structure, which is made possible by specifying the implementation within each of the methods ind AJohnDoesWebsiteHTMLPage. BUT - I might only partially implement one of the methods. For example, the body() method. I might add in some basic HTML code that will be in all of the body() methods (but could be changed in special cases.
Partial example:
Code: Select all
abstract class AJohnDoesWebsiteHTMLPage extends AHTMLPage
{
//For this example, assume that all other methods of AHTMLPage are already implemented and I just didn't put them here to see (but you would in reality)
protected function body()
{
//Basic HTML structure that will be in most body() methods of this website
?>
<div id="section_a"></div>
<div id="section_b"></div>
<div id="news"></div>
<?php
}
}
Honestly, though, I don't think this is the best example, but it would work. Ideally, you would create a class method for each of those <div> tags in the body() method.
Re: Static Abstract and Interface Classes
ok, thanks again for everything!
Re: Static Abstract and Interface Classes
"Animal" is abstract. You can tell any animal class to speak. But a dog class might speak in a different way than a cat class. Interfaces make sure that when you tell the "animal" to speak its at least going to respond in some way. Thats the theory. That way you never accidentally tell a non-animal object (lets say a rock) to speak, and end up looking like a fool.
Also interfaces allow you to think "narrowly". If you're telling a dog to speak it might have a ton of functions for that. Bark(), Growl(). You could have a speaking interfaces that describes though, separate from its "movement" interface where you tell it to walk() & run(). So when you use this object later you only have to look at a "narrow" interface.
Abstract classes are the same but allow you to include functionality. A class can have many interfaces, but only one abstract superclass.
So then your functions can declare interfaces
As you type $animal-> your IDE should pop up with a list of all the commands all speaking animals share in common, just those commands nothing more nothing less. Allows you to add more "types" of speaking animals in the future.
Its analogous to real world things. Power plugs have an "interface" Most power devices can plug into the wall socket. Imagine a world where you had to get "adapters" for every device you want to plug in. A lot of companies already do that. Thats why its nice to have a common interface. Of course sometimes interfaces should be different (Ex. The interface for my power plug is and should be different then the one that plugs the mouse into my computer). But within a single "category" (Ex. computer peripherals) I want everything to follow the same interface as a user. Your code has users too, other programmers, and yourself. When we use code we want it to be plug & play, which is why we use interfaces when we write hardcore systems.
Also interfaces allow you to think "narrowly". If you're telling a dog to speak it might have a ton of functions for that. Bark(), Growl(). You could have a speaking interfaces that describes though, separate from its "movement" interface where you tell it to walk() & run(). So when you use this object later you only have to look at a "narrow" interface.
Abstract classes are the same but allow you to include functionality. A class can have many interfaces, but only one abstract superclass.
So then your functions can declare interfaces
Code: Select all
function doStuff( Speaking_Animal $animal )
{
$animal->speak();
}
Its analogous to real world things. Power plugs have an "interface" Most power devices can plug into the wall socket. Imagine a world where you had to get "adapters" for every device you want to plug in. A lot of companies already do that. Thats why its nice to have a common interface. Of course sometimes interfaces should be different (Ex. The interface for my power plug is and should be different then the one that plugs the mouse into my computer). But within a single "category" (Ex. computer peripherals) I want everything to follow the same interface as a user. Your code has users too, other programmers, and yourself. When we use code we want it to be plug & play, which is why we use interfaces when we write hardcore systems.