Java interview programming questions on this keyword part 2
- Hi friends this is the part 2 of this keyword programming interview questions
- Check this for part 1 Java programming examples programs on this keyword part 1
- Java interview program on this keyword: can we call method using this keyword?
Program #5:
Program #6: Can we call non static method from constructor using this?
Program #7: Can we assign something to this ?
- package thiskeywordinterviewprograms.java;
- public class ThisDemo {
- int a;
- int b;
- ThisDemo(int x, int y){
- this= new ThisDemo();
- System.out.println("Two argument constructor called.");
- this.x=x;
- this.y=y;
- }
- public static void main(String[] args) {
- ThisDemo obj = new ThisDemo(10, 20);
- System.out.println(obj.a);
- System.out.println(obj.b);
- }
- }
Program #8 : Can we use this as return statement in a method?
- public class B{
- int a;
- public int getA() {
- return a;
- }
- public void setA(int a) {
- this.a = a;
- }
- B show(){
- return this;
- }
- public static void main(String[] args) {
- B obj = new B();
- obj.setA(10);
- System.out.println(obj.getA());
- B obj2= obj.show();
- System.out.println(obj2.getA());
- }
- }