the program compiles , gives no error. when run program in latest netbeans (latest java installed), don't see output. have taken idea code book java 7 third edition chapter 5. topic under discussion using java.lang.class , creation of object without using new operator.
package java7thirdeditionpart1; public class creatobjectwithoutnewoperator { public static void main(string[] args) { class myclass2 = null; try { myclass2 = class.forname("book"); } catch (classnotfoundexception e) { } if (myclass2 != null) { try { //creating instance of book class book book1 = (book) myclass2.newinstance(); book1.setauthor("khan"); system.out.println(book1.getauthor()); book1.settitle("second book"); book1.setisbn("kh_s_b"); book1.printbookdetails(); } catch (illegalaccessexception e1) { e1.printstacktrace(); } catch (instantiationexception e2) { e2.printstacktrace(); } } }//main method ends here. }//class creatobjectwithoutnewoperator ends here. package java7thirdeditionpart1; public class book { string isbn; string title; string author; public book() { this.setisbn(""); this.settitle(""); this.setauthor(""); }//constructor ends here. public book(string isbn, string title, string author) { this.setisbn(isbn); this.settitle(title); this.setauthor(author); } public string getisbn() { return isbn; } public void setisbn(string isbn) { this.isbn = isbn; } public string gettitle() { return title; } public void settitle(string title) { this.title = title; } public string getauthor() { return author; } public void setauthor(string author) { this.author = author; } public void printbookdetails(){ system.out.println("*********************"); system.out.println("isbn: " + this.getisbn()); system.out.println("title: " + this.gettitle()); system.out.println("author: " + this.getauthor()); system.out.println("*********************"); }//method printbookdetails ends here. }//class book ends here.
try using package name before class in method forname()
package java7thirdeditionpart1; public class creatobjectwithoutnewoperator { public static void main(string[] args) { class myclass2 = null; try { myclass2 = class.forname("java7thirdeditionpart1.book"); } catch (classnotfoundexception e) { e.printstacktrace(); } if (myclass2 != null) { try { //creating instance of book class /*since newinstance returns java.lang.object object, need downcast original type.*/ book book1 = (book) myclass2.newinstance(); book1.setauthor("khan"); book1.settitle("second book"); book1.setisbn("kh_s_b"); book1.printbookdetails(); book1 = (book) myclass2.newinstance(); book1.setauthor("ajmal"); book1.settitle("first book"); book1.setisbn("aj_f_b"); book1.printbookdetails(); } catch (illegalaccessexception e1) { e1.printstacktrace(); } catch (instantiationexception e2) { e2.printstacktrace(); } } }//main method ends here. }//class creatobjectwithoutnewoperator ends here.
Comments
Post a Comment