Lets say you have some random class called Dude, and you have some private instance variables and you have some get methods and a compareTo method to say if one instance of the class has the same variables as another instance of the class and that's pretty much it. Well, lets say in some driver class, you make two Dude objects, and you call them d1 and d2.
Well, now you wanna compare the two and see if they have the same instance data, so you'd call d1.compareTo(d2);
Now, my question is, when creating the compareTo method inside the dude class, you pass it one object as a parameter and the other one.....?
I'm thinking it would go something like this:
public boolean compareTo(Dude d){
if (this.getArbitraryVariable() == d.getArbitraryVariable()) return true
and so on.
But for that to work, you would have no clue what the currently executing object is, and the only logical explaination I can think of is that the "." operator makes whatever is to the left of it, the current executing object in the class. Is that right or no?
That is not quite the correct intuition.
When you write d1.compareTo(d2);, this compiles down to something closer to compareTo(d1,d2).
That is, when you call a method on an object, you basically pass the object as the first parameter implicitly.
When you are inside the method, you use the keyword this to refer to the implicit object that was passed to the method.
The dot operator not only gives you the current executing object , it can also give you the current executing class, which is how you use static methods and static variables.
For ex :-
staticClass.staticMethod();
Also you can use the dot operator for chaining. For ex
String finalValue=input.replaceAll("numbers","alphabets").substring(0,`32).trim();
Related
I am a beginner in Java, I know something of the basics, but sometimes I see lines of codes that I don't really understand why they are written that way, here are some questions that I have:
Question 1:
Methods or attributes that are called with other methods or attributes:
Ex.: System.out.print();
I understand that system is a class, and when you write System.out, you are calling the "out" attribute, but from the "out" attribute, you call the "print()" method, is the print() method within the out attribute? how does this works.
Also sometimes I see method being called that way: ... method1().method2();
If I put a method inside the scope of another method, won't it run automattically?
like:
public void method1(){ method 2};
Question 2:
I've been learning about the Date and Calendar classes, and I saw a video where the guy instantieted objects of Date and Calendar, without using the world "new", neither a construction method:
Date d = Date.from(Instant.parse("2018-06-25T15:42:07Z"));
Calendar cal = Calendar.getInstance();
How does that works? Can I instantiate any object of any class by calling a abstract method (if the class have one)? Or is just that in those methods they are returning a Date and Calendar object?
Question 3:
How can a array of type have a the atributte "length", aren't array just a set of primitive types? how can a primitive type have attributes??
Ex: int[] x = new int[3];
System.out.print(x.length); //Prints 3;
Question 1:
System has a class, and it has a field (often in Java, it's called a field instead of an attribute. They are the same thing though) called out. out is of type PrintStream. You don't have to worry about what a printStream is, but just know that printStream has a method called print. So, you access System's field called out, and you call that fields print method.
You can do stuff like method1().method2() because method1 returns an object, and you call that objects method. For example, let's say you have a class which has a method called print(). Then if you have a method like this:
public A getA() {
return new A();
}
Then if you call that method, you will get an a class. With that a class, you can call it's method and access it's fields.
getA().print();
Question 2
Like in the previous answer, you can get objects from methods. So, you assign your object to the return value of that method. For example, if you have the same method as before:
public A getA() {
return new A();
}
You can do:
A a = getA();
Since it returns an A type, you assign it to your A.
Question 3
Array is actually a special type. It's technically an object, which allows it to have fields like length, however you can still get elements using array[5] for example. I don't think you should worry about arrays, it is very different than regular objects.
I am required to take all user input from within a void method (though it's important to note that the original verbiage says the method must not have a return value), and have all output be relegated to a separate method.
Now, I have all that set up and it's passing the relevant array to the sub method just fine (because I call the sub method from within the void method). But, I need the main to actually do the rest of the calling using the value from that sub method in other methods.
An in depth explanation and teaching would be deeply appreciated.
If you have luxury to change the signature of the methods (keeping the return type as void), you can pass another data structure to the methods. That way, you can get the user inputs inside GetUserInput(customDataStruct) method, pass it to SubMethod(customDataStruct) method. SubMethod() will modify the customDataStruct content, which will be available directly in main(), if main() invokes GetuserInput().
Second option, as #Fiddle suggested, is to use a global variable and let the methods manipulate it. This global variable shall be accessible from main().
I had it flipped. By letting the void method be the sub method and actually learning to pass by reference (enjoy my head smacking) I was able to use the method with the return to bring the value back to main.
Hello I taking Computer Science 1, and working on understanding constructors in java.
There is a question in my book asking:
what is wrong with the following code?
public C7e2()
{
C7e2 r;
r= new C7e2;
}
I know you can write the instance variables as C7e2 r = new C7e2 ();
Once I created a main method this would be a legal program right? Even though it doesn't do anything special.
Any beginner information would be greatly received.
That would create an infinite recursion until the stack overflowed. Consider that the C7e2() constructor is instantiating another C7e2 object, which will call the constructor again, which will instantiate another C7e2, which will call...
The object's constructor handles creation of new instances of that object. If creation of the object requires another instance of itself to be created, that second instance will require a third, etc.
In the constructor of the class you are trying to create an object of this class. The problem is that this is a recursion and when you create a C7e2 object your program won't work. Do not create objects in the constructor of the class.
The example you give is perfectly legal, in the sense that it is syntactically correct Java code and will compile, once you fix the missing parentheses. But it won't execute, as it involves an infinite recursion on C7e2().
Following this tutorial:
http://developer.android.com/training/notepad/notepad-ex2.html
In Step 2, this method gets called:
registerForContextMenu(getListView());
which is a public method of Activity. Now, I'm a bit of a Java newbie here - I thought if you wanted to call an instance method of a superclass you needed to preface it with this. E.g.
this.registerForContextMenu(getListView());
Is it just a style thing here? Is there any difference between
this.registerForContextMenu
and simply
registerForContextMenu
No, there is no difference.
You don't have to use this., but it is often done anyway to make the code clearer.
For one thing, it makes it easy to tell if a method is static or not if you use the convention of calling instance methods like this:
this.registerForContextMenu()
and static methods like this:
ClassName.staticRegisterForContextMenu()
you do not have to use this. If you ommit it it is assumed you called method in this scope. One particular example when this may help could be i.e.:
Boolean someVar;
public function setMe( Boolean someVar ) {
this.someVar = someVar;
}
In this case, w/o this you would get the error.
To call a method of superclass either you need object of superclss or keyword super .
eg.
superObject.superclassMethod();
super.superclassMethod();
this is a reference of the current object. this can be used to call method of a class in which it is used. this can never be used to call a superclass method.
As for
this.registerForContextMenu()
and
registerForContextMenu()
no such difference. you can use either of them.
Both ways are correct for calling a method on the current (this) instance of the class. Non private methods are inherited from super classes, so you can use the same syntax to call such methods.
In a recent question, someone asked about static methods and one of the answers stated that you generally call them with something like:
MyClassName.myStaticMethod();
The comments on that also stated that you could also call it via an object with:
MyClassName myVar;
myVar.myStaticMethod();
but that it was considered bad form.
Now it seems to me that doing this can actually make my life easier so I don't have to worry about what's static or not (a).
Is there some problem with calling static functions via an object? Obviously you wouldn't want to create a brand new object just to call it:
Integer xyzzy;
int plugh = xyzzy.parseInt ("42", 10);
But, if you already have an object of the desired type, is there a problem in using it?
(a) Obviously, I can't call a non-static method with:
MyClassName.myNonStaticMethod();
but that's not the issue I'm asking about here.
In my opinion, the real use case that makes this so unreadable is something like this. What does the code below print?
//in a main method somewhere
Super instance = new Sub();
instance.method();
//...
public class Super {
public static void method() {
System.out.println("Super");
}
}
public class Sub extends Super {
public static void method() {
System.out.println("Sub");
}
}
The answer is that it prints "Super", because static methods are not virtual. Even though instance is-a Sub, the compiler can only go on the type of the variable which is Super. However, by calling the method via instance rather than Super, you are subtly implying that it will be virtual.
In fact, a developer reading the instance.method() would have to look at the declaration of the method (its signature) to know which method it actually being called. You mention
it seems to me that doing this can actually make my life easier so I don't have to worry about what's static or not
But in the case above context is actually very important!
I can fairly confidently say it was a mistake for the language designers to allow this in the first place. Stay away.
The bad form comment comes from the Coding Conventions for Java
See http://www.oracle.com/technetwork/java/codeconventions-137265.html#587
The reason for it, if you think about it, is that the method, being static, does not belong to any particular object. Because it belongs to the class, why would you want to elevate a particular object to such a special status that it appears to own a method?
In your particular example, you can use an existing integer through which to call parseInt (that is, it is legal in Java) but that puts the reader's focus on that particular integer object. It can be confusing to readers, and therefore the guidance is to avoid this style.
Regarding this making life easier for you the programmer, turn it around and ask what makes life easier on the reader? There are two kinds of methods: instance and static. When you see a the expression C.m and you know C is a class, you know m must be a static method. When you see x.m (where x is an instance) you can't tell, but it looks like an instance method and so most everyone reserves this syntax for instance methods only.
It's a matter of communication. Calling a method on an instance implies you're acting on/with that particular instance, not on/with the instance's class.
It might get super confusing when you have an object that inherits from another object, overriding its static method. Especially if you're referring to the object as a type of its ancestor class. It wouldn't be obvious as to which method you're running.