Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do virtual functions work in C# and Java?

Tags:

How do the virtual functions work in C# and Java?

Does it use same vtable and vpointer concept similar to C++ or is it something totally different?

like image 899
Naveen Avatar asked Jan 20 '09 08:01

Naveen


People also ask

How do virtual functions work?

A virtual function is a member function that you expect to be redefined in derived classes. When you refer to a derived class object using a pointer or a reference to the base class, you can call a virtual function for that object and execute the derived class's version of the function.

How are virtual functions implemented in C?

In C, virtual function calls look unlike any other kind of function call. For example, a call to the virtual area function applied to a shape looks like: shape *s;~~~s->vptr->area(s); In this case, if s points to a circle (the dynamic type of *s is circle ), then the call above calls circle_area .

Why do we need virtual functions in C?

Why use virtual functions. We use virtual functions to ensure that the correct function is called for an object, regardless of the reference type used to call the function. They are basically used to achieve the runtime polymorphism and are declared in the base class by using the virtual keyword before the function.


2 Answers

How do virtual functions work in Java?

Coding interviewers love this question. Yes. Although Java does NOT have a virtual keyword, Java has virtual functions and you can write them.

In object-oriented programming, a virtual function or virtual method is a function or method whose behavior can be overridden within an inheriting class by a function with the same signature. This concept is a very important part of the polymorphism portion of object-oriented programming (OOP).

Asking an architecture question about a specific language like this requires great communication skills and a deep mastery of underlying principles of the Java compiler, specifically interfaces, abstract classes, and how inheritance works.

Guide the interviewer onto a specific example of a virtual function.

Yes you can write virtual functions in Java with interfaces.

Java interface methods are all "pure virtual" because they are designed to be overridden. For example:

interface Bicycle {         //the function applyBrakes() is virtual because
    void applyBrakes();     //functions in interfaces are designed to be 
}                           //overridden.

class ACMEBicycle implements Bicycle {
    public void applyBrakes(){               //Here we implementing applyBrakes()
       System.out.println("Brakes applied"); //function, proving it is virtual.
    }
}

Yes you can write virtual functions in Java with abstract classes.

Java Abstract classes contain implicitly "virtual" methods, implemented by classes extending it. For Example:

abstract class Dog {                   
    final void bark() {               //bark() is not virtual because it is 
        System.out.println("woof");   //final and if you tried to override it
    }                                 //you would get a compile time error.

    abstract void jump();             //jump() is a virtual function because it
}                                     //is part of an abstract class and isn't
                                      //final.  
class MyDog extends Dog{
    void jump(){
        System.out.println("boing");    //here jump() is being overridden, a 
    }                                   //demonstration that it is virtual.
}
public class Runner {
    public static void main(String[] args) {
        MyDog myDog = new MyDog();       //instantiating myDog
        myDog.jump();                    //calling the overridden function jump()
    }
}

You can force a function to NOT be virtual in a generic class by making it final

For example:

class myJavaFoobarClass {

    final boolean giveMeTrueFunction()   //this Java function is NOT virtual
    {                                    //because final keyword prevents this
        return true;                     //function from being modified in a
    }                                    //subclass.

    boolean isItRainingFunction()   //this Java function IS virtual because
    {                               //without the final keyword, the function
        return false;               //can be overridden in a subclass.
    }
}
like image 168
Eric Leschinski Avatar answered Oct 18 '22 19:10

Eric Leschinski


There is no virtual keyword in Java at least.

It just resolves to the most derived version of whatever method you're calling...

class A{
void sayhi(){ System.out.println("A");}
}
class B extends A{
void sayhi(){ System.out.println("B");}
}

A a = new B();
a.sayhi();

Will print "B".

You can create "pure virtual" methods by declaring a class Abstract and leaving the pure virtual methods declared but unimplemented. Or by using interface / implements instead of class / extends. An interface is basically a class where all of the methods are pure virtual. This has the added bonus that a class can implement multiple interfaces, since unlike C++ a Java class can only inherit one other class directly.

EDIT:


In response to your comment, Naveen:

If you said A a = new A(); a.sayhi(); it would print "A".

The java terminology is dynamic. You can think of it as virtual, but that may confuse some Java devs. the ones who don't know C++, at least. In Java there are no explicit pointers, so we don't need to worry about virtual / non virtual. There are no VTables, you just backtrack the class and its ancestors until you find an implementation of the method you want. There's only single inheritance, so you don't have to worry about order of constructors (it's always bottom up).

In C++ you get different behaviour if you have virtual methods and do something like

a->sayhi();

where a was A* pointing to an instance of B instead of

a.sayhi();

where a was an object of type A holding an object of type B

like image 36
patros Avatar answered Oct 18 '22 18:10

patros