Java static this keyword

static and this Keywords in Java With Examples

Let us look at the significance of the static keyword on each of them.

Static Variable

Declaring a variable as static makes it a static variable. It is used to define the common attribute that is to be shared among all the instances of an object. It is used for saving memory when it is known that all objects are going to share the same value for a specific attribute. To access such a variable, we do not need any instance. We can simply access it using the Class name. Since it is shared, any change made in such a variable gets reflected in every instance.

As a result, the variable gets loaded in memory only once, that too at the time of class loading.

Example:

While creating a Java application for School, we realize that the students will have the same school name attribute. So instead of making the school name attribute, an instance variable, we make it a static variable. There will be only one memory allocation, instead of each copy for every student.

Non-Static Approach: Here school is an instance variable. As a result, every instance is going to have to its own copy resulting in wastage of space

class Students < //Instance Variable String name; String clas; String sec; int rollNo; String school; //Parameterized Constructor Students(String n,String c, String s, int rn, String sch)< name=n; clas=c; sec=s; rollNo=rn; school=sch; >//method to print the details void getDetails() > public class School < public static void main(String args[])< Students obj1 = new Students("Gourav Gupta","XII","C",7,"Don Bosco High School"); Students obj2 = new Students("Madhurav Prasad","XI","A",25,"Don Bosco High School"); obj1.getDetails(); obj2.getDetails(); >> 

Output:

Gourav Gupta XII C 7 Don Bosco High School Madhurav Prasad XI A 25 Don Bosco High School

Static Approach: We can declare the school as static, and it will yield the same performance saving lots of memory.

class Students < //Instance Variable String name; String clas; String sec; int rollNo; //Static Variable static String school="Don Bosco High School"; //Parameterized Constructor Students(String n,String c, String s, int rn)< name=n; clas=c; sec=s; rollNo=rn; >//method to display the values void display () > public class School < public static void main(String args[])< System.out.println("School is a class member. Can be accessed by Class Name also.\nSchool Name:"+Students.school+"\n"); Students obj1 = new Students("Gourav Gupta","XII","C",7); Students obj2 = new Students("Madhurav Prasad","XI","A",25); obj1.display(); obj2.display(); >> 

Output:

School is a class member. Can be accessed by Class Name also. School Name:Don Bosco High School Gourav Gupta XII C 7 Don Bosco High School Madhurav Prasad XI A 25 Don Bosco High School

Static Method

Declaring a method as static makes it a static method. As a result, the class belongs to the class rather than the object. To access such a method, we do not need any instance. We can simply access it using the Class name.

It is for this reason the main method is static in nature. The main serves to be the entry point of the program execution. Making it static allows the JVM to execute using Class only without instantiating and allocating unnecessary memory.

A static method can only access the static variable and not the instance variable.

Example:

class Students < //Instance Variable String name; String clas; String sec; int rollNo; //Static Variable static String school="Don Bosco High School"; //Parameterized Constructor Students(String n,String c, String s, int rn)< name=n; clas=c; sec=s; rollNo=rn; >//method to display the values void display () //Static Method to change the static member static void setSchoolName(String newName) < school = newName; >> public class School < public static void main(String args[])< System.out.println("School is a class member. Can be accessed by Class Name also.\nSchool Name:"+Students.school+"\n"); Students obj1 = new Students("Gourav Gupta","XII","C",7); Students obj2 = new Students("Madhurav Prasad","XI","A",25); obj1.display(); obj2.display(); Students.setSchoolName("St. Mary High School"); System.out.println("\n\nSchool name is changed.\nSchool Name:"+Students.school+"\n"); obj1.display(); obj2.display(); >> 

Output:

School is a class member. Can be accessed by Class Name also. School Name:Don Bosco High School Gourav Gupta XII C 7 Don Bosco High School Madhurav Prasad XI A 25 Don Bosco High School School name is changed. School Name:St. Mary High School Gourav Gupta XII C 7 St. Mary High School Madhurav Prasad XI A 25 St. Mary High School

Java Static Block

The static block is an anonymous block enclosed by <> and preceded with the keyword static . It is used to initialize static attributes. In order of execution, the static block is executed before the main method during class loading. Note, that it is simply executed earlier and cannot be an alternative to the main method.

Example:

public class School < static int val; static< System.out.println("I am inside static block"); val=25; >public static void main(String args[])< System.out.println("I am inside main block"); System.out.println("Static variable val language-java">class MyClass < int param1; int param2; //Parameterized Constructor //Here, both the parameter and instance variable has same name MyClass(int param1,int param2) < param1 = param1; //compiler doesn't assign, but only evaluate param2 = param2; //compiler doesn't assign, but only evaluate >> public class ClassWithMain < public static void main(String args[])< MyClass obj = new MyClass(5,6); //This has no impact on values of param1 and param2 System.out.println(obj.param1+" "+obj.param2); >> 

Output:

So we can see that the constructor dint perform initialization. Upon usage of this , let us see what difference does it make.

class MyClass < int param1; int param2; //Parameterized Constructor //Here, both the parameter and instance variable has same name //Using this.variable name specifies that it is an instance variable, not the input parameter MyClass(int param1,int param2) < this.param1 = param1; this.param2 = param2; >> public class ClassWithMain < public static void main(String args[])< MyClass obj = new MyClass(5,6); //This has impact on values of param1 and param2 because of this keyword System.out.println(obj.param1+" "+obj.param2); >> 

Output:

Constructor invocation using this

this is used to call one version of the constructor from another. This helps in configuring the chain of constructor calls. It is by convention to use this as the first statement of the constructor.

Example:

class MyClass < int param1; int param2; //Parameterized Constructor //Here, both the parameter and instance variable has same name //Using this.variable name specifies that it is an instance variable, not the input parameter MyClass(int param1) < System.out.println("I am inside Constructor 1"); this.param1 = param1; >MyClass(int param1,int param2) < //It signifies that constructor version with only 1 input parameter is to be executed first this(param1); System.out.println("I am inside Constructor 2"); this.param2 = param2; >> public class ClassWithMain < public static void main(String args[])< MyClass obj = new MyClass(5,6); //This has impact on values of param1 and param2 because of this keyword System.out.println(obj.param1+" "+obj.param2); >> 

Output:

I am inside Constructor 1 I am inside Constructor 2 5 6

This was an overview of static and this keyword. We will be discussing Java Inheritance in the next lecture.

Источник

Ключевое слово this

Java-университет

Ключевое слово this <в примерах data-lazy-src=

Таким образом, здесь this позволяет не вводить новые переменные для обозначения одного и того же, что позволяет сделать код менее «перегруженным» дополнительными переменными.

Пример второй — Применение this для явного вызова конструктора

Вызов одного конструктора из другого может пригодиться тогда, когда у вас (как ни странно) несколько конструкторов и вам не хочется в новом конструкторе переписывать код инициализации, приведенный в конструкторе ранее. Запутал? Все не так страшно как кажется. Посмотрите на код ниже, в нем два конструктора класса Human :

 class Human < int age; int weight; int height; Human(int age, int weight)< this.age = age; this.weight = weight; >Human(int age, int weight, int height) < //вы вызываете конструктор с двумя параметрами this(age, weight); //и добавляете недостающую переменную this.height = height; >> 

Здесь у нас сначала приводится конструктор с двумя параметрами, который принимает int age и int weight . Допустим, мы написали в нем две строчки кода:

 this.age = age; this.weight = weight; 

а потом решили добавить еще один конструктор, с тремя параметрами, который помимо возраста и веса принимает еще и рост. В новом конструкторе вы бы могли написать так:

 this.age = age; this.weight = weight; this.height = height; 

Но вместо того, чтобы повторять уже написанный ранее код в этом конструкторе, вы можете с помощью ключевого слова this явно вызвать конструктор с двумя параметрами:

 this(age, weight); // и дописываете недостающую переменную: this.height = height; 
  • вызови this (этот) конструктор, который имеет два параметра.
  • и добавить недостающую переменную.

Ключевое слово this <в примерах data-lazy-src=

Java static and this Keyword

There are various reserve words that Java provides to do different types of operations. Keywords are reserved words whose meanings are already known to Java compiler. There are two essential keywords in Java that are used for very special purposes.

What is static in Java?

Static keyword is unacceptable to the following

  • Class
  • Constructor
  • Local inner classes
  • Inner class methods
  • Instance variables
  • Local Variables
  • Interfaces

Static variables or methods can be invoked without having an instance of the class. Only a class is needed to call up a static method or a static variable. If you declare any variable as static, it is known static variable. The static variable can refer to a common property of all objects (that is not unique for each object), e.g. company name of employees, college name of students, etc. Memory in a static variable is reserved only once in a class area at the time of class loading. One advantage of using static is that it increases the efficiency of the memory.

Program for Static in Java

public class egStatic < static int x = 60; static void fun() < System.out.println("Within Static"); >public static void main(String[] args) < egStatic.fun(); System.out.println(egStatic.x); egStatic S1 = new egStatic(); egStatic S2 = new egStatic(); System.out.println(S1.x); S1.fun(); >>

Rules for using Static Variables

  • Variables or methods belong to class rather than to any particular instance
  • A static method cannot access a non-static variable of a class nor can directly invoke non-static method
  • Static members can be applied without creating or referencing an instance of the class
  • A static variable will be shared by all instances of that class which will result in only one copy

What is this keyword in Java?

  • For referring current class instance variable, this keyword can be used
  • To invoke current class constructor, this() is used
  • this can be passed as message argument in a method call
  • In a constructor call, this can be passed as argument
  • For returning current class instance, this keyword is used

Program for this in Java

class Emp < int e_id; String name; Emp(int e_id, String name) < this.e_id = e_id; this.name = name; >void show() < System.out.println(e_id + " " + name); >public static void main(String args[]) < Emp e1 = new Emp(1006, "Karlos"); Emp e2 = new Emp(1008, "Ray"); e1.show(); e2.show(); >>

Источник

Читайте также:  Css image properties size
Оцените статью