Question is:
How many Ways to create an object in java? Or what is the difference between new keyword or newInstance()?
There Is Two way to create an object in java. usually, programmer or developer use the new keyword to create an object. so, how can use it let's check?
1 ) Using new Keyword:
suppose one class is Test class so let us create an object of class
Test objT = new Test();
Here Above In that Test is class name and objT is object name = using assignment operator and new keyword and Test() were a constructor. ok, so it's very easy to create an object. ok, so here we know that Test class is there in my java file. and we use to perform an operation. But,
At run time how to create and you don't know class name at beginning. so that time you using newInstance() to create an object.
2 ) newInstance():
When you don't know class name at beginning or runtime you want to create an object of class so we can yous newInstance().
ex.
class bike{ //.... }
class demo{ //.... }
class Test{
public static void main(String args[])throws Exception//compiler throw exception so that throws exception
{
Object objT = Class.forName(args[0]).newInstance();
System.out.println("Object Name is>>"+objT.getClass().getName());
}
}
above Test class contain Object of creating by newInstance() method. were is Class.forName() use get parameter from the command line argument which is enter by programmer. one more thing is that newInstance() contain empty constructor so , you can not provide any parameters like that.
Now, Go to Command Prompt-> go to the directory where your file is stored. suppose my file stored in the documents folder
>>>In Command Prompt<<<
C:\user\publlic\documents:javac Test.java
then enter.
C:\user\public\documents:java Test bike
Object Name is>> bike
so, in two way to create an object of the class.
Comments
Post a Comment