EzDevInfo.com

inheritance interview questions

Top inheritance frequently asked interview questions

How to define custom exception class in Java, the easiest way?

I'm trying to define my own exception class the easiest way, and this is what I'm getting:

public class MyException extends Exception {}

public class Foo {
  public bar() throws MyException {
    throw new MyException("try again please");
  }
}

This is what Java compiler says:

cannot find symbol: constructor MyException(java.lang.String)

I had a feeling that this constructor has to be inherited from java.lang.Exception, isn't it?


Source: (StackOverflow)

How to call a parent class function from derived class function?

How do I call the parent function from a derived class using C++? For example, I have a class called parent, and a class called child which is derived from parent. Within each class there is a print function. In the definition of the child's print function I would like to make a call to the parents print function. How would I go about doing this?


Source: (StackOverflow)

Advertisements

Python class inherits object

Is there any reason for a class declaration to inherit from object?

I just found some code that does this and I can't find a good reason why.

class MyClass(object):
    # class code follows...

Source: (StackOverflow)

Ruby: kind_of? vs. instance_of? vs. is_a?

What is the difference? When should I use which? Why are there so many of them?


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)

What does it mean that Javascript is a prototype based language?

One of the major advantages with Javascript is said to be that it is a prototype based language.

But what does it mean that Javascript is prototype based, and why is that an advantage?


Source: (StackOverflow)

Use of .apply() with 'new' operator. Is this possible?

In JavaScript, I want to create an object instance (via the new operator), but pass an arbitrary number of arguments to the constructor. Is this possible?

What I want to do is something like this (but the code below does not work):

function Something(){
    // init stuff
}
function createSomething(){
    return new Something.apply(null, arguments);
}
var s = createSomething(a,b,c); // 's' is an instance of Something

The Answer

From the responses here, it became clear that there's no in-built way to call .apply() with the new operator. However, people suggested a number of really interesting solutions to the problem.

My preferred solution was this one from Matthew Crumley (I've modified it to pass the arguments property):

var createSomething = (function() {
    function F(args) {
        return Something.apply(this, args);
    }
    F.prototype = Something.prototype;

    return function() {
        return new F(arguments);
    }
})();

Source: (StackOverflow)

C++ superclass constructor calling rules

What are the C++ rules for calling the superclass constructor from a subclass one??

For example I know in Java, you must do it as the first line of the subclass constructor (and if you don't an implicit call to a no-arg super constructor is assumed - giving you a compile error if that's missing).


Source: (StackOverflow)

What is object slicing?

Someone mentioned it in the IRC, but google doesn't have a good answer.


Source: (StackOverflow)

Difference between private, public, and protected inheritance

I looked in SO and couldn't find a good description regarding the difference between public, private, and protected inheritance in C++. All the questions were assuming an specific case. What is the difference?


Source: (StackOverflow)

Differences between isinstance() and type() in python

What are the differences between these two code fragments? Which way is considered to be more pythonic?

Using type():

import types

if type(a) is types.DictType:
    do_something()
if type(b) in types.StringTypes:
    do_something_else()

Using isinstance():

if isinstance(a, dict):
    do_something()
if isinstance(b, str) or isinstance(b, unicode):
    do_something_else()

Edit: This seems to be discussed already: link.


Source: (StackOverflow)

How do you declare an interface in C++?

How do I setup a class that represents an interface? Is this just an abstract base class?


Source: (StackOverflow)

Why not inherit from List?

When planning out my programs, I often start with a chain of thought like so:

A football team is just a list of football players. Therefore, I should represent it with:

var football_team = new List<FootballPlayer>();

The ordering of this list represent the order in which the players are listed in the roster.

But I realize later that teams also have other properties, besides the mere list of players, that must be recorded. For example, the running total of scores this season, the current budget, the uniform colors, a string representing the name of the team, etc..

So then I think:

Okay, a football team is just like a list of players, but additionally, it has a name (a string) and a running total of scores (an int). .NET does not provide a class for storing football teams, so I will make my own class. The most similar and relevant existing structure is List<FootballPlayer>, so I will inherit from it:

class FootballTeam : List<FootballPlayer> 
{ 
    public string TeamName; 
    public int RunningTotal 
}

But it turns out that a guideline says you shouldn't inherit from List<T>. I'm thoroughly confused by this guideline in two respects.

Why not?

Apparently List is somehow optimized for performance. How so? What performance problems will I cause if I extend List? What exactly will break?

Another reason I've seen is that List is provided by Microsoft, and I have no control over it, so I cannot change it later, after exposing a "public API". But I struggle to understand this. What is a public API and why should I care? If my current project does not and is not likely to ever have this public API, can I safely ignore this guideline? If I do inherit from List and it turns out I need a public API, what difficulties will I have?

Why does it even matter? A list is a list. What could possibly change? What could I possibly want to change?

And lastly, if Microsoft did not want me to inherit from List, why didn't they make the class sealed?

What else am I supposed to use?

Apparently, for custom collections, Microsoft has provided a Collection class which should be extended instead of List. But this class is very bare, and does not have many useful things, such as AddRange, for instance. jvitor83's answer provides a performance rationale for that particular method, but how is a slow AddRange not better than no AddRange?

Inheriting from Collection is way more work than inheriting from List, and I see no benefit. Surely Microsoft wouldn't tell me to do extra work for no reason, so I can't help feeling like I am somehow misunderstanding something, and inheriting Collection is actually not the right solution for my problem.

I've seen suggestions such as implementing IList. Just no. This is dozens of lines of boilerplate code which gains me nothing.

Lastly, some suggest wrapping the List in something:

class FootballTeam 
{ 
    public List<FootballPlayer> Players; 
}

There are two problems with this:

  1. It makes my code needlessly verbose. I must now call my_team.Players.Count instead of just my_team.Count. Thankfully, with C# I can define indexers to make indexing transparent, and forward all the methods of the internal List... But that's a lot of code! What do I get for all that work?

  2. It just plain doesn't make any sense. A football team doesn't "have" a list of players. It is the list of players. You don't say "John McFootballer has joined SomeTeam's players". You say "John has joined SomeTeam". You don't add a letter to "a string's characters", you add a letter to a string. You don't add a book to a library's books, you add a book to a library.

I realize that what happens "under the hood" can be said to be "adding X to Y's internal list", but this seems like a very counter-intuitive way of thinking about the world.

My question (summarized)

What is the correct C# way of representing a data structure, which, "logically" (that is to say, "to the human mind") is just a list of things with a few bells and whistles?

Is inheriting from List<T> always unacceptable? When is it acceptable? Why/why not? What must a programmer consider, when deciding whether to inherit from List<T> or not?


Source: (StackOverflow)

Prefer composition over inheritance?

Why prefer composition over inheritance? What trade-offs are there for each approach? When should you choose inheritance over composition?


Source: (StackOverflow)

Understanding Python super() with __init__() methods [duplicate]

This question already has an answer here:

I'm trying to understand super(). From the looks of it, both child classes can be created just fine. I'm curious as to what difference there actually is between the following child classes:

class Base(object):
    def __init__(self):
        print "Base created"

class ChildA(Base):
    def __init__(self):
        Base.__init__(self)

class ChildB(Base):
    def __init__(self):
        super(ChildB, self).__init__()

ChildA() 
ChildB()

Source: (StackOverflow)