this keyword in java javatpoint

Similar documents
COLLEGE OF ENGINEERING, NASHIK

CONSTRUCTOR & Description. String() This initializes a newly created String object so that it represents an empty character sequence.

Java static keyword static keyword

Questions Answer Key Questions Answer Key Questions Answer Key

Answer1. Features of Java

INHERITANCE Mrs. K.M. Sanghavi

Questions Answer Key Questions Answer Key Questions Answer Key

Questions Answer Key Questions Answer Key Questions Answer Key

This Week. Fields and Variables. W05 Example 1: Variables & Fields. More on Java classes. Constructors. Modifiers

Programming - 2. Common Errors

Methods. Bok, Jong Soon

Class, Variable, Constructor, Object, Method Questions

Method Overriding in Java

1.00 Lecture 8. Using An Existing Class, cont.

Day 4. COMP1006/1406 Summer M. Jason Hinek Carleton University

Name Return type Argument list. Then the new method is said to override the old one. So, what is the objective of subclass?

OBJECTS AND CLASSES CHAPTER. Final Draft 10/30/2011. Slides by Donald W. Smith TechNeTrain.com

Inheritance in java is a mechanism in which one object acquires all the properties and behaviors of parent object.

Lecture 5: Methods CS2301

Chapter 5. Inheritance

JAVA PROGRAM EXAMPLE WITH OUTPUT PDF

Relationships Between Real Things. CSE 143 Java. Common Relationship Patterns. Composition: "has a" CSE143 Sp Student.

Fundamentals of Object Oriented Programming

Conversions and Overloading : Overloading

Programming in Java, 2e Sachin Malhotra Saurabh Choudhary

Chapter 4 Defining Classes I

STUDENT LESSON A5 Designing and Using Classes

ECOM 2324 COMPUTER PROGRAMMING II

Chapter 6 Introduction to Defining Classes

Java Classes - Using your classes. How the classes you write are being used

Objects as a programming concept

Module - 3 Classes, Inheritance, Exceptions, Packages and Interfaces. OOC 4 th Sem, B Div Prof. Mouna M. Naravani

Java Fundamentals (II)

UNIT -IV INHERITANCE, PACKAGES AND INTERFACES

Chapter 4. Defining Classes I

Introduction to Java. Handout-1d. cs402 - Spring

CS180 Recitation. More about Objects and Methods

Lecture Notes CPSC 224 (Spring 2012) Today... Java basics. S. Bowers 1 of 8

Mobile Application Development ( IT 100 ) Assignment - I

Course Content. Objectives of Lecture 24 Inheritance. Outline of Lecture 24. Inheritance Hierarchy. The Idea Behind Inheritance

Course Content. Objectives of Lecture 24 Inheritance. Outline of Lecture 24. CMPUT 102: Inheritance Dr. Osmar R. Zaïane. University of Alberta 4

Chapter 1: Introduction to Computers, Programs, and Java

University of Palestine. Mid Exam Total Grade: 100

CSC1322 Object-Oriented Programming Concepts

Programming Language (2) Lecture (4) Supervisor Ebtsam AbdelHakam Department of Computer Science Najran University

JAVA GUI PROGRAMMING REVISION TOUR III

CS-201 Introduction to Programming with Java

( &% class MyClass { }

QUIZ 2 Introduction to Computer Science (COMP 250) Mon. March 2, 2009 Professor Michael Langer

String is one of mostly used Object in Java. And this is the reason why String has unique handling in Java(String Pool). The String class represents

CHAPTER 3 COUPLING MODEL

Std 12 Lesson-10 Exception Handling in Java ( 1

Objectives. Introduce static keyword examine syntax describe common uses

Announcements. PS 3 is due Thursday, 10/6. Midterm Exam 1: 10/14 (Fri), 9:00am-10:53am

Introduction to Programming Using Java (98-388)

User Defined Classes Part 2. CS 180 Sunil Prabhakar Department of Computer Science Purdue University

Java How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved.

Selected Questions from by Nageshwara Rao

PASS4TEST IT 인증시험덤프전문사이트

Chapter 10. Class & Objects in JAVA. By: Deepak Bhinde PGT Com.Sc.

ASSIGNMENT NO 13. Objectives: To learn and understand concept of Inheritance in Java

Instance Members and Static Members

BM214E Object Oriented Programming Lecture 8

COMP 250 Winter 2011 Reading: Java background January 5, 2011

CMSC 341. Nilanjan Banerjee

Objects. Theoretical Part. Contents. Keywords. Programming with Java Module 5. 1 Module Overview 3

Relationships Between Real Things CSE 143. Common Relationship Patterns. Employee. Supervisor

News and information! Review: Java Programs! Feedback after Lecture 2! Dead-lines for the first two lab assignment have been posted.!

C11: Garbage Collection and Constructors

Classes and Objects 3/28/2017. How can multiple methods within a Java class read and write the same variable?

Getter and Setter Methods

Instantiation of Template class

3.1 Class Declaration

AP Computer Science Chapter 10 Implementing and Using Classes Study Guide

Lecture 3. COMP1006/1406 (the Java course) Summer M. Jason Hinek Carleton University

Computer Science II (20082) Week 1: Review and Inheritance

Distributed Systems Recitation 1. Tamim Jabban

Object Oriented Programming is a programming method that combines: Advantage of Object Oriented Programming

Example: Count of Points

Chapter 9 Objects and Classes. OO Programming Concepts. Classes. Objects. Motivations. Objectives. CS1: Java Programming Colorado State University

Topic 5 Polymorphism. " Inheritance is new code that reuses old code. Polymorphism is old code that reuses new code.

Relationships Between Real Things CSC 143. Common Relationship Patterns. Composition: "has a" CSC Employee. Supervisor

Character Stream : It provides a convenient means for handling input and output of characters.

OO Programming Concepts. Classes. Objects. Chapter 8 User-Defined Classes and ADTs

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub

*Java has included a feature that simplifies the creation of

Programming in C. main. Level 2. Level 2 Level 2. Level 3 Level 3

Introduction to Java

Unit 4 - Inheritance, Packages & Interfaces

Computer Programming, I. Laboratory Manual. Final Exam Solution

* Mrs. K.M. Sanghavi

LECTURE 2 (Gaya College of Engineering)

3.Constructors and Destructors. Develop cpp program to implement constructor and destructor.

Chapter 4. Defining Classes I

Lecture 7 Objects and Classes

Java Primer 1: Types, Classes and Operators

CMSC 132: Object-Oriented Programming II. Interface

Unit 4: Classes and Objects Notes

Object Oriented Programming

COE 212 Engineering Programming. Welcome to Exam I Tuesday November 11, 2014

Transcription:

this keyword in java javatpoint There can be a lot of usage of java this keyword. In java, this is a reference variable that refers to the current object. Usage of java this keyword Here is given the 6 usage of java this keyword. 1. this keyword can be used to refer current class instance variable. 2. this() can be used to invoke current class constructor. 3. this keyword can be used to invoke current class method (implicitly) 4. this can be passed as an argument in the method call. 5. this can be passed as argument in the constructor call. 6. this keyword can also be used to return the current class instance. Suggestion: If you are beginner to java, lookup only two usage of this keyword. 1) The this keyword can be used to refer current class instance variable. If there is ambiguity between the instance variable and parameter, this keyword resolves the problem of ambiguity. Understanding the problem without this keyword Let's understand the problem if we don't use this keyword by the example given below: 1. class Student10{ 2. int id; 3. String name; 4. Student10(int id,string name){ 5. id = id; 6. name = name; 7. } 8. void display(){system.out.println(id+" "+name);} 9. public static void main(string args[]){ 10. Student10 s1 = new Student10(111,"Karan"); 11. Student10 s2 = new Student10(321,"Aryan");

12. s1.display(); 13. s2.display(); 14. } Output:0 null 0 null In the above example, parameter (formal arguments) and instance variables are same that is why we are using this keyword to distinguish between local variable and instance variable. Solution of the above problem by this keyword 1. //example of this keyword 2. class Student11{ 3. int id; 4. String name; 5. Student11(int id,string name){ 6. this.id = id; 7. this.name = name; 8. } 9. void display(){system.out.println(id+" "+name);} 10. public static void main(string args[]){ 11. Student11 s1 = new Student11(111,"Karan"); 12. Student11 s2 = new Student11(222,"Aryan"); 13. s1.display(); 14. s2.display(); 16. } Output111 Karan 222 Aryan

If local variables(formal arguments) and instance variables are different, there is no need to use this keyword like in the following program: Program where this keyword is not required 1. class Student12{ 2. int id; 3. String name; 4. Student12(int i,string n){ 5. id = i; 6. name = n; 7. } 8. void display(){system.out.println(id+" "+name);} 9. public static void main(string args[]){ 10. Student12 e1 = new Student12(111,"karan"); 11. Student12 e2 = new Student12(222,"Aryan"); 12. e1.display(); 13. e2.display(); 14. } Output:111 Karan 222 Aryan 2) this() can be used to invoked current class constructor. The this() constructor call can be used to invoke the current class constructor (constructor chaining). This approach is better if you have many constructors in the class and want to reuse that constructor.

1. //Program of this() constructor call (constructor chaining) 2. class Student13{ 3. int id; 4. String name; 5. Student13(){System.out.println("default constructor is invoked");} 6. Student13(int id,string name){ 7. this ();//it is used to invoked current class constructor. 8. this.id = id; 9. this.name = name; 10. } 11. void display(){system.out.println(id+" "+name);} 12. public static void main(string args[]){ 13. Student13 e1 = new Student13(111,"karan"); 14. Student13 e2 = new Student13(222,"Aryan"); 15. e1.display(); 16. e2.display(); 17. } 18. } Output: default constructor is invoked default constructor is invoked 111 Karan 222 Aryan Where to use this() constructor call? The this() constructor call should be used to reuse the constructor in the constructor. It maintains the chain between the constructors i.e. it is used for constructor chaining. Let's see the example given below that displays the actual use of this keyword. 1. class Student14{ 2. int id; 3. String name; 4. String city; 5. Student14(int id,string name){ 6. this.id = id; 7. this.name = name; 8. } 9. Student14(int id,string name,string city){ 10. this(id,name);//now no need to initialize id and name 11. this.city=city; 12. } 13. void display(){system.out.println(id+" "+name+" "+city);} 14. public static void main(string args[]){ 15. Student14 e1 = new Student14(111,"karan");

16. Student14 e2 = new Student14(222,"Aryan","delhi"); 17. e1.display(); 18. e2.display(); 19. } 20. } Output:111 Karan null 222 Aryan delhi Rule: Call to this() must be the first statement in constructor. 1. class Student15{ 2. int id; 3. String name; 4. Student15(){System.out.println("default constructor is invoked");} 5. Student15(int id,string name){ 6. id = id; 7. name = name; 8. this ();//must be the first statement 9. } 10. void display(){system.out.println(id+" "+name);} 11. public static void main(string args[]){ 12. Student15 e1 = new Student15(111,"karan"); 13. Student15 e2 = new Student15(222,"Aryan"); 14. e1.display(); 15. e2.display(); 16. } 17. } Output:Compile Time Error 3)The this keyword can be used to invoke current class method (implicitly). You may invoke the method of the current class by using the this keyword. If you don't use the this keyword, compiler automatically adds this keyword while invoking the method. Let's see the example

1. class S{ 2. void m(){ 3. System.out.println("method is invoked"); 4. } 5. void n(){ 6. this.m();//no need because compiler does it for you. 7. } 8. void p(){ 9. n();//complier will add this to invoke n() method as this.n() 10. } 11. public static void main(string args[]){ 12. S s1 = new S(); 13. s1.p(); 14. } Output:method is invoked 4) this keyword can be passed as an argument in the method. The this keyword can also be passed as an argument in the method. It is mainly used in the event handling. Let's see the example: 1. class S2{ 2. void m(s2 obj){ 3. System.out.println("method is invoked"); 4. } 5. void p(){ 6. m(this); 7. } 8. public static void main(string args[]){ 9. S2 s1 = new S2(); 10. s1.p(); 11. }

12. } Output:method is invoked Application of this that can be passed as an argument: In event handling (or) in a situation where we have to provide reference of a class to another one. 5) The this keyword can be passed as argument in the constructor call. We can pass the this keyword in the constructor also. It is useful if we have to use one object in multiple classes. Let's see the example: 1. class B{ 2. A4 obj; 3. B(A4 obj){ 4. this.obj=obj; 5. } 6. void display(){ 7. System.out.println(obj.data);//using data member of A4 class 8. } 9. } 10. class A4{ 11. int data=10; 12. A4(){ 13. B b=new B(this); 14. b.display(); 16. public static void main(string args[]){ 17. A4 a=new A4(); 18. } 19. } Output:10 6) The this keyword can be used to return current class instance. We can return the this keyword as an statement from the method. In such case, return type of the method must be the class type (non primitive). Let's see the example: Syntax of this that can be returned as a statement 1. return_type method_name(){ 2. return this; 3. } Example of this keyword that you return as a statement from the method

1. class A{ 2. A geta(){ 3. return this; 4. } 5. void msg(){system.out.println("hello java");} 6. } 7. class Test1{ 8. public static void main(string args[]){ 9. new A().getA().msg(); 10. } 11. } Output:Hello java Proving this keyword Let's prove that this keyword refers to the current class instance variable. In this program, we are printing the reference variable and this, output of both variables are same. 1. class A5{ 2. void m(){ 3. System.out.println(this);//prints same reference ID 4. } 5. public static void main(string args[]){ 6. A5 obj=new A5(); 7. System.out.println(obj);//prints the reference ID 8. obj.m(); 9. } 10. }