How do virtual functions work in C# and Java?

2019-01-22 08:08发布

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?

6条回答
啃猪蹄的小仙女
2楼-- · 2019-01-22 08:31

I am sure Java does not use vtables, since it is able to support binary compatibility.

To Clarify: The vtable is built when the derived/sub class is compiled. If the base/super class layout changes then the vtable for the d/s needs to be recompiled. In Java this is not the case. You can change the b/s without having to recompile the d/s.

Hmmm. It is possible that a vtable is built at runt-time. when the class is loaded. In which case Java and C++ would be same same but different.

查看更多
爱情/是我丢掉的垃圾
3楼-- · 2019-01-22 08:40

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.
    }
}
查看更多
爷、活的狠高调
4楼-- · 2019-01-22 08:40

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

查看更多
戒情不戒烟
5楼-- · 2019-01-22 08:41

All languages supporting polymorphism use vtables to resolve method calls to the correct function. So also Java and .NET.

They both compile to some intermediate langauge (IL for .NET and byte code for java) but the vtable is not visible in this intermediate language. It is supported by the underlying engine (CLR for .NET)

查看更多
贪生不怕死
6楼-- · 2019-01-22 08:45

Pure virtual functions are in C++. C# uses Interfaces to serve the same purpose, so I'd suggest you go that route.

查看更多
啃猪蹄的小仙女
7楼-- · 2019-01-22 08:55

In Java virtual function is totally different. In Java, virtual function means a function which can be overridden in its subclasses. So all non-static methods of Java are virtual function. Only the final and private function are not inherited so they are not virtual function.

So we can say that all non-static function which are not final and private are virtual function in Java.

查看更多
登录 后发表回答