System.out.println(this);
Why would you use 'this' in the brackets? Is it for printing the references? Or as in the code below for comparing if the object points to the same reference?
public void compareDrzewo(Drzewo tree)
{ if (tree == this)
{ System.out.println("true"); }
else { System.out.println("false"); }
main method code
Drzewo name1 = name2;
name1.compareDrzewo(name2);
The other examples of the use of 'this.' are quite straight forward (inner class etc.) Please comment only on this or similar use.
That instance has a toString() method associated with it, which means it will invoke it to print out meaningful information, or it uses Object's toString() (meaning it'll print out a memory location, which is much less useful).
System.out.println(this)
is the same as
System.out.println(this.toString());
So if the class of which this is an instance overrides the toString method, that line of code would be meaningful.
You use this to refer to the current object.
One example is when your want to refer to the current instance of your class, so if you need to call a method with your class, for example something.equals(this) or something == this.
Another example is explicitly specifiying a class instance of a variable rather than a local instance, for example a setter:
public void setMyVar(String myVar) {
this.myVar = myVar;
}
So myVar is the variable declared in the method, this.myVar is the variable declared in your class.
Related
I don't think we can instantiate an Enum. So do we need to have toString(), equals() and hashCode() method for an enum? Is this statement true?
Also as a follow up question
What does "this" keyword refers to in the following enum class?
public enum DocuType {
text, print, html, pdf; //Why aren't these in caps?
public boolean isPrint() {return this == print; } //What does this refers to?
public boolean isText() {return this == text; }
public boolean isTextOrPrint() { return isText() || isPrint(); }
}
How do I call any of the boolean methods of this enum as they are not static?
Also when I call, what does the keyword "this" refers to ?
I don't think we can instantiate an Enum.
Enum is one of type as we have class type. The way we can create instance (i.e. create variable) of a class, similarly we can create variables of Enum but that's only during during its definition which eventually makes them a Constant.
So do we need to have toString(), equals() and hashCode() method for an enum?
equals() & hashcode() are used to compare two instances. In case of class instances, the instances are created dynamically. So this means we don't have knowledge about instances beforehand and hence we need to compare them to know if they are equal. However, in case of Enum we know the instances when we define the Enum. So, we know beforehand whether they are equal or not. If the enum instances mean to be equal why on the earth we need two separate equal enum instances. So, in case of enum we generally don't override these methods.
What does "this" keyword refers to in the following enum class?
&
How do I call any of the boolean methods of this enum as they are not static?
&
Also when I call, what does the keyword "this" refers to ?
this means an instance currently in access. In your example, you have DocuType instances as text, pdf, print, html. When you invoke a method on any of the instance, ex: DocuType.text.isPrint(), this keyword inside the isPrint method will point to text. So, for instance pdf, all the methods will return false except isPdf().
So do we need to have toString(), equals() and hashCode() method for an enum? Is this statement true?
You don't need any of these methods in the enum.
Also as a follow up question What does "this" keyword refers to in the following enum class?
Imagine you have this code:
DocuType myType = DocuType.print;
If you want to check if the document is a PRINT document, you can do this:
boolean isPrint = myType.isPrint();
In this case, this is the myType, which means that it's the print enum. In the end, the result is true, because print == print;
I would also suggest to read the Tutorial to Enums
It seems you lack the knowledge of the concept of an enum.
And to your last question, an enum is static, but each "type" of it is an object, meaning you can do
DocuType.html.isText(); // false
DocuType.print.isPrint(); // true
To initalize your own Enum you have to
DocuType TextDocu = DocuType.text;
And you can write them in CAPS, but you don't have to, but it's recommened.
To explain it more in detail:
enum DocuType //this is an enum and not instantiatable
text,print,html,pdf // these are Objects with the functions of the enum and are an instance
As preparation for an explanation, a quick glance back in history.
Before enums were available in Java, a possible replacement could have been constructed like that:
public class DocuType {
public final static DocuType text=new DocuType();
public final static DocuType print=new DocuType();
public final static DocuType html=new DocuType();
public final static DocuType pdf=new DocuType();
private DocuType(){}; // hide constructor
public boolean isPrint() {return this == print; }
public boolean isText() {return this == text; }
public boolean isTextOrPrint() { return isText() || isPrint(); }
}
As you can see, while you cannot create new instances of DocuType, 4 static instances of them are already prepared for you in the Class.
Javas enum work very similar to that example (less writing involved, obviously); therefore, this refers to the instance you execute the method on. Regarding toString, it's up to you; the default implementation can be good enough or not. There is no need to implement neither equals nor hashCode.
In java. How to return the same exceuting object in a return object(same) method without taking the name of the excecuting object as a parameter. For example, suppose there is a method in a class called X(parameters) with the same return type of the class. And I created an Object of the class let it be Y. And I invoke this method by Y.X(par). Can i return Y inside the method from this invocation in a special case.
Is there a way in the java language to do this around other than declaring the method static and taking two paramters?
Consider for the previous example a simple concatenate method.
LinkedList concate(LinkedList secondList){
if(secondList.isEmpty()) return (current object);// What is the right form ??
// current object is a pseude code not java's
}
Thanks in Advance!
What you are looking for is 'this' operator.
LinkedList concate(LinkedList secondList){
if(secondList.isEmpty())
return this;
}
By default 'this' returns current instance reference.
Yes as the method and object belongs to same class, you can write:
LinkedList concate(LinkedList secondList){
if(secondList.isEmpty()) {
return (this);
}
}
this holds the reference of current object.
Consider:
class TestParent{
public int i = 100;
public void printName(){
System.err.println(this); //{TestChild#428} according to the Debugger.
System.err.println(this.i); //this.i is 100.
}
}
class TestChild extends TestParent{
public int i = 200;
}
public class ThisTest {
public static void main(String[] args) {
new TestChild().printName();
}
}
I know that similar questions have been asked, but I couldn't get a firm understanding of the 'this' variable in Java.
Let me try to explain how I understand the result of the above image.
Since it's a new TestChild() object that's calling the printName() method, the this variable in line 6 is set to a TestChild object - {TestChild#428} according to the Debugger.
However, since Java doesn't have a virtual field - I'm not completely sure what this means, but I conceptually understand it as being the opposite of Java methods, which support Polymorphism - this.i is set to 100 of TestParent at compile time.
So no matter what this is, this.i in a TestParent method will always be the i variable in the TestParent class.
I'm not sure that my understanding is correct so please correct me if I'm wrong.
And also, my main question is,
How is the this variable set to the current object that's calling the method? How is it actually implemented?
In essence, there is no difference between
this.foo()
and
anyObject.foo()
as both are "implemented" the same way. Keep in mind that "in the end" "object orientation is only an abstraction, and in "reality" what happens is something like:
foo(callingObject)
In other words: whenever you use some object reference to call a method ... in the end there isn't a call on some object. Because deep down in assembler and machine code, something like "a call on something" doesn't exist.
What really happens is a call to a function; and the first (implicit/invisible on the source code level) parameter is that object.
BTW: you can actually write that down in Java like:
class Bar {
void foo(Bar this) { ... }
and later use
new Bar().foo();
And for this.fieldA, in the end: you have a reference to some location in memory; and a table that tells you on which "offset" you will find fieldA.
Edit - just for the record. If you are interested in more details about foo(Bar this) - you can turn to this question; giving the details in the Java spec behind it!
What's happening here is that there are two completely different fields both called i; to use their full names, one is TestParent::i and one is TestChild::i.
Because the method printName is defined in TestParent, when it refers to i, it can only see TestParent::i, which is set to 100.
Whereas when you set i to 200 in TestChild, both fields called i are visible, but because they have the same name, TestChild::i hides TestParent::i, and you end up setting TestChild::i and leaving TestParent::i untouched.
Well when a new object is created that object has an address in memory so you can think of it as if the object had a private member this that is set to the address when the object is created. You can also think of it like this: obj.method(param) is just syntactic sugar for method(obj, param); and this is actually a parameter of method.
To directly address what you see in the output: The call to print 'this.i' is passing as argument to 'print()' the value of the field 'i' in the current scope, which is the scope of the parent class. By contrast, the call to print 'this' is getting translated under the hood to a call to print 'this.getClass().getName()' [roughly speaking], and the 'getClass()' call gets the actual class object, which is for the child class.
Adding some more info on top of #Tom Anderson answer, which explains hiding concept nicely.
I have added one more constructor in Child ( TestChild) which prints values of i in both parent and child.
If you want get value of i from child (TestChild), override the method in TestChild.
class TestParent{
public int i = 100;
public void printName(){
System.err.println("TestParent:printName()");
System.err.println(this); //{TestChild#SOME_NUM} according to the Debugger.
System.err.println(this.i); //this.i is 100.
}
}
class TestChild extends TestParent{
public int i = 200;
public TestChild(){
System.out.println("TestChild.i and TestParent.i:"+this.i+":"+super.i);
}
public void printName(){
//super.printName();
System.err.println("TestChild:printName()");
System.err.println(this); //{TestChild#SOME_NUM} according to the Debugger.
System.err.println(this.i); //this.i is 200.
}
}
public class ThisTest {
public static void main(String[] args) {
TestParent parent = new TestChild();
parent.printName();
}
}
Case 1: If I comment super.printName() call from child, Child version of TestChild.printName() prints the value of i in TestChild
Output:
TestChild.i and TestParent.i:200:100
TestChild:printName()
TestChild#43cda81e
200
Case 2: TestChild.printName() calls super.printName() as the first line in printName() method. In this case, i value from both parent and child are displayed in respective methods.
Output:
TestChild.i and TestParent.i:200:100
TestParent:printName()
TestChild#43cda81e
100
TestChild:printName()
TestChild#43cda81e
200
Sometimes we call className.methodName() without creating object for it, I mean without using syntax as className objectName = new constructor() and then call as object.methodName()
When to use className.methodName()?
When to call method using object as object.methodName()?
Explanation of above two cases with example will be appreciated.
What you're referring to is a static method.
Assume that I have this :
public class A {
public static void foo(){
System.out.println("Hooray! I work!");
}
}
You can now do this anywhere else in any other class :
A.foo();
This is because the method is static, which means that it can be called on by the CLASS.
This means that it doesn't require an instance of that class in order for the method to be called.
However, even though it isn't required, you can still do this :
A a = new A();
a.foo();
But since the method foo() is static, instantiating an object A is not required in order to run the foo() method.
First. When you're create at least one static method of a class, you can use this method without creating an instance of class. This is useful, for example, for the creation of methods with independent logic. For example:
public class Checker {
public static Boolean month(int value) {
return (value >= 1 && value <= 12);
}
}
You need check correct value of month many times. But what to do each time to create the object. It is much effective to use a static method.
Second. When you create the object, the object is stored in the memory and you get a link to it. Then the object can be used for example to save at the list.
Method at this object is specific. You can save class data and do specific operation with member of this class. For example:
List<Animals> animalsList = new ArrayList<>();
Animal animal = new Animal("dog");
int legs = animal.getCountLegs(); // specific function for object
animalList.add(animal); //save if you need
// use list of object
For every class, we have a Object called as class object which is YourClass.class object. static methods are invoked based on meta-data on those objects. For instances of a class, methods are invoked on the actual instances. Both static and non-static methods are present on method area.
There is no different between 1 and 2 point, because in during compilation compiler makes ClassName.staticMethod() instead of instance.staticMethod().
Static methods in java belong to the class (not an instance of it). They use no instance variables and will usually take input from the parameters, perform actions on it, then return some result. Instances methods are associated with objects and, as the name implies, can use instance variables.
I have two classes :
import android.cla;
public class CW {
public static void main(String [] args){
System.out.println(new cla());
}
}
public class Cl {
#Override
public String toString(){
return "LOL";
}
}
In the first class I'm calling the objects toString() method, which has been overriden and printing it to console. It clearly returns "LOL";
I have two questions :
Is it possible to return data while instantiating like this (new cla()) without overriding the objects toString() method; and
What is the proper term for instantiating classes like this (new cla()), that's without declaration like : Object l = new cla()
Thanks. Please correct me on the proper terms.
1 - No it isn't. A 'constructor' is a special method on the class that always returns an object instance of the class. The whole point of the constructor is to return the object. So no, it can't return anything else.
1a - The reason that System.out.println calls the toString method is because you are asking it to print out that object to the screen, and the toString method is the method chosen by the authors of println (and the Java language in general) to give a string representation of the object.
2 - That way of writing isn't really called anything. It's just an expression that you're passing as an 'actual parameter' to the println method. True, it's an expression that instantiates a new object, but it's no different to println("a string"). You could call it an anonymous object if you really wanted to.
2a - (old answer that doesn't actually answer your question but I'll keep it here) That's just called 'using a less derived reference† to a class'. Beware you can only call methods on the type of the reference, so if you added extra methods to your Cl class you couldn't call them from an Object reference. Look into Liskov substitution principle.
† 'less derived' or 'supertype' or 'superclass' or 'more general class' etc...