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.
Related
I am trying to use mockito to mock a method. However the class I am injecting mocks with calls the method twice while sending in two different objects of the same type, but depending the values in the object determine the output of the method.
So, for example, If I am trying to mock
public ArrayList<example> attemptToMock(testObject testing)
Lets sat type testObject has a string value in it.
So if the string value in testObject is "OK" then attemptToMock should output an array of two objects in it. If testObject string value is "NO" then the Array list sent out only has one Object.
How to I write a test to handle a call so that a class can call attemptToMock twice, within the same method, and I can mock out its output it so depending on the values within testObject. I can mock it to send out different arrays.
A few options:
Override equals and hashCode on your object (TestObject). This is only feasible if all of the values on your object are predictable, and may be more work than other solutions, but if you need to write equals and hashCode anyway (for Map and Set behavior, for example) this is a reasonable solution.
// Mockito compares with objects' equals(Object) methods by default.
when(collaborator.attemptToMock(object1)).thenReturn(array1);
when(collaborator.attemptToMock(object2)).thenReturn(array2);
Write a Hamcrest matcher and use that to match the arrays. This acts as a compact analogue to equals for a specific case, and is especially handy if you need to change behavior based on the same value in many tests.
public class IsATestObjectWithValue extends TypeSafeMatcher<TestObject> {
private final String expectedValue;
public IsATestObjectWithValue(String expectedValue) {
super(TestObject.class);
this.expectedValue = expectedValue;
}
#Override public void matchesSafely(TestObject object) {
// object will never be null, but object.value might.
return expectedValue.equals(object.value);
}
}
Now you can write an equivalent match as above:
when(collaborator.attemptToMock(argThat(new IsATestObjectWithValue("OK")))
.thenReturn(array1);
when(collaborator.attemptToMock(argThat(new IsATestObjectWithValue("NO")))
.thenReturn(array2);
Use an Answer, as wdf described. Anonymous inner Answers are common and pretty concise, and you get access to all of the arguments. This is especially good for one-off solutions, or if you want to explicitly and immediately fail the test if an invalid value (testObject.value) is passed in.
As a last resort, if the order of the calls is predictable, you can return multiple values in sequence.
when(collaborator.attemptToMock(any(TestObject.class)))
.thenReturn(array1).thenReturn(array2);
when(collaborator.attemptToMock(any(TestObject.class)))
.thenReturn(array1, array2); // equivalent
Either of the above lines will return array1 for the first call and array2 for the second call and all calls after it, regardless of the parameter. This solution will be much more brittle than your original question asks for--it'll fail if the call order changes, or if either of the calls is edited out or repeated--but is sometimes the most compact solution if the test is very temporary or if the order is absolutely fixed.
You can access the parameters passed into a mocked method invocation and vary the return value accordingly by using the Answer interface. See the answer to this question, and the docs for Answer.
Basically, the only weird/non-obvious thing going on here is that you have to downcast the parameters to the type you are expecting. So, in your case, if you are mocking a method that takes a single 'TestObject' parameter, then you'll have to do something like this inside of your 'answer' implementation:
Object[] args = invocation.getArguments();
TestObject testObj = (TestObject) args[0];
if ("OK".equals(testObj.value)) {
return new ArrayList(value1, value2);
} else if ("NO".equals(testObj.value)) {
return new ArrayList(singleObject);
}
What difference does it makes?
Let's think we have a method in java as following:
void demoMethod(MyClass mc){
// some operations
}
First type:
demoMethod(new MyClass()); // directly passing an object
Second type:
MyClass mc = new MyClass();
demoMethod(mc); // passing reference of an object
No difference in terms of the method's behavior on that reference. The first code can semantically translate to the second one. Eventually, the object created using new MyClass() needs to be stored somewhere so that it can be re-loaded and passed to the method.
However, using the second code you can re-use the reference.
It doesn't make any difference for demoMethod. Actually in both cases you are passing reference only.
However if you want to use the information after demoMethod does some operation in the calling method, you can't do that in first type.
Assume your demoMethod sets a property of your MyClass object to true or false, you don't have any way to find out what it's value is set to.
So, you can do something like
demoMethod(mc);
if(mc.isMyProperty()==true)
System.out.println("mc is changed");
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();
I'd define myself as a beginner in Java, had it for just one semester and before that I had very little experience with programming whatsoever, virtually none with OOP.
Anyway, I'm going through a code and I found a method declared as a class type
public Polica stavi (Predmet p, int i)
throws GPolIndeks, GPolZauzeto, GPolTezina{
if(i<0 || i>=niz.length) throw new GPolIndeks (i);
if(niz[i] != null) throw new GPolZauzeto (i);
if(q + p.Q() > maxQ) throw new GPolTezina (p);
niz[i] = p;
q += p.Q();
return this;
}
Now the code is rather simple and almost I'm not stranger to it, except for the part where a method called "stavi" is declared. I've been thought there are two types of methods, those who return a value and those who don't, and this one does, but it is not declared as an any type regularly used (int, double, long...), it is declared with a class name, which in this case would be "Polica". This is the first time I'm coming to something like this and it works in a compiler, so my question would be, where can I read up on methods more in more detail, to better understand how this works.
Ok, I will explain some points for you. And its all about OOP
Polica is a class which will became an Object as soon as you create an instance of it
Polica polica = new Polica();
and methods can return any type of variables and also Objects
which means in your function you're expecting to return an Object Polica
public Polica stavi(){
Polica polica = new Polica();
return polica;
}
and this represents its self instance of its own so it would be really same with this
public Polica stavi(){
Polica polica = new Polica();
return this;
}
Well its nice that you have a great curiosity! here's a good tutorial for you.
http://docs.oracle.com/javase/tutorial/java/concepts/index.html
http://docs.oracle.com/javase/tutorial/java/javaOO/objects.html
Goodluck!
I would start with the Java Tutorials for Methods
In this example, the method is returning a reference to an object which in this case is the object you just invoked a method on. This is used for chaining and a class where is often using is StringBuilder eg.
String text = new StringBuilder().append("Hello, the time is ")
.append(new Date()).append("\n).toString();
As you can see, this works because each append method return this of the original StringBuilder.
In java or any other oops language the return type of a method can be any object type i.e it is not restricted to be of primitive type ( int, double...)
You should read this (language specification) for more details.
here you can find what you need. and answering to your question this method returns an object of type Polica.
Take a look at the documentation here
The return type does not have to be a int, long or double etc. It can be of an object you define yourself.
it is not declared as an any type regularly used (int, double, long...), it is declared with a class name
There is no difference between int, double, long, etc. (which are called primitives) and classes when you return them. They return the same way, and a different type is returned.
public Potato weirdMethod(Elephant e) {
System.out.println(e);
return new Potato();
}
That would work fine if you defined the classes "Potato" and "Elephant."
(Edit: as Chris McCabe clarified in the comments, when you return an object it is pass-by-reference, so you can change it and it will change the actual object you returned. Primitives are pass-by-value so if you get a primitive from a method and change it, the original will be unaffected.)
In this case, looks like you want to be using a constructor. http://docs.oracle.com/javase/tutorial/java/javaOO/constructors.html
The official java tutorials are a great place to start with more-ever I would recommend books like Head First Java which are really good for java beginners and will help you get a grip on java fundamentals.
Being Specific to your question java methods can return either primitives like int,float etc.,inbuilt Class object instances like Integer , or custom classes that you create in your java application like "Polica " which you have mentioned above.
Also note that within an instance method or a constructor, this is a reference to the current object — the object whose method or constructor is being called. You can refer to any member of the current object from within an instance method or a constructor by using 'this'.So in your case when your method returns 'this' and method signature says it returns 'Polica' that means that the method "stavi" is part of the Class 'Polica'and is refering to the current instance of 'Polica'.
im trying to do some reflection on a applet.
things i found are some arrays of ints, strings, objects etc.
for example, if there was a field with an object[] and object[0].toString() = [I#7593c366
then i know its an integer array. but what if it says aa#98324ca33 is it's class then aa?
im using a classloader, so my first guess when i see this i need to load the aa class (part before the #, and use the object in it. but im not sure the part befor the # is the class. can somebody say me this is right? or got other ideas?
thnx!
You shouldn't use toString() for this - for one thing, it can have been overridden. As a straightforward example:
Object x = "aa#98324ca33";
String bogusClassName = x.toString();
You would clearly be wrong to think that x refers to an object of type aa here - it refers to a string.
You can find out the class of any object just by calling getClass() on it:
Object x = new SomeType();
Class<?> clazz = x.getClass();
It's not really clear what you're trying to do or where you're getting information from in the first place, but you definitely shouldn't be using toString to determine the class involved.
Yes, the part before # is the class fqn, but you should not rely on that. Object can override toString() and then your logic will fail.
Use obj.getClass() instead.
Take a look at the class java.lang.Class. Just call getClass on an object to retrieve its class instead of using the toString method
Object anObject = ... ;
Class<?> clazz = anObject.getClass();
If you want to check whether it is an array, you can use to Class#isArray() method
clazz.isArray()
The other way around is also possible. If you have a Class instance, you can determine whether an object belongs to this class by using the Class#isInstance( Object ) method
clazz.isInstance( anObject );