EzDevInfo.com

polymorphism interview questions

Top polymorphism frequently asked interview questions

Polymorphism with gson

I have a problem deserializing a json string with Gson. I receive an array of commands. The command can be start, stop , some other type of command. Naturally I have polymorphism, and start/stop command inherit from command.

How can I serialize it back to the correct command object using gson?

Seems that I get only the base type, that is the declared type and never the runtime type.


Source: (StackOverflow)

When to use virtual destructors?

I have a solid understanding of most OO theory but the one thing that confuses me a lot is virtual destructors.

I thought that the destructor always gets called no matter what and for every object in the chain.

When are you meant to make them virtual and why?


Source: (StackOverflow)

Advertisements

What is polymorphism, what is it for, and how is it used?

I was watching a Google Tech Talks video, and they frequently referred to polymorphism.

What is polymorphism, what is it for, and how is it used?


Source: (StackOverflow)

List> vs List>

Is there any difference between

List<Map<String, String>>

and

List<? extends Map<String, String>>

?

If there is no difference, what is the benefit of using ? extends?


Source: (StackOverflow)

In Java, how do I call a base class's method from the overriding method in a derived class?

I have two Java classes : B, which extends another class A, as follows :

class A
{
    public void myMethod()
    { /* ... */ }
}

class B extends A
{
    public void myMethod()
    { /* Another code */ }
}

I would like to call the A.myMethod() from the B.myMethod(). I am coming from the C++ world, and I don't know how to do this basic thing in Java :( If someone can help :) Thanks.


Source: (StackOverflow)

python properties and inheritance

I have a base class with a property which (the get method) I want to overwrite in the subclass. My first thought was something like:

class Foo(object):
    def _get_age(self):
        return 11

    age = property(_get_age)


class Bar(Foo):
    def _get_age(self):
        return 44

This does not work (subclass bar.age returns 11). I found a solution with an lambda expression which works:

age = property(lambda self: self._get_age())

So is this the right solution for using properties and overwrite them in a subclass, or are there other preferred ways to do this?


Source: (StackOverflow)

Is List a subclass of List? Why aren't Java's generics implicitly polymorphic?

I'm a bit confused about how Java generics handle inheritance / polymorphism.

Assume the following hierarchy -

Animal (Parent)

Dog - Cat (Children)

So suppose I have a method doSomething(List<Animal> animals). By all the rules of inheritance and polymorphism, I would assume that a List<Dog> is a List<Animal> and a List<Cat> is a List<Animal> - and so either one could be passed to this method. Not so. If I want to achieve this behavior, I have to explicitly tell the method to accept a list of any subset of Animal by saying doSomething(List<? extends Animal> animals).

I understand that this is Java's behavior. My question is why? Why is polymorphism generally implicit, but when it comes to generics it must be specified?


Source: (StackOverflow)

Avoiding instanceof in Java

Having a chain of "instanceof" operations is considered a "code smell". The standard answer is "use polymorphism". How would I do it in this case?

There are a number of subclasses of a base class; none of them are under my control. An analogous situation would be with the Java classes Integer, Double, BigDecimal etc.

if (obj instanceof Integer) {NumberStuff.handle((Integer)obj);}
else if (obj instanceof BigDecimal) {BigDecimalStuff.handle((BigDecimal)obj);}
else if (obj instanceof Double) {DoubleStuff.handle((Double)obj);}

I do have control over NumberStuff and so on.

I don't want to use many lines of code where a few lines would do. (Sometimes I make a HashMap mapping Integer.class to an instance of IntegerStuff, BigDecimal.class to an instance of BigDecimalStuff etc. But today I want something simpler.)

I'd like something as simple as this:

public static handle(Integer num) { ... }
public static handle(BigDecimal num) { ... }

But Java just doesn't work that way.

I'd like to use static methods when formatting. The things I'm formatting are composite, where a Thing1 can contain an array Thing2s and a Thing2 can contain an array of Thing1s. I had a problem when I implemented my formatters like this:

class Thing1Formatter {
  private static Thing2Formatter thing2Formatter = new Thing2Formatter();
  public format(Thing thing) {
      thing2Formatter.format(thing.innerThing2);
  }
}
class Thing2Formatter {
  private static Thing1Formatter thing1Formatter = new Thing1Formatter();
  public format(Thing2 thing) {
      thing1Formatter.format(thing.innerThing1);
  }
}

Yes, I know the HashMap and a bit more code can fix that too. But the "instanceof" seems so readable and maintainable by comparison. Is there anything simple but not smelly?

Note added 5/10/2010:

It turns out that new subclasses will probably be added in the future, and my existing code will have to handle them gracefully. The HashMap on Class won't work in that case because the Class won't be found. A chain of if statements, starting with the most specific and ending with the most general, is probably the best after all:

if (obj instanceof SubClass1) {
    // Handle all the methods and properties of SubClass1
} else if (obj instanceof SubClass2) {
    // Handle all the methods and properties of SubClass2
} else if (obj instanceof Interface3) {
    // Unknown class but it implements Interface3
    // so handle those methods and properties
} else if (obj instanceof Interface4) {
    // likewise.  May want to also handle case of
    // object that implements both interfaces.
} else {
    // New (unknown) subclass; do what I can with the base class
}

Source: (StackOverflow)

How to call base.base.method()?

// Cannot change source code
class Base
{
    public virtual void Say()
    {
        Console.WriteLine("Called from Base.");
    }
}

// Cannot change source code
class Derived : Base
{
    public override void Say()
    {
        Console.WriteLine("Called from Derived.");
        base.Say();
    }
}

class SpecialDerived : Derived
{
    public override void Say()
    {
        Console.WriteLine("Called from Special Derived.");
        base.Say();
    }
}

class Program
{
    static void Main(string[] args)
    {
        SpecialDerived sd = new SpecialDerived();
        sd.Say();
    }
}

The result is:

Called from Special Derived.
Called from Derived. /* this is not expected */
Called from Base.

How can I rewrite SpecialDerived class so that middle class "Derived"'s method is not called?

UPDATE: The reason why I want to inherit from Derived instead of Base is Derived class contains a lot of other implementations. Since I can't do base.base.method() here, I guess the best way is to do the following?

// Cannot change source code

class Derived : Base
{
    public override void Say()
    {
        CustomSay();

        base.Say();
    }

    protected virtual void CustomSay()
    {
        Console.WriteLine("Called from Derived.");
    }
}

class SpecialDerived : Derived
{
    /*
    public override void Say()
    {
        Console.WriteLine("Called from Special Derived.");
        base.Say();
    }
    */

    protected override void CustomSay()
    {
        Console.WriteLine("Called from Special Derived.");
    }
}

Source: (StackOverflow)

How does polymorphism work in Python?

I'm new to Python... and coming from a mostly Java background, if that accounts for anything.

I'm trying to understand polymorphism in Python. Maybe the problem is that I'm expecting the concepts I already know to project into Python. But I put together the following test code:

class animal(object):
    "empty animal class"

class dog(animal):
    "empty dog class"

myDog = dog()
print myDog.__class__ is animal
print myDog.__class__ is dog

From the polymorphism I'm used to (e.g. java's instanceof), I would expect both of these statements to print true, as an instance of dog is an animal and also is a dog. But my output is:

False
True

What am I missing?


Source: (StackOverflow)

Must ASP.NET MVC Controller Methods Return ActionResult?

Being new to ASP.NET MVC, I've been wondering about the signature of Controller methods. In all the examples I've seen, they always seem to return ActionResult, even if they actually return a ViewResult instance or similar.

Here's a commonly seen example:

public ActionResult Index()
{
    return this.View();
}

In such a case, wouldn't it make more sense to declare the method as public ViewResult Index(), and get stronger type support?

Experimentation indicates that this works, so it seems possible.

I do realize that there may be situations where the polymorphism is desired (e.g. if you want to redirect only in certain situations, but show a view in other situations), but if the method always returns a view, I'd find a ViewResult more desirable.

In terms of future compatibility, ActionResult obviously provides a more robust signature, but if one controls the entire code base, it's always possible to change a method's signature to a more general return type if that should become necessary in the future.

Are the any other considerations that I'm not aware of, or should I just go ahead and declare my controller methods with specific return types?


Source: (StackOverflow)

Will GetType() return the most derived type when called from the base class?

Will GetType() return the most derived type when called from the base class?

Example:

public abstract class A
{
    private Type GetInfo()
    {
         return System.Attribute.GetCustomAttributes(this.GetType());
    }
}

public class B : A
{
   //Fields here have some custom attributes added to them
}

Or should I just make an abstract method that the derived classes will have to implement like the following?

public abstract class A
{
    protected abstract Type GetSubType();

    private Type GetInfo()
    {
         return System.Attribute.GetCustomAttributes(GetSubType());
    }
}

public class B : A
{
   //Fields here have some custom attributes added to them

   protected Type GetSubType()
   {
       return GetType();
   }
}

Source: (StackOverflow)

How are virtual functions and vtable implemented?

We all know what virtual functions are in C++, but how are they implemented at a deep level?

Can the vtable be modified or even directly accessed at runtime?

Does the vtable exist for all classes, or only those that have at least one virtual function?

Do abstract classes simply have a NULL for the function pointer of at least one entry?

Does having a single virtual function slow down the whole class? Or only the call to the function that is virtual? And does the speed get affected if the virtual function is actually overwritten or not, or does this have no effect so long as it is virtual.


Source: (StackOverflow)

Pure virtual destructor in C++

Is it wrong to write:

class A {
public:
    virtual ~A() = 0;
};

for an abstract base class?

At least that compiles in MSVC... Will it crash at run time?


Source: (StackOverflow)

Where do "pure virtual function call" crashes come from?

I sometimes notice programs that crash on my computer with the error: "pure virtual function call".

How do these programs even compile when an object cannot be created of an abstract class?


Source: (StackOverflow)