Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using "this" with class name

Tags:

java

android

this

I am doing Android programming and was learning about Intents, when I saw a constructor that, to my C# trained mind, seemed funky. The call was:

Intent myIntent = new Intent(CurrentActivity.this, NextActivity.class);

Both of the parameters are new to me. How is there a static ".this" off of a Class Name? Is this a Java thing or an Android thing? I am assuming that it is the same as just saying "this", since I am in the context of CurrentActivity, but I don't get how the "this" can be called off of the Class name itself. Also. The ".class" looks like it is used for reflection, which I am familiar with in C#, but any insight into this would be welcomed as well.

Thanks.

like image 841
skaz Avatar asked Oct 17 '22 04:10

skaz


People also ask

Can we call a function with class name?

We can call a static method by using the ClassName. methodName. The best example of the static method is the main() method. It is called without creating the object.

Can we use keyword as class name in Java?

In Java, Using predefined class name as Class or Variable name is allowed. However, According to Java Specification Language(§3.9) the basic rule for naming in Java is that you cannot use a keyword as name of a class, name of a variable nor the name of a folder used for package.

How do you call a class name in Java?

The simplest way is to call the getClass() method that returns the class's name or interface represented by an object that is not an array. We can also use getSimpleName() or getCanonicalName() , which returns the simple name (as in source code) and canonical name of the underlying class, respectively.

What is a class name?

The name of a logical class, a general name; (Grammar) = class noun .


1 Answers

Usually, you can use only this. But, sometimes this makes reference to an inner class... so, for example:

Button button = (Button)findViewById(R.id.ticket_details_sell_ticket);
button.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View v) {
        // it will be wrong to use only "this", because it would
        // reference the just created OnClickListener object
        Intent login = new Intent(ClassName.this, Login.class);
        startActivityForResult(login, LOGIN_REQUEST);
    }
});
like image 143
Cristian Avatar answered Oct 19 '22 17:10

Cristian