• 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:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

constructores

 
Ranch Hand
Posts: 234
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
public class Test
{
static StringBuffer sb = new StringBuffer("Java");
public Test() {}
public Test(StringBuffer s) {
this( s,s.append(" Script"));
}
public Test(StringBuffer s, StringBuffer sb1) {
System.out.println(s.toString());
System.out.println(sb1.toString());
}
public static void main(String[] args) {
new Test(sb);
}
}
prints the output as :
Java Script
Java Script
 
mister krabs
Posts: 13974
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
That is correct. s and sb1 are two pointers to the same object so naturally they print the same thing. s.append("xxx") does not create a new object but rather updates the existing StringBuffer object.
Step at a time:
1) MAIN METHOD:
new Test(sb);
2) STATIC:
static StringBuffer sb = new StringBuffer("Java");
3) CONSTRUCTOR:
public Test(StringBuffer s) {
this( s,s.append(" Script"));
}
- s.append(" Script") will update sb so that it contains "Java Script"
- at this point we have 2 pointers pointing to the same StringBuffer (class variable sb and method variable s)
4)THE OTHER CONSTRUCTOR
public Test(StringBuffer s, StringBuffer sb1) {
System.out.println(s.toString());
System.out.println(sb1.toString());
}
- we now have 4 pointers pointing to the same StringBuffer (class variable sb, method variable s from first constructor, and method variables s and sb1 from the second constructor)
- there has only been 1 new so that is a clue that we only have created one StringBuffer object
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic