0

Hi daniweb team,
I need to understand newinstance in java.So i tried the below program and got the error.
Can any one know how to write the newinstance program and explain the code.

import java.io.*;
public class sample
{
    public static void main(String args[])throws IOException{
        one obj=one.newinstance();
        obj.one();
    }
}
    class one{
        public static void one(){
        System.out.println("Sample program for new instances");
        }
    }

Thank you,
Prem

Edited by mike_2000_17: Fixed formatting

2
Contributors
1
Reply
2
Views
7 Years
Discussion Span
Last Post by javaAddict
0

First of all what errors do you get?
Second, does the 'one' class has a 'newinstance' method? I don't see any so there is your error. You haven't defined a newinstance method.

Maybe you should try this:

try {
            one obj = (one)Class.forName("one").newInstance();
            obj.one();
        } catch (ClassCastException cce) {
            System.out.println("Error: "+cce.getMessage());
        }

And try to have class names begin with capital.
And don't have methods that have the same as the class.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.