Interview :: Core Java
There is no copy constructor in java. However, we can copy the values from one object to another like copy constructor in C++.
There are many ways to copy the values of one object into another in java. They are:
- By constructor
- By assigning the values of one object into another
- By clone() method of Object class
In this example, we are going to copy the values of one object into another using java constructor.
Test it NowOutput:
111 Karan 111 Karan
There are many differences between constructors and methods. They are given below.
Java Constructor | Java Method |
---|---|
A constructor is used to initialize the state of an object. | A method is used to expose the behavior of an object. |
A constructor must not have a return type. | A method must have a return type. |
The constructor is invoked implicitly. | The method is invoked explicitly. |
The Java compiler provides a default constructor if you don't have any constructor in a class. | The method is not provided by the compiler in any case. |
The constructor name must be same as the class name. | The method name may or may not be same as class name. |
The static variable is used to refer to the common property of all objects (that is not unique for each object), e.g., The company name of employees, college name of students, etc. Static variable gets memory only once in the class area at the time of class loading. Using a static variable makes your program more memory efficient (it saves memory). Static variable belongs to the class rather than the object.
Test it NowOutput:111 Karan ITS 222 Aryan ITS
Two main restrictions are applied to the static methods.
- The static method can not use non-static data member or call the non-static method directly.
- this and super cannot be used in static context as they are non-static.
Can we override the static methods?
No, we can't override static methods.
Program compiles. However, at runtime, It throws an error "NoSuchMethodError."
static or class method | instance method |
---|---|
1)A method that is declared as static is known as the static method. | A method that is not declared as static is known as the instance method. |
2)We don't need to create the objects to call the static methods. | The object is required to call the instance methods. |
3)Non-static (instance) members cannot be accessed in the static context (static method, static block, and static nested class) directly. | Static and non-static variables both can be accessed in instance methods. |
4)For example: public static int cube(int n){ return n*n*n;} | For example: public void msg(){...}. |