[ACCEPTED]-What is an abstract class?-oop
- most commonly to serve as a base-class or interface (some languages have a separate
interface
construct, some don't) - it doesn't know the implementation (that is to be provided by the subclasses / implementing classes) - abstraction and re-use
- when the base-class can provide no meaningful default-implementation for a method (but allowing subclasses to re-use the non-abstract parts of the implementation; any fields, non-abstract methods, etc)
For example:
public abstract class Stream { /* lots of code, some abstract methods */ }
What the heck is a stream by itself? What 6 kind of stream? a stream to a file? a network? a 5 memory buffer? Each may have different and 4 unrelated ways of reading / writing, but 3 provide a common API. It makes no sense to create 2 just a Stream
, but via the abstract
class, you can code to the 1 Stream
API without knowing the details:
Stream s = CreateStream(...); // I don't *care* what kind of stream
s.Write(new byte[] {1,2,3,4,5});
s.Close();
Abstract (Base) classes give you semi-concrete 3 classes to implement your class hierarchy 2 against. They allow you to do several things:
- Consolidate common behavior (unlike an interface which only defines the contract)
- Provide default (and optionally override-able) implementations for functions
- Provide well defined branch points for inheritance hierarchies
- Control IoC injection points
The 1 list goes on.
1) What is the point of creating a class that can'y be instantiated?
Just because something is not instantiated 23 directly does not mean it is useful. An 22 abstract class plays an important role in 21 inheritance and can be very useful in class 20 design of its inherited classes.
For instance, I 19 have used abstract classes before to define 18 the basic structure of what a class must 17 conform to. Then I have defined inherited 16 classes based on that abstract class and 15 if I have missed a required method or something, it 14 can be picked up by the compiler.
What this 13 also allows you to do is associate inherited 12 classes together which means you can then 11 assume certain methods defined in the abstract 10 class will exist in the inherited classes 9 - which can be useful.
2) Why would anybody want such a class
Typically I use it 8 for ensuring that a series of inherited 7 classes have certain methods etc. For me 6 it is really useful for design of a structure 5 of a set of inherited classes.
3) What is the situation in which abstract classes become necessary?
I don't think 4 an abstract class is ever necessary, but 3 when used in certain circumstances it can 2 be useful and help to simplify the problem 1 you are solving.
An abstract class is one that cannot be 9 instantiated. For example, a Square, Circle, or 8 Rectangle is a type of shape and could be 7 derived from a class Shape.
A Shape will 6 contain code that is common to a Square, Circle, or 5 Rectangle such as calculating the area of 4 the shape. But instantiating a Shape would 3 be useless since it's an abstract concept 2 and squares, circles, and rectangles are 1 real entities.
The point is to specify methods that derived 8 classes must implement, same as an interface, but also 7 provide some of the implementation (which 6 an interface cannot do). Abstract classes 5 are never, strictly speaking, "necessary" - but 4 they are useful. Just search the .NET or 3 Java standard library for them and see for 2 yourself how they are used. You will find 1 there are plenty of examples.
Abstract classes are only useful if you 4 use inheritance. You create subclasses that must implement 3 the same interface as your abstract class and will 2 inherit some base implementation you may 1 have defined in your abstract class.
Its simply to Hide the actual implementation 29 from the client who consumes it.
- It Provides the concerete implementation for the certain functionality and this cannot be directly instantiated
- This will only be accessed from the classes those are implementing it.
- So the clients consuming the derived class, will never know the implementation of the functionality because its abstratced.
Now you 28 would ask why do we need this, since the 27 interfaces serve the same mechanismm.. Go 26 through the simple logger example
interface ILogger
{
string PrepareLog(System.Exception ex);
void InitializeLogger(string Type);
int WriteLog(string msg);
}
Any logging 25 client implements this interface should 24 implement all this functionality
class EventLogger : ILogger
{
public override void InitializeLogger(string Type)
{
//Event Logger Initialize
}
public override int WriteLog(string msg)
{
//Write to event log
return 1;
}
public override string PrepareLog(System.Exception ex)
{
return ex.StackTrace ;
}
}
class FileLogger : ILogger
{
public override void InitializeLogger(string Type)
{
}
public override int WriteLog(string msg)
{
//Write to File
return 1;
}
public override string PrepareLog(System.Exception ex)
{
return ex.StackTrace ;
}
}
class MailLogger : ILogger
{
public override void InitializeLogger(string Type)
{
}
public override int WriteLog(string msg)
{
//Write to mail
return 1;
}
public override string PrepareLog(System.Exception ex)
{
//prepare HTML Formatted msg
return ex.StackTrace ;
}
}
And the 23 classes EventLogger ,FileLogger and maillogger 22 implements the iLogger and gives the Context Specific implementation. Now 21 we wanted to hide the actual implementation 20 of PrepareLog and this would do the common 19 operation of preparing the log message from 18 the exception object.
In our current implementation 17 we dont have the option to make the single 16 method concrete and others to be just contracts.
so 15 lets change the implementation little bit 14 with abstract classes
abstract class AbstractLogger:ILogger
{
#region ILogger Members
public virtual string PrepareLog(System.Exception ex)
{
return ex.StackTrace;
}
public abstract void InitializeLogger(string Type);
public abstract int WriteLog(string msg);
#endregion
}
class EventLogger : AbstractLogger
{
public override void InitializeLogger(string Type)
{
//Event Logger Initialize
}
public override int WriteLog(string msg)
{
//Write to event log
return 1;
}
}
class FileLogger : AbstractLogger
{
public override void InitializeLogger(string Type)
{
}
public override int WriteLog(string msg)
{
//Write to File
return 1;
}
}
class DBLogger : AbstractLogger
{
public override void InitializeLogger(string Type)
{
}
public override int WriteLog(string msg)
{
//Write to DB
return 1;
}
}
class MailLogger : AbstractLogger
{
public override void InitializeLogger(string Type)
{
}
public override int WriteLog(string msg)
{
//Write to mail
return 1;
}
public override string PrepareLog(System.Exception ex)
{
//prepare HTML Formatted msg
return ex.StackTrace ;
}
}
Now i have created 13 the AbstractLogger class which inherits from the iLogger 12 and implemented the PrepareLog method alone, remainig 11 methods left abstract. so the consumers 10 will write the context specific code in 9 their implementation.
So now the PrepareLog 8 method completely hidden (meaning the log 7 preparation) from the cosumers initialized 6 any of the Loggers.
then why PrepareLog 5 is Virtual ed??
There are scenarios the consumer 4 may want to override the preparelog method, Ex: MailLogger 3 will override the PrepareLog and format 2 HTML formatted output to supply to mail 1 messages.
An abstract class is an abstraction. It guarantees 20 behaviors exist but does not force how the 19 behavior is implemented. This leaves you 18 free to change the way the behavior is implemented, if 17 you later decide you want to.
An abstraction 16 is like a keyboard, monitor, or cell phone. All 15 keyboards have the ability to enter data; all 14 monitors have the ability to display pixels; and 13 all cell phones have the ability to make 12 calls. But the manufacturers of these items 11 have different ways of implementing the 10 behavior.
So when you want to make a call, you 9 can do it from pretty much any cell phone 8 because all cell phone manufacturers create 7 phones that adhere to the common abstract 6 idea of what a cell phone is. You don't 5 need to relearn how to make a call on a 4 Samsung if you have already learned how 3 to do it on a BlackBerry or LG.
A cell phone 2 is a cell phone, and subclasses of an abstract class 1 are all the abstract class.
The point of an abstract class is to define 17 (restrict) your interface, without describing 16 the implementation.
An abstract class can 15 be instantiated by constructing a compatible 14 object with a derived class type.
To implement 13 a clean interface that hides ugly platform 12 specific code. Also to hide privates from 11 any sort of exposure. (So that you are 10 truly forced to use the class with the abstracted 9 interface.)
It is necessary when you have 8 two different implementations of the same 7 class that are radically different. Think 6 of a file, a socket, and a block of memory. All 5 of them can make readable data available 4 -- using an abstract class you can implement 3 those three in the three different ways, even 2 though the using code (the call-sites) is 1 written one way to support all three.
Both interfaces and abstract classes promote 15 loose coupling in your code base. Abstract 14 classes are a compromise between interfaces 13 and concrete classes, because abstract classes 12 can have actual methods with implemented 11 behavior.
In general, prefer interfaces. Abstract 10 classes are useful when you have an inheritance 9 tree that has common operations to be used 8 by the child classes. But even here you 7 may want to declare that your abstract class 6 implements an interface. Josh Bloch calls this the 5 "Abstract Interface" pattern. This 4 allows you to deploy different implementations 3 of even the abstract class, which paradoxically 2 isn't actually completely abstract -- only 1 interfaces are.
Same as with interfaces, an abstract class 6 is a contract in which you have provided some general 5 (or abstract) functionality that is applicable to 4 many scenarios, but expect an implementer 3 to provide some functionality that is specific 2 and/or different for each scenario. Someone 1 mentioned the Stream
example - very good example.
Okay, now you made an interface with all 11 the methods that change in each implementation. As 10 you program, you notice that some code blocks 9 are shared by ALL implementations of the 8 interface.
These code blocks should go in 7 an abstract class, instead of being repeated 6 in every implementation. That way, when 5 something changes, you only fix the code 4 in the abstract class instead of in every 3 implementation.
It's only abstract because 2 you want all the inheriting classes to have 1 their own implementations.
Abstract classes serve an useful purpose 7 by being able to create a class that embodies 6 a concept rather than something concrete. E.g, Animal can 5 be a class, but no one just an animal, it 4 is either a Bird, Dog, or Cat etc which are different 3 kinds of animals. Hope this helps. It also 2 goes in conjunction with concepts like inheritance 1 and polymorphism.
More Related questions
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.