• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Tim Cooke
  • Campbell Ritchie
  • paul wheaton
  • Ron McLeod
  • Devaka Cooray
Sheriffs:
  • Jeanne Boyarsky
  • Liutauras Vilda
  • Paul Clapham
Saloon Keepers:
  • Tim Holloway
  • Carey Brown
  • Piet Souris
Bartenders:

new method

 
Ranch Hand
Posts: 172
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Look at the following program,
class test
{ public void doo() {System.out.print("doo");}
public static void main(String [] args)
{test n = new test() {}; //why correct?
n.doo();}
}
Could anyone please tell me why "new test() {}" is a correct format for the method new; does it have any difference with "new test()"?
Thanks in advance
 
Ranch Hand
Posts: 97
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Yaun.


class test {

public void doo() {
System.out.print("doo");
}
public static void main(String [] args) {
test n = new test() {}; //why correct?
n.doo();}
}
}


The syntax .new test() {}; creates a very simple anonymous inner class. Technically, it creats a subclass instance of test, albeit one that does not override any of the methods of the test class.
So this syntax is effectively redundant when used in this way. To Make it more meaningful you could override the doo() method when you instantiate. Example :


And given the above change, n.doo() will now print "daa" instead of "doo".
Hope this helps
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic