Using this in static method java

Why am i able to use this keyword with static variables in java

I am a beginner in java and i am trying to understand the concept of static from a book I bought to learn java. But, because of my experiments in the program, I am very confused. The book says that static could not refer to this keyword, which is fine until I started using normal functions instead of static. In this, I was able to access the static variable with the this keyword!! (see the displayMobileSpecs function in the code below)

import java.util.Random; class Static < public static void main(String[] com)< System.out.println("By default the mobile is having " + Mobile.RAM + "gigabytes of RAM and" + Mobile.CameraMP + " mega pixels of camera"); Mobile S4mini = new Mobile("S4 Mini" , 4 , 16); S4mini.displayMobileSpecs(true); Mobile mob2 = new Mobile("fdf" , 23 , 45); mob2.displayMobileSpecs(true); S4mini.displayMobileSpecs(false); >> class Mobile < static int RAM; static int CameraMP; Random rand = new Random(); double InternalMemorySpace; double ExternalMemorySpace; String modelNo; Mobile(String modelName,double internalMem , double externalMem) < this.modelNo = modelName; this.InternalMemorySpace = internalMem; this.ExternalMemorySpace = externalMem; >static < RAM = 4; CameraMP = 12; System.out.println("The Static part of the class is executed"); >void displayMobileSpecs(boolean change) < if(change) this.RAM = (int) rand.nextInt(8) + 2; System.out.println(this.RAM + " , " + Mobile.RAM); >> 

So is it that static variables could be accessed using this but not in the static functions or what?? I am really confused and this is a very silly question as I see it, but please answer me. (Note: by the way, please don’t mind the ridiculous example of mobile used in the program. thanks 🙂 )

Читайте также:  Позиционирование элементов при помощи css

1 Answer 1

static variables could be accessed using this but not in the static functions

In static block or a static method, there is no instance to refer to, and therefore the «this» keyword is not permitted.

Why am i able to use this keyword with static variables in java

But you can refer «this» in a non static method also you can use refer static variable with «this» keyword in the non static method.Here «this» points to current object.

Источник

Is it possible for a static method to refer to «this» in Java?

I am new to Java. I know static is class level and this is object level but please let me know if a static method can refer to the this pointer in java?

Since what you ask doesn’t make sense, I have to ask what it is you are trying to do. The whole point of a static method is that it doesn’t have a this , so the simplest way to change a static method to have a this is to remove the static keyword.

This question addresses the use of static and what it does. It might be useful to you: stackoverflow.com/questions/413898/…

You can put an inner class inside a static method and inside that inner class, the this pointer would make sense.

3 Answers 3

No it does not make sense to refer this in static methods/blocks. Static methods can be called without creating an instance hence this cannot be used to refer instance fields.

If you try to put this in a static method, compiler will throw an error saying

cannot use this in static context

Without a better explanation from the OP, it would be pointless to speculate on these types of situations.

No, this cannot be accessed in a static context. June Ahsan said everything that you probably need to know but I would like to add a little background.

The only difference between an object method and a static method on byte code level is an extra first parameter for object methods. This parameter can be accessed through this . Since this parameter is missing for static methods, there is no this .

class MyClass < private int b; public void myMethod(int a)< System.out.println(this.b + a); >public static void myStaticMethod(int a) < System.out.println(a*a); // no access to b >> 

on byte code level becomes (roughly speaking, because byte code does not look like this)

class MyClass < int b; >void myMethod(MyClass this, int a) < System.out.println(this.b + a); >static void myStaticMethod(int a) < System.out.println(a*a); // no access to b >

Источник

How to use this keyword in a static method in java?

Thus static classes were allowed, making the intent of the class, that of a place for the definition of static methods, clear to users and to the type system. The best use for a static class is for utility functions, you could also use them to keep the global methods and data in your application, I use static static classes very often in almost any project.

How to use this keyword in a static method in java?

Is there any way to use this keyword inside a static method in Java? I want to display a Toast message inside a static method in my activity class . How do I do that? Thanks.

You can create a static method with one input parameter that is the Class you need to use.

public static void showMyTouch(MyActivity act, String message)

No. There is nothing for it to refer to.

I believe that «this» represents the object that invokes the method. Static methods are not specifically bound to any particular object. Rather, they are class level methods . That is why «this» cannot be used in static methods.

C# — What is the use of a static class, A static class simply denotes that you don’t expect or need an instance. This is useful for utility logic, where the code is not object-specific. For example, extension methods can only be written in a static class. Pre C# 2.0, you could just have a regular class with a private constructor; but static makes it …

What is the use of a static class

What is the use of a static class? I mean what are benefits of using static class and how CLR deals with Static classes ?

A static class simply denotes that you don’t expect or need an instance . This is useful for utility logic , where the code is not object-specific. For example, extension methods can only be written in a static class.

Pre C# 2.0, you could just have a regular class with a private constructor; but static makes it formal that you can never have an instance (there is no constructor*, and all members must be static).

(*=see comment chain; you can optionally have a type initializer (static constructor aka .cctor ), but you cannot have an instance constructor (aka .ctor )).

The compilation and metadata model for .net requires that all functions are defined within a class. This makes life somewhat easier and simpler for the reflection api’s since the concepts of the owning class and its visibility is well defined. It also makes the il model simpler.

since this precludes free functions (ones not associated with a class) this makes the choice of where to put functions which have no associated state (and thus need for an instance). If they need no state associated with them nor have any clear instance based class to which they can be associated and thus defined within there needs to be some idiom for their definition.

Previously the best way was to define the methods within a class whose constructor was private and have none of the functions within the class construct it.

This is a little messy (since it doesn’t make it crystal clear why it was done without comments) and the reflection api can still find the constructor and invoke it.

Thus static classes were allowed, making the intent of the class, that of a place for the definition of static methods, clear to users and to the type system. Static classes have no constructor at all.

A static class is a language hack to write procedural programs in C#.

All members of a static class has to be static members, so, if you forget to add ‘static’ before any of them your code won’t compile, it also makes your code more readable as anyone who will see that the class is static will understand it only contains static members.

The best use for a static class is for utility functions, you could also use them to keep the global methods and data in your application, I use static static classes very often in almost any project.

Static Keyword in C++, Let us now look at each one of these use of static in details: Static Variables. Static variables in a Function: When a variable is declared as static, space for it gets allocated for the lifetime of the program.Even if the function is called multiple times, space for the static variable is allocated only once and the …

What is the role of static keyword in importing java.lang.System class?

I don’t understand the meaning of the keyword static when I import System class:

import static java.lang.System.* 

I’m reading the book about Java and it’s written there:

  • The name of a class within that package
  • An asterisk (indicating all classes within that package)

And I have the following code:

And it works when I import this way:

import static java.lang.System.out; import static java.lang.System.* 

But doesn’t work when I try do this:

import java.lang.System.out; import java.lang.System.* 

What’s the meaning of the static keyword in this particular case?

And why import java.lang.*; doesn’t import the whole package with System class in it?

A static import allows you to write this:

System.out.print("The result is "); 

See e.g. http://docs.oracle.com/javase/1.5.0/docs/guide/language/static-import.html.

I often use static imports in my unit tests, like so:

import static org.junit.Assert.*; 

This allows me to write this code:

Assert.assertEquals(2, list.size()); 

Static import is a feature introduced in the Java programming language that allows members (fields and methods) defined in a class as public static to be used in Java code without specifying the class in which the field is defined. This feature was introduced into the language in version 5.0.

The feature provides a typesafe mechanism to include constants into code without having to reference the class that originally defined the field. It also helps to deprecate the practice of creating a constant interface: an interface that only defines constants then writing a class implementing that interface, which is considered an inappropriate use of interfaces.

When you import with static keyword it means you just inserted it somehow in your class and you can use it’s methods the same way you’re calling your own classes’ methods.

import static java.lang.Math.*; import static java.lang.System.out; 
out.println("I have a house with an area of " + (PI * pow(2.5,2)) + " sq. cm"); 

1) it works when I import this way:

a. import static java.lang.System.out; b. import static java.lang.System.* 

But doesn’t work when I try do this:

c. import java.lang.System.out; d. import java.lang.System.*; 

2) What’s the meaning of the static keyword in this particular case?

3) And why import java.lang .*; doesn’t import the whole package with System class in it?

1) & 2) static imports e.g.(import static java.lang.System.out) are used to import methods or fields that have been declared as static inside other classes in this particular case from the System class.

a. import static java.lang.System.out; //Works because "out" is a static field b. import static java.lang.System.*; //Works because you are importing ALL static fields and methods inside the System class c. import java.lang.System.out; //Does NOT work because you are trying to import a static field in a non-static way. (see a.) d. import java.lang.System.*; //Actually Works because of the * wildcard which allows you to include all imports. 

The main reason why you would want to import methods or fields in a static way is so you can omit the class specification for all calls to those methods or fields. So instead of writing:

System.out.print("Hello"); System.out.print("World"); 
import static java.lang.System.* //or import static java.lang.System.out if you only plan on using the 'out' field. out.print("Hello"); out.print("World"); 

3) importing java.lang .* is redundant! Java automatically and implicitly imports this package for you! 🙂 and yes it imports the System class with it, but don’t get confused unless you imported it as a static import you will still need to write out the long way:

Check if the given string of words can be formed from, A naive Approach will be to match all words of the input sentence separately with each of the words in the dictionary and maintain a count of the number of occurrence of all words in the dictionary.So if the number of words in dictionary be n and no of words in the sentence be m this algorithm will take …

Why are Laravel Models static and should I use static functions in my own Models?

In Laravel Models use functions that are static and the documentation uses static functions to show how Models work. If I create a new Model for my application, it extends the base Model class but why is Laravel using static functions? I thought the idea is static anything is bad? For example, it makes testing harder?

I’m just confused as most things can be retrieved from the DI container? For example, a Model called Flight, why is it not used like this inside a controller:

namespace App\Http\Controllers; use App\Flight; class FlightController < public __construct(Flight $flight) < $this->flight = $flight; // etc. > > 

And Models are not even using a Facade either? When I create my own models am I suppose to always use static functions as well?

I’m not sure I understand your question correctly, but I think you are mistaking Facades for static methods. Read this https://laravel.com/docs/7.x/facades#how-facades-work, Laravel uses the magic method _callStatic() to resolve to actual instances. So it looks static, but it isn’t.

Static keyword in Java, 2) Java static method. If you apply static keyword with any method, it is known as static method. A static method belongs to the class rather than the object of a class. A static method can be invoked without the need for creating an instance of a class. A static method can access static data member and can change the …

Источник

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