How instance method works? Person a=new Person(),b=new Persion(); a.setWeight(100);b.setWeight(120); D How can the method know whether it's been called for object a or b? OInternal:Person.setWeight(a,100); o Invisible additional parameter to all instance methods:this o It holds a reference to the object through which the method is invoked Oa.setWeight(100)>this=a
How instance method works? lHow can the method know whether it’s been called for object a or b? ¡Internal: Person.setWeight(a, 100); lInvisible additional parameter to all instance methods: this lIt holds a reference to the object through which the method is invoked ¡a.setWeight(100) this=a Person a=new Person(), b=new Persion(); a.setWeight(100); b.setWeight(120);
Keyword this o Can be used only inside method o When call a method within the same class,don't need to use this,compiler do it for you. ●Vhen to use it? Omethod parameter or local variable in a method has the same name as one of the fields of the class O Used in the return statement when want to return the reference to the current object. ●Example
Keyword this l Can be used only inside method l When call a method within the same class, don’t need to use this, compiler do it for you. l When to use it? ¡method parameter or local variable in a method has the same name as one of the fields of the class ¡Used in the return statement when want to return the reference to the current object. l Example …
Keyword this example l class Af int w; public void setValue (int w){ this.w=w,/same name! When a method parameter or local variable in a method has the same name as one of the fields of the class,you must use this to refer to the field
Keyword this example I class A{ int w; public void setValue (int w) { this.w = w; //same name! } } When a method parameter or local variable in a method has the same name as one of the fields of the class, you must use this to refer to the field
Keyword this example ll class Exp{ public int i=0; public Exp increment () i++; return this;/return current object } public static void main(String[]args){ Exp e=new Exp(); int v e.increment().increment().i;/v=2!! } }
Keyword this example II class Exp{ public int i=0; public Exp increment () { i++; return this; // return current object } public static void main (String[] args){ Exp e = new Exp(); int v = e.increment().increment().i; // v=2!! } }
Object life cycle Life cycles of dynamically created objects ●C O alloc()-use-free() ●C++ O new(-constructor()-use-destructor( o Java O new()-constructor()-use-[ignore garbage collection]
Object life cycle lLife cycles of dynamically created objects lC ¡ alloc() – use – free() lC++ ¡ new() – constructor() – use – destructor() lJava ¡ new() – constructor() – use – [ignore / garbage collection]