Why can't an object of abstract class be created? - language-agnostic

Here is a scenario in my mind and I have googled, Binged it a lot but got the answer like
"Abstract class has not implemented method so, we cant create the object"
"The word 'Abstract' instruct the compiler to not create an object of the class"
But in a simple class where we have all virtual method, able to create an object???
Also, we can define different access modified to Abstract class constructor like private, protected or public.
My search terminated to this question:
Why we can't create object of an Abstract class?

An abstract type is defined largely as one that can't be created. You can create subtypes of it, but not of that type itself. The CLI will not let you do this.
An abstract class has a protected constructor (by default) allowing derived types to initialize it.
For example, the base-type Stream is abstract. Without a derived type where would the data go? What would happen when you call an abstract method? There would be no actual implementation of the method to invoke.

Because it's abstract and an object is concrete. An abstract class is sort of like a template, or an empty/partially empty structure, you have to extend it and build on it before you can use it.
Take for example an "Animal" abstract class. There's no such thing as a "pure" animal - there are specific types of animals. So you can instantiate Dog and Cat and Turtle, but you shouldn't be able to instantiate plain Animal - that's just a basic template. And there's certain functionality that all animals share, such as "makeSound()", but that can't be defined on the base Animal level. So if you could create an Animal object and you would call makeSound(), how would the object know which sound to make?

It's intended to be used as a base class.
http://msdn.microsoft.com/en-us/library/sf985hc5(VS.71).aspx
The abstract modifier can be used with
classes, methods, properties,
indexers, and events.
Use the abstract modifier in a class
declaration to indicate that a class
is intended only to be a base class of
other classes.
Abstract classes have the following
features:
An abstract class cannot be instantiated.
An abstract class may contain abstract methods and accessors.
It is not possible to modify an abstract class with the sealed modifier, which means that the class cannot be inherited.
A non-abstract class derived from an abstract class must include actual implementations of all inherited abstract methods and accessors.

Abstract classes should have at least one virtual method or property that has no implementation. This is marked with the abstract keyword. Inheriting classes must provide an implementation if they are not abstract themselves. You cannot create an instance of an abstract class because it does not have a complete implementation. If it does, it should not be marked abstract in the first place.

As an addition to the other answers, you may not be able to create an instance of the abstract class, but you can certainly refer to instances of derived types through the abstract type and use methods or properties that are defined within the abstract base.
abstract class A
{
public abstract void D();
public void E() { }
}
class B : A
{
public override void D() { }
}
class C : A
{
public override void D() { }
}
...
A a = new B();
a.D();
a.E();
List<A> list = new List<A>() { new B(), new C() };

Simply speaking, an abstract class is like a shell of a class. Not all the methods have implementations, something like a circuit with some wire segments missing. While the majority of it may be constructed, it is up to the users to stick in the wires and resistors in those segments as they see fit.
As to why Java won't let you create it, part of it is just a failsafe (many abstract classes will function just fine without any additions as long as you don't call unimplemented methods).

If we have a class containing pure virtual function then the class is abstract. If we will create an object of the abstract class and calls the method having no body(as the method is pure virtual) it will give an error. That is why we cant create object of abstract class.

We cannot create object for abstract class bcoz ,mostly abstract class contain "abstract methods" ,so abstract methods are incomplete methods.so we cannot estimate the memory of those methods how much they are going to occupy .This is one of the reason why we cannot create object for abstract class.

Here is a similar StackOverflow question. In short, it is legal to have a public constructor on an abstract class. Some tools will warn you that this makes no sense.
Whats the utility of public constructors in abstract classes in C#?

Actually when we create an object of a normal class we use Constructor to allocate the memory
for that object like
myclass obj=new myclass();
Here using constructorr clr identifies how much memory the object needed depending upon the instance variabless and methods. But in case of abstract classes we cant predict the amount of memory required as we dont implement the abstract methods so its not possible to create object.

When we create a pure virtual function in Abstract class, we reserve a slot for a function in the VTABLE(studied in last topic), but doesn't put any address in that slot. Hence the VTABLE will be incomplete.
As the VTABLE for Abstract class is incomplete, hence the compiler will not let the creation of object for such class and will display an errror message whenever you try to do so.
Source : Study Tonight

The reference studytonight :
When we create a pure virtual function in Abstract class, we reserve a
slot for a function in the VTABLE(studied in last topic), but doesn't
put any address in that slot. Hence the VTABLE will be incomplete.
As the VTABLE for Abstract class is incomplete, hence the compiler
will not let the creation of object for such class and will display an
errror message whenever you try to do so.

Sorry guys...
You can Create object for an abstract class, if and only if that abstract class does not contains any abstract method.
Here is my Example. Copy it and compile and run.
abstract class Example {
void display(){
System.out.println("Hi I am Abstract Class.");
}
}
class ExampleDemo {
public static void main(String[] args) {
Example ob = new Example(){};
ob.display();
}
}
So your answer is yes, we can create object for abstract class if it's no Abstract Method.
Check my program.

I don't agree with the accepted answer. The reason is that we can have body for pure virtual function.
The answer is that :
When we create a pure virtual function in the class, we reserve a slot for a function in the VTABLE, but doesn't put any address in that slot. Hence the VTABLE will be incomplete.
As the VTABLE for Abstract class is incomplete, hence the compiler will not let the creation of object for such class and will display an error message whenever you try to do so.

we can create object for abstract class like this also...
public class HelloWorld
{
public static void main(String args[])
{
Person p = new Person()
{
void eat()
{
console.writeline("sooper..");
}
};
p.eat();
}
}
abstract class Person
{
abstract void eat();
}

every body is writing dat abstract class has some virtual function which has not defined. for dat reason we cant create object, but abstract class is a class with the key word 'abstract' which may or may not have abstract method. i think it is a concept, it does not take any memory for dat. so if we can create an object den a memory will be created which is not possible, for dat reason we can't create object of an abstract class bt we can create reference of it which does not occupy any memory location.

Related

How to lock/unlock a resource?

First 2 parts of this query has been addressed in link and further would like to understand more about third part before implementation.
Part III (3 points)
Implement a "lockable" doubly-linked list ADT: a list in which any node can be "locked." A locked node can never be removed from its list. Any attempt to remove a locked node has no effect (not even an error message). Your locked list classes should be in the list package alongside DList and DListNode.
First, define a LockDListNode class that extends DListNode and carries information about whether it has been locked. LockDListNodes are not locked when they are first created. Your LockDListNode constructor(s) should call a DListNode constructor to avoid code duplication.
Second, define a LockDList class that extends DList and includes an additional method
public void lockNode(DListNode node) { ... }
that permanently locks "node".
Your LockDList class should override just enough methods to ensure that
(1) LockDListNodes are always used in LockDLists (instead of DListNodes), and
(2) locked nodes cannot be removed from a list.
WARNING: To override a method, you must write a new method in the subclass with EXACTLY the same prototype. You can’t change a parameter’s type to a subclass. Overriding won’t work if you do that.
Your overriding methods should include calls to the overridden superclass methods whenever it makes sense to do so. Unnecessary code duplication will be penalized.
It is important to understand locking and unlocking a DListNode without using any existing Java package. With an approach of, boolean flag; being member of LockDListNode to represent lock/unlock status, setting of this flag is non-atomic. Because, if i set flag = true; this set operation could be a multi-line instruction at byte code level.
Once this clarification that became a bottleneck to implement lock/unlock is resolved, Inheritance and override stuff could be taken care easily after this.
My question:
Can you suggest an approach to implement lock/unlock feature on DListNode?
Note: This query has nothing to do with knowledge of Java.
The new class LockDListNode will extend DListNode. Now you need to understand inheritance. DListNode should have an delete operation method you need to override that method not not do anything. See the code template below:
public class DListNode {
public DListNode{
}
public void delete(){
// TODO some delete code here
}
}
public class LockDListNode extends DListNode {
public LockDListNode{
super();
}
#override
public void delete(){
// DO nothing here
}
}
Now if you do
DListNode unableToDeleteNode = new LockDListNode();
unableToDeleteNode.delete();
You created an object of LockDListNode and call delete method it will call the delete for the LockDListNode and not DListNode.

Design pattern to use instead of multiple inheritance

Coming from a C++ background, Im used to multiple inheritance. I like the feeling of a shotgun squarely aimed at my foot. Nowadays, I work more in C# and Java, where you can only inherit one baseclass but implement any number of interfaces (did I get the terminology right?).
For example, lets consider two classes that implement a common interface but different (yet required) baseclasses:
public class TypeA : CustomButtonUserControl, IMagician
{
public void DoMagic()
{
// ...
}
}
public class TypeB : CustomTextUserControl, IMagician
{
public void DoMagic()
{
// ...
}
}
Both classes are UserControls so I cant substitute the base class. Both needs to implement the DoMagic function. My problem now is that both implementations of the function are identical. And I hate copy-and-paste code.
The (possible) solutions:
I naturally want TypeA and TypeB to share a common baseclass, where I can write that identical function definition just once. However, due to having the limit of just one baseclass, I cant find a place along the hierarchy where it fits.
One could also try to implement a sort of composite pattern. Putting the DoMagic function in a separate helper class, but the function here needs (and modifies) quite a lot of internal variables/fields. Sending them all as (reference) parameters would just look bad.
My gut tells me that the adapter pattern could have a place here, some class to convert between the two when necessary. But it also feels hacky.
I tagged this with language-agnostic since it applies to all languages that use this one-baseclass-many-interfaces approach.
Also, please point out if I seem to have misunderstood any of the patterns I named.
In C++ I would just make a class with the private fields, that function implementation and put it in the inheritance list. Whats the proper approach in C#/Java and the like?
You can use the strategy pattern or something like it to use has a (composition) instead of is a (inheritance):
public class TypeA : CustomButtonUserControl, IMagician {
IMagician magicObj = new Magical();
public void DoMagic() {
magicObj.DoMagic();
}
}
public class TypeB : CustomButtonUserControl, IMagician {
IMagician magicObj = new Magical();
public void DoMagic() {
magicObj.DoMagic();
}
}
public class Magical : IMagician {
public void DoMagic() {
// shared magic
}
}
There are other ways to instantiate your private IMagician members (such as passing them as a param via constructor) but the above should get you started.
In .Net, you can have extension methods apply to interfaces. It's really neat when it's possible, and applicable for you because it's a rare way to apply a common implementation to an interface. Certainly consider it, but it might not work for you since you say that DoMagic works with a lot of Private members. Can you package these private variables internal possibly? This way the extension method could access them.
Have the common functionality in another class. If there's a logical place to put this common functionality, pass your objects to this other class method (perhaps this is UI functionality, and you already have a UI helper . . .). Again, can you expose the private data with an internal/public property? (Security/encapsulation is a concern in all this of course. I don't know if your classes are for internal use only or will be exposed publicly.)
Otherwise, pass a separate functionality class (or specific function pointer) into the interface-defined method. You would have to have a little bit of duplicated code to pass your private variables to this external function reference, but at least it wouldn't be much, and your implementation would be in one place.
We might be making this too complicated. It won't make you feel all object-oriented when you go to sleep tonight, but could you have a static routine in your library somewhere that all IMagician implementers call?
In the end, Adapter might indeed be what you're looking for. Less likely but still worth consideration is the Decorator pattern.
If nothing seems particularly good, pick what feel best, use it a couple times, and rearrange tomorrow. :)
Replace inheritance with composition.
Move your 'common' function to separate class, create an instance of that class, and insert it to TypeA object and to TypeB object.
Your gut is correct in this case. The Adapter pattern is what you're looking for.
DoFactory has good .NET examples (that should be pretty close to their Java counterparts as well):
Adapter Design Pattern in C# and VB.NET
The composite pattern is meant for complex objects, that means the focus is on one object being made up of other objects. The strategy-pattern can be regarded as a special case of that, but a strategy does not have to be an object. I think this would apply more to your case. Then again, this heavily depends on the nature of what DoMagic() does.
public interface IMagician{ /* declare here all the getter/setter methods that you need; they will be implemented both in TypeA and TypeB, right? */ }
public static class MyExtensions {
public static void doMagic(this IMagician obj)
{
// do your magic here
}
}
Now, the problem is if you REALLY need to use private properties/methods (as opposed to "internal" ones), this approach won't work. Well, actually, you may be able to do your magic if you can read those properties through reflection, but even if it works, it's a rather ugly solution :)
[Note that "doMagic" will automatically appear to become a part of TypeA and TypeB,simply because you implement IMagician - there is no need to have any implementation there ]
You can use composition to have magician as a property of typeA and typeB
class Magician : IMagician
{
public void DoMagic()
{}
}
Class TypeA : CustomButtonUserControl
{
//property
Magician magicianInTypeA
}
Class TypeB : CustomTextUserControl
{
//property
Magician magicianInTypeB
}
abstract class Magical: CustomButtonUserControl
{
public void DoMagic()
{
// ...
}
}
public class TypeA : Magical
{
}
public class TypeB : Magical
{
}

Interface member name conflicts in ActionScript 3

I am trying to create an ActionScript 3 class that implements two interfaces. The interfaces contain member functions with different signatures but the same name:
public interface IFoo
{
function doStuff(input:int):void;
}
public interface IBar
{
function doStuff(input1:String, input2:Number):void;
}
public class FooBar implements IFoo, IBar
{
// ???
}
In C# (for example) this is not a problem because methods can be overloaded, but ActionScript does not support overloading. Is there any way to create a class that implements both interfaces?
No, unfortunately this is not possible and it's because of the reason you already pointed out: ActionScript 3 does not support member overloading. It's a shame, but it's the unfortunate truth.
It is possible to have multiple members with the same name and even the same signature in a class, however, they must be qualified by namespace in that case. For instance, this should work:
public namespace foo;
public namespace bar;
foo function doStuf(input:int):void
{
// ...
}
bar function doStuff(input1:String, input2:String):void
{
// ...
}
You then reference the methods by qualifying them like so:
foo::doStuff(1);
bar::doStuff("foo", "bar");
Unfortunately, this won't help with your problem because even though the namespaces may be in the public namespace, they are still not the same as the public namespace itself meaning you're not satisfying the contract set forth by the interfaces (everything must be public). Making a long story short; unless you use some sort of composite pattern, you're out of luck until Adobe decides to implement member overloading.
public class FooBar would have to implement both interaces and thus implment those functions listed. Problem is ActionScript does not support method overloading. It is a nice feature that I miss from C# :(

Choosing the correct constructor using an external configuration file in Windsor?

I'm new to Windsor, but I'm certain there must be a way to do this...
I have a class with three different constructors:
public MyClass(string SomeParam)
{
...
}
public MyClass(string AnotherParam, string YetAnother)
{
...
}
public MyClass(string AnotherOne, string YeahIKnow, string AnnoyingExampleParam)
{
...
}
In my external configuration file, I have my service defined as:
<component
id="IMyClass"
service="IMyInterface, MyAssembly"
type="MyClass, MyOtherAssembly">
<parameters>
<AnotherOne>string value #1</AnotherOne>
<YeahIKnow>string value #2</YeahIKnow>
<AnnoyingExampleParam>string value #3</AnnoyingExampleParam>
</parameters>
</component>
When Windsor initializes an instance of my class, it only wants to initialize using the first (single string parameter) constuctor of my class, when I really want Windsor to use the third constructor.
I don't see anything in the docs about forcing the kernel to us a particular constructor using an external configuration, even though I can find references to doing it in code, but that sort of defeats the purpose of an external configuration!
Any advice would be appreciated.
Best,
David Montgomery
What version of Castle? I recall, from the depths of what goes for my memory at 4am in the morning, that there was a resolution for constructor work in Castle 2.0.
Humm, memory coming back a little now... Something tells me that Castle will construct the object with the first public ctor. May be as simple as moving what you want for Castle to load, to the top.
If that doesn't work for you, perhaps refactor your code a little?
Option 1) Make the first two constructors internal.
Option 2) Use a Factory pattern for your complex objects, which will utilize castle on the backend to new up the more simple or complex version.
Option 3) Create 3 classes from your base superclass, each having a more complicated constructor. This way, you can specific in the Castle config file exactly which service to load. For example:
public abstract class BaseClass
{
public BaseClass(String requiredParam)
{
...
}
}
public class SimpleClass : BaseClass
{
public SimpleClass(String requiredParam, String anotherParam)
: base(requiredParam)
{
...
}
}
public class MoreComplexClass : SimpleClass
{
public MoreComplexClass (String requiredParam, String anotherParam, String yetAnother)
: base(requiredParam, anotherParam)
{
...
}
}
But, I myself have not run into this yet. Mainly because I stick to only public 1 ctor on my classes, with a few private/internal ctors for things such as Linq to new up my objects with an empty ctor (since Linq doesn't support Dependency Injection, boo).
Note that in that last statement, internal ctors, that my SRP (Single Responsiblity Pattern) for resolving my IoC components is external, in a seperate higharchy assembly (i.e. an application or UI layer). Since it not internal to my domain objects, the internal ctors are not seen by Castle.
You must be doing something wrong.
Windsor uses the greediest constructor it can satisfy. If it uses the smaller one, you perhaps have some typo?
when your type is the service, you don't have to specify both
service="MyClass, MyAssembly"
type="MyClass">
remove the type.

Why does the actionscript3.0 class heirachy fail (sometimes)?

All Objects in actionscript3.0 inherit from the Object class, but the actionscript3.0 compiler seems not to be smart enough to understand this.
take a look at the following code:
package{
public class TestOne{
public function TestOne(){
var t2: TestTwo = new TestTwo();
trace(t2.toString()); // COMPILE TIME ERROR
trace((t2 as Object).toString(); // [object TestTwo]
var t22 : * = new TestTwo();
trace(t22.toString()); // [object TestTwo]
trace((t22 as Object).toString(); // [object TestTwo]
}
}
}
class TestTwo{}
t2.toString() gives a compile time error because the data type t2 does not include toString(). However, t2 does include toString() because it is an object as (t2 as Object).toString() shows. If we do not give the variable a datatype, like t22, then the problem is never encountered. Why cant the actionscript3.0 compiler relize that t2 is both TestTwo and Object?
This is because
Methods of the Object class are
dynamically created on Object's
prototype. To redefine this method in
a subclass of Object, do not use the
override keyword. For example, a
subclass of Object implements function
toString():String instead of using an
override of the base class.
So if you cast TestTwo to an Object, the compiler knows those methods will be implemented. If you don't cast it, TestTwo does not inherit those methods and so they have not been implemented and will error.
It's a bit of a weird one!
Class inheritance and prototype inheritance are two different things in AS3. Prototype inheritance is as far as I understand included for backwards compatibility with AS2/AS1, and it's prototype inheritance that's providing the toString() method on the variable that's cast to the Object class in your example. The Object prototype has the toString() method, not the Object class. Since the prototype is not present on your TestTwo class, it doesn't have a toString() method. If the toString() method was supplied via class inheritance instead, your example would compile.
So technically, your statement "All Objects in actionscript3.0 inherit from the Object class" is not entirely correct, because of the difference between prototype inheritance and class inheritance. Prototype inheritance is a somewhat esoteric OO concept found in script languages.
Does anyone know the reason why AS3 is designed like this?