Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

constructores

 
sona gold
Ranch Hand
Posts: 234
  • Mark post as helpful
  • send pies
  • 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
 
Thomas Paul
mister krabs
Ranch Hand
Posts: 13974
  • Mark post as helpful
  • send pies
  • 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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic