In C++:
class Rectangle {
int x, y;
public:
void set_values (int,int);
int area () {return (x*y);}
};
int main () {
Rectangle rect;
rect.set_values (3,4);
}
In Java:
class Rectangle {
int x, y;
void set_values (int x,int y);
int area () {return (x*y);}
}
public static void main(String[] args) {
Rectangle rect=new Rectangle(3,4);
}
In C++ compiler will create rect object & reserve memory 4 bytes. I want to know How Java is creating object?
When you do: –
in C++, it invokes, the 0-arg default constructor, provided by the compiler.
If you wanted to use a 2-arg constructor, you would have to do: –
wherein, you would have to provide a 2-arg constructor explicitly, else it won’t compile.
Now, similar is the case in Java. If you do: –
then its ok, because, in that case, compiler will provide you with a default 0-arg constructor, as in C++, but when your create object like: –
Then you would have to explicitly provide the class with a 2-arg constructor, else it won’t compile, as in your 2nd example, that won’t compile.
Also, once you provide a
parameterized constructor, then in that case, Compiler won’t provide the default constructor. You would have to provide a 0-arg constructor explicitly, if you want to use one. This suffice in both,JavaandC++Now, as per the
memory allocationis concerned, since Java is platform independent, so the size ofinttype is32 bits, in all platforms. This is in contrast toC++where size of data types are platform dependent.See
JVM Specification - The Structure of JVMfor detaled information about the allocation of various types.P.S.: –
I suggest you to go through the below link, for basics of Java classes and objects: –