Destroying this in java

this keyword in Java

this is a keyword in Java. It can be used inside the method or constructor of a class. It(this) works as a reference to the current object, whose method or constructor is being invoked. This keyword can refer to any member of the current object from within an instance method or a constructor.

this keyword with a field(Instance Variable)

this keyword in java can be handy in the handling of Variable Hiding. We can not create two instances/local variables with the same name. However, it is legal to create one instance variable & one local variable or Method parameter with the same name. In this scenario, the local variable will hide the instance variable; this is called Variable Hiding.

Example of Variable Hiding

class JBT < int variable = 5; public static void main(String args[]) < JBT obj = new JBT(); obj.method(20); obj.method(); >void method(int variable) < variable = 10; System.out.println("Value of variable :" + variable); >void method() < int variable = 40; System.out.println("Value of variable :" + variable); >>

The output of the above program

Value of variable :10 Value of variable :40

As you can see in the example above, the instance variable is hiding, and the value of the local variable (or Method Parameter) is displayed, not the instance variable. To solve this problem, use this keyword to point to the instance variable instead of the local variable.

Example of this keyword in Java for Variable Hiding

class JBT < int variable = 5; public static void main(String args[]) < JBT obj = new JBT(); obj.method(20); obj.method(); >void method(int variable) < variable = 10; System.out.println("Value of Instance variable :" + this.variable); System.out.println("Value of Local variable :" + variable); >void method() < int variable = 40; System.out.println("Value of Instance variable :" + this.variable); System.out.println("Value of Local variable :" + variable); >>

The output of the above program

Value of Instance variable :5 Value of Local variable :10 Value of Instance variable :5 Value of Local variable :40

this Keyword with Constructor

“this” keyword can be used inside the constructor to call another overloaded constructor in the same class. It is called the Explicit Constructor Invocation. This occurs if a Class has two overloaded constructors, one without argument and another with the argument. Then this” keyword can call the constructor with an argument from the constructor without argument. This is required as the constructor cannot be called explicitly.

Читайте также:  border-bottom-color

Example of this with Constructor

class JBT < JBT() < this("JBT"); System.out.println("Inside Constructor without parameter"); >JBT(String str) < System.out .println("Inside Constructor with String parameter as " + str); >public static void main(String[] args) < JBT obj = new JBT(); >>

The output of the above program

Inside Constructor with String parameter as JBT Inside Constructor without parameter 

As you can see, “this” can invoke an overloaded constructor in the same class.

  • this keyword can only be the first statement in Constructor.
  • A constructor can have either this or super keyword but not both.

this Keyword with Method

this keyword can also be used inside Methods to call another Method from the same Class.

Example of this keyword with Method

class JBT < public static void main(String[] args) < JBT obj = new JBT(); obj.methodTwo(); >void methodOne() < System.out.println("Inside Method ONE"); >void methodTwo() < System.out.println("Inside Method TWO"); this.methodOne();// same as calling methodOne() >>

The output of the above program

Inside Method TWO Inside Method ONE

Example of this keyword as a Method parameter

public class JBTThisAsParameter < public static void main(String[] args) < JBT1 obj = new JBT1(); obj.i = 10; obj.method(); >> class JBT1 extends JBTThisAsParameter < int i; void method() < method1(this); >void method1(JBT1 t) < System.out.println(t.i); >> 

If you understood this keyword correctly, the next step should be to understand the Static Keyword in Java from Java Tutorial.

References
1- Official Document

Next Post
Java Static Keyword

70 thoughts on “this keyword in Java”

class car
int speed;
car()
speed=70;
>
protected void finalize()
System .out.println(“destroy object of car”);
>
>
class bike
int speed;
bike()
speed=70;
>
protected void finalize()
System.out.println(“destroy object of bike”)
>
>
class Garbage_Collection
public static void main(String []args)
car c=new car();
bike b=new bike();
b=null;
System.gc();
System.out.println(“speed of car: “+c.speed);
>
>

class JBT <
public static void main(String[] args) <
JBT obj = new JBT();
obj.methodTwo();
>
void methodOne() <
System.out.println(“Inside Method ONE”);
>
void methodTwo() <
System.out.println(“Inside Method TWO”);
this.methodOne();// same as calling methodOne()
>
> when I removed ‘this’ from the line this.methodOne();// same as calling methodOne() I get the same output. Is this the standard behaviour ?

Yes, that is standard behavior. this is just used to point to the current object and in this case, it is the current object’s method. So it will get called.

Источник

Destructor in Java

Destructor in Java

Destructors in Java can be learned with the finalize method in Java. The concept is as same as the finalize method. Java works for all except the destructor with the help of the Garbage collection. Therefore, if there is a need for calling the destructor, it can be done with the help of the finalize method. This method is not independent as it relies on Garbage Collection. The garbage collector is a thread that deletes or destroyed the unused object in the heap area. Say if the object is connected to a file or say some database application or network connections, before deleting or destroying the object, it has to close all the connections related to these resources before the garbage collection takes place. This closing of the functions is done by calling the finalize method.

Читайте также:  Python request ssl certificate

Definition of Destructor in Java

“ Destructor is a method called when the destruction of an object takes place. “ The main goal of the destructor is to free up the allocated memory and also to clean up resources like the closing of open files, closing of database connections, closing network resources, etc.,

How Does Destructor Work in Java?

The destructor has a finalize() method in java, which is similar to the destructor in C++. When the objects are created, they are stored in the heap memory. These are accessible by main or child threads. So when these objects are no more used by the main thread or its child threads, they become eligible for garbage collection and the memory which was acquired now becomes available by new objects being created. Before an object is a garbage collected by the garbage collector, the JRE (Java Runtime Environment) calls the finalize() method to close the input-output streams, the database connections, network connections, etc. Note that the finalize method called is protected. Why finalize is protected because it can be either called by the base class or derived class? finalize method is present in the Object class. Thus in case you want to call this finalize method from other objects, you can change this protected to public.

protected void finalize throws Throwable() < //Keep some resource closing operations here >

Methods of finalize()

  1. finalize() method is protected as defined in java.lang.Object class.
  2. finalize() method is called only once.
  3. to override the finalize() method, you need to call the finalize method explicitly.
  4. GC() is a service of JVM to execute Garbage Collection; it is called when the heap memory is full and needs memory for new arriving objects.
  5. JVM ignores all exceptions except the unchecked exceptions that occur in the finalize method.

Example #1

The String class corresponding finalizes method is called instead of the finalize method present in the program in the below program. The finalize method is overridden here.

public class Demo < public static void main(String[] args) < Integer i = new Integer(2); i = null; System.gc(); System.out.println("In the Main Method"); >protected void finalize() < System.out.println("object is garbage collected "); >>

Destructor in Java - Example 1

Example #2

In the below program, the finalize method is called internally; no explicit call required.

public class Demo < public static void main(String[] args) < Demo dm = new Demo(); dm = null; System.gc(); System.out.println("In the Main Method"); >protected void finalize() < System.out.println("object is garbage collected "); >>

Destructor in Java - Example 2

Example #3

In the below program, the finalize was called internally depending upon the number of objects created.

public class NewProgram < public void finalize()< System.out.println("object is garbage collected"); >public static void main(String args[]) < NewProgram np1=new NewProgram(); //first instantiation of Class NewProgram NewProgram np2=new NewProgram(); //second instantiation of Class NewProgram np1=null; np2=null; System.gc(); System.out.println("In the Main Method"); >> 

Destructor in Java - Example 3

Example #4

In the below program, two objects are created the finalize is called once as both the objects are pointing to the same.

public class NewProgram < public void finalize()< System.out.println("garbage collected"); >public static void main(String args[]) < NewProgram np1=new NewProgram(); //first instantiation of Class NewProgram NewProgram np2=new NewProgram(); //second instantiation of Class NewProgram np1 = np2; // both now pointing to same object System.gc(); System.out.println("in the Main Method"); >>

Output:

Читайте также:  Php number format no rounding

Destructor in Java - Example 4

Example #5

In the below program, the finalize method will be called twice explicitly and internally both.

public class Demo < public static void main(String[] args) < Demo dm = new Demo(); dm.finalize(); dm = null; System.gc(); System.out.println("In the Main Method"); >protected void finalize() < System.out.println("garbage collected "); >>

Example 5

Example #6

In the below program, an arithmetic exception is called in the finalize method as it is explicitly called, which further causes the exception and stops the execution of the remaining program.

public class Demo < public static void main(String[] args) < Demo dm = new Demo(); dm.finalize(); dm = null; System.gc(); System.out.println("In the Main Method"); >protected void finalize() < System.out.println("garbage collected "); System.out.println(10 / 0); >>

Example 6

Example #7

There is no exception called in the below program as it is not called explicitly and continues the execution of the remaining program.

public class Demo < public static void main(String[] args) < Demo dm = new Demo(); dm = null; System.gc(); System.out.println("In the Main Method"); >protected void finalize() < System.out.println("garbage collected "); System.out.println(10 / 0); >>

Example 7

Advantages of Destructor in Java

  1. The destructor destroys the value created by the constructor to space in heap memory.
  2. Destructor is always called at the end of the program.
  3. Destructor is never overloaded destructor doesn’t take any argument.
  4. No need to define our constructor; the compiler creates for us one.

Conclusion

I hope this article was interesting and informative both for you to learn the topic. This article given has covered almost all the topics you are looking for, and I hope fulfills all of your requirements.

This has been a guide to Destructor in Java. Here we have discussed the Definition of Destructor in Java, How does destructor work in java with Methods, advantages and different examples. You can also go through our other suggested article to learn more-

89+ Hours of HD Videos
13 Courses
3 Mock Tests & Quizzes
Verifiable Certificate of Completion
Lifetime Access
4.5

97+ Hours of HD Videos
15 Courses
12 Mock Tests & Quizzes
Verifiable Certificate of Completion
Lifetime Access
4.5

JAVA Course Bundle — 78 Courses in 1 | 15 Mock Tests
416+ Hours of HD Videos
78 Courses
15 Mock Tests & Quizzes
Verifiable Certificate of Completion
Lifetime Access
4.8

Источник

Оцените статью