I’m a newbie to Java, but somewhat familiar to C. I wanted to know — what differences are there between C structures and Java objects and invoking their methods? Or are the totally equivalent?
For example, the Bicycle structure:
class BicycleDemo {
public static void main(String[] args) {
// Create two different Bicycle objects
Bicycle bike1 = new Bicycle();
Bicycle bike2 = new Bicycle();
// Invoke methods on those objects
bike1.changeCadence(50);
bike1.speedUp(10);
bike1.changeGear(2);
bike1.printStates();
bike2.changeCadence(50);
bike2.speedUp(10);
bike2.changeGear(2);
bike2.changeCadence(40);
bike2.speedUp(10);
bike2.changeGear(3);
bike2.printStates();
}
}
The reason why I am asking is because they look so similar! Thanks!
If you leave method overriding out of the picture, then you can think of Java classes and methods as a pair of a C-style
structand a set of functions that operate on thosestructs. For example, if you have a class like this:This would be similar to writing C code to this effect:
The main idea is that a method is similar to a function that takes the receiver object as an implicit “this” parameter. In C, you have to explicitly pass the receiver as a parameter to the function, while in Java this is done implicitly through the
object.method()syntax.If you start introducing method overriding, this becomes a bit more complicated because the method that you invoke on an object depends on the dynamic type of the object, not the static type. One way of simulating this is using something called a vtable or virtual function table, so named because of C++’s
virtualkeyword. The idea is that each object stores a pointer to a table of function pointers, one per function that can be overridden, and when a method is called on the object the appropriate function pointer is selected out of the table and called. So, more properly, the above Java object might look something like this:Whenever you created an instance of
MyJavaClass, you’d set up its vtable doing something like this:Then, when invoking a function like this (in Java):
In C it would look like
So in a sense a Java class is just a struct with some extra metainformation. Of course, to the programmer it looks totally different – there’s encapsulation, polymorphism, a stricter type system, etc. – but at the level of native code a regular C struct and a Java class probably look very similar.
Hope this helps!