This question already has answers here:
What is the meaning of "this" in Java?
(22 answers)
Closed 9 years ago.
I am currently in the process of learning Java, and I have done what I could to try and understand what these two things mean and do, but I simply don't get it. I have done a lot of googling, and also checked around for past questions on the site, but I still don't get it. So far I know that "this" somehow refers to some kind of method/variable/object, but I just don't get how it can refer to any of these, without (in the examples I have seen) actually specifing what to refer to, they just use the keyword "this.something or this(532);", it does not make sense. Same story with toString, they is no logic in these two that I get. Anyways, can anyone explain these two keywords in a simple way to me, and tell me how they can be even remotely useful in any program. Thanks in advance.
this.something refers to object something in the current class.
this.method() refers to a method of the current class
this() refers to constructor of the current class
toString() is a method used to create String representation of an object. Since every class in Java is a sub-class of Object and Object has toString() method, every class has a default toString() method. Often you will need to override the default toString() in order to get meaningful results.
The this keyword refers to the instance of the class.
this(512) refers to a constructor of the class that takes an int as Argument
this.field refers to a field of the class
this.method() refers to a method of the class
The toString() method is inherited from Object but can be overridden in a subclass to get more meaningful output.
For example if your class is like the following:
public class Database {
public Database (int port){
}
}
Then to refer this class' object, you can use like so: this(3306);
As a result this keyword is used for referring to the class
The this keyword refers to the current instance of the class (see http://docs.oracle.com/javase/tutorial/java/javaOO/thiskey.html).
The toString() keyword isn't a keyword: it is a method name. It is defined in the Object class and can be overridden. What it does is creates the text representation of the class (see http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Object.html#toString()).
Related
I'm trying to find a solution for a project assignment. Basically I have created a class which is derivative of another abstract class. In it's construction I'm trying to call the supertype constructor with a string and an integer as argument. The issue is that I'm trying to calculate the integer value in an overridden method in the same class. Like so:
super(name, getBaseValue());
This doesn't work because I can't reference the method within the supertype constructor. Maybe I have simply misunderstood the assignment and the UML-diagram. Any ideas how to go about solving this?
getBaseValue() must be static and also use this.getBaseValue (), so that it looks like this:
super(name, this.getBaseValue());
You probably shouldn't do that at all. At the time the constructor runs, the object is not yet created (it's still in the process of being created), and calling a method on it is risky because that method may assume the object is fully created. Even worse, a derived class could also define that method, and then you the parent constructor isn't even done when a child class' method is already called --- chaos.
You can call static methods (which don't require an object instance being created), or you can hard-code any values you want to pass.
See also MET05-J. Ensure that constructors do not call overridable methods in the Secure Java Coding Standard and Sonar Source's warning about this.
I know super is a special reserved keyword but from the way how we use it , it should be called as object. Can some one clarify whether my thought is right or wrong. Would be better if you can provide more detailed clarification on this.
That would not be correct. Super is a keyword in java used to reference the superclass of the instance of a class.
Object is an instance of a class.
You cannot use the word "super" unless an instance of a class exist, therefore, it cannot be considered equivalent to an object.
Think of a hypothetical class Human. You can ask me "what's your superclass" and I would say "it's Creature". But you cannot "create" a new Human by asking "what's your superclass".
Maybe your confusion comes from the usage of the word "super" in the constructor. When we make the super(); call, we're actually executing the superclass's constructor. As you know, constructors are very particular methods and they are not invoked the same way another method would have been. If I was to refer to a getter of the superclass, I would do super.getWhatever(); instead. However, we cannot do super.something() to call a constructor, so we just do super();.
And regarding the call to the superclass's constructor when constructing an instance of a class, that's because you cannot call me "Human" before defining me as a "Creature". So, you first create the creature characteristics on me and then you make me human.
I hope that makes sense :).
I am trying to write an abstract class. In that class I have a method which is supposed to access the actual object for which the method is called.
"this" however will only return the "part of the object" that I write myself (the abstract one).
To specify some more:
If the method I was writing had a parameter of the type of my class, what i want looks like this:
public abstract class MyClass {
public void foo(MyClass invoker) {
...
}
}
The above code would allow me access to the object invoking the method, but it would be tedious to write it like this, since this is supposed to become part of a library I want to supply to others and I cannot know for certain, that the passed argument would in fact be the right object and not some other object of a class derived from MyClass.
Is there a way to invoke something along the lines of getNestingObject() or do I specifically have to give the method a parameter and constantly infer "this" to every call?
Finally, since I am no master in java, a perhaps less obvious question:
Is there a security reason, why the above described concept is flawed? Could someone
with malicious intent abuse that kind of keyword?
I am trying to write an abstract class. In that class I have a method
which is supposed to access the actual object for which the method is
called. "this" however will only return the "part of the object" that
I write myself (the abstract one).
this will return a reference to "the whole" object, not "a part". To proof this, if you cast this reference to a class that is lower in the hierarchy, you can access any property or method of this class using the instance referenced by this.
However, casting the instance referenced by this, would not be a good design practice. Speaking in general terms, you should write a foo method in MyClass with the general behaviour, and override it with the particular behaviour of each classs. If you want to use the foo method of the parent class, you can invoke it using super.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What is a class literal in Java?
I was going through literals in the Java tutorial where I came across this sentence:
Finally, there's also a special kind of literal called a class literal, formed by taking a type name and appending ".class"; for example, String.class. This refers to the object (of type Class) that represents the type itself.
Which doesn't make any sense to me, even though I paid attention to all the other topics prior to this. Can anyone explain in simple language with examples or references?
Instances of the class java.lang.Class represent classes and interfaces in a running Java application. For each class in the application, there is an instance of Class. The SomeClass.class syntax is a way to get from SomeClass to the corresponding instance of Class.
A class literal is just a special type to use when you want to do something involving the class itself, rather than an instance.
Here's a short list of a few things I commonly use this for (not at all comprehensive, but you can get a good idea)
1.) Reflection, you want to instantiate something in run-time that you may not know (perhaps it was stored in a variable of type Class)
2.) You want to check if 2 objects are of the same related type, you can write something along the lines of: B.class.isAssignableFrom(a.getClass());
3.) You want to list all the methods, or public variables within a class, perhaps for documentation.
There are many other uses, but these are the main ones I find myself using in common practice.
Speaking simple language: that thing, which you call class literal is an object which fully describes some class: all its methods, all its fields, all its annotations, class's modifiers and so on. It is needed for creating new instances of that class in runtime.
Short example:
Class x = String.class;
System.out.println(x);
you can use x to create runtime instances of the class it points to or to test the class of an object against it.
It evaluates to be the class identifier of the reference or primitive type's wrapper class. The expression void.class evaluates to the class identifier of the Void class. Same thing with 'String.class'
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
In Java, what does a reference to Class.class do?
Firstly apologies for asking this question here. I know it's a simple question and can probably be answered quite quickly and easily. However searching for Java .class is such a loaded search term it brings up nothing useful.
Having said that, I just started learning Java and I just came across something like this:
Intent i = new Intent(this, ReminderManageActivity.class);
I am not sure, but I think ReminderManageActivity.class is an attribute that gives a string of the name of the class? Is that correct?
I know it sounds stupid, but class is a Class object that represent the Class.
If you want to instantiate / use some class, and you want to get this class as parametr, you can't just write Intent i = new Intent(this, ReminderManageActivity); since ReminderManageActivity is not an object.
In Java, given an object, an instance of a class, you can get the class name by coding the following:
Class clazz = obj.getClass();
String clazzName = clazz.getName();
Sometimes you want you want to create a Class object for a given class. In this case you can do so by writing code similar to the following example:
Class clazz = MyClass.class;
source
If you just started learning java than you will see more about this when you will study Type Information or RTTI(Runtime Type Information)
ReminderManageActivity.class
is called a class literal and it produces a reference to the Class object, which contains information about the class in question.
It is similar to the static method :
Class.forName("ReminderManageActivity");
It is an instance of java.lang.Class which is part of Java Refleciton API. You can get more informaiton about the API here
Because everything in Java is an object, so even classes can be represented by objects.
ReminderManageActivity.class returns a Class object representing the ReminderManageActivity class.
A Class object contains information of a class, such as class' name, class' method, class's variables etc. You can look at the class API for more information: http://download.oracle.com/javase/6/docs/api/java/lang/Class.html