Declaring a method of class type? - java

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'.

Related

Using instanceof to seperate classes in an ArrayList

apologies if this is simple or has been answered before, I'm new to Java and in my research I can't find too much on this issue and have not yet found a solution.
I have an ArrayList with multiple classes that all share a common Interface, in this example the interface is called "Packable". I'm trying to create a method that takes a class parameter and sweeps through each element of this ArrayList, returning a new list containing all the items in the original list that are of the same class as the reference parameter.
This is my code so far, trying the instanceof method:
public List<Packable> getOfType(Packable reference){
List<Packable> typeOfItems = new ArrayList<>();
for (Packable item: itemsStored) {
if (item instanceof reference){
typeOfItems.add(item);
}
}
return typeOfItems;
}
This is throwing an error as it doesn't yet recognise reference as a class. This question mentions a method isAssignableFrom with the answer stating: "When using instanceof, you need to know the class of B at compile time. When using isAssignableFrom() it can be dynamic and change during runtime." (Thanks Marc Novakowski)
I understand that given the parameter the class isn't known at compilation and as such I've tried implementing isAssignableFrom and can't really seem to get it to work. The IDE doesn't really recognise or suggest it, and there isn't too much about the method online. I've tried implementing it the way the JavaDocs suggest but this isn't working either:
if (reference.isAssignableFrom(item.getClass())){
typeOfItems.add(item);
}
Any help or advice on methods to look into would be greatly appreciated. Thanks for reading the question, and again apologies if this is simple or has been answered elsewhere and I've just missed it. Thanks everyone
I'm not sure what Packable is, but you appear to be confused about a few concepts here.
In java, Packable reference does not represent the Packable concept. It represents a specific instance of Packable (or null).
In other words, given Dog dog, that means dog is some specific dog. Not 'the general concept of a dog'. We know that the specific animal that dog is referring to is, at least, a Dog. It could be Fifi, the neighbour's schnauzer.
instanceof, on the other hand, is about the general concept of things: if (fifi instanceof Dog) is how you're supposed to use it. You're more or less attempting to do the equivalent of if (fifi instanceof rover) which just doesn't make sense. How can one dog be 'an instance' of another? It's not that the answer is 'true' or 'false', but that the very question doesn't even make sense, which is why javac doesn't compile it. It has no idea what this even means.
Java, being java, makes objects of many things. Notably including the very notion of things. Thus, there is the class java.lang.Class, instances of which represent classes. A bit of alice-going-down-the-rabbit-hole thing is happening here: Classes as a concept are also represented as instances of the java.lang.Class class.
A class OBJECT (so, an instance of java.lang.Class) has the .isAssignableFrom method. This in fact takes another j.l.CLass as argument, it's for checking if one type is a subtype of another. In that sense, the question linked is needlessly confusing - you're really looking for the instanceOf method (there is an instanceof language construct, but the j.l.Class class has an isInstance method, which is unrelated, other than that they roughly accomplish the same goal: Check if some INSTANCE is of a type that is equal to, or a subtype of, some TYPE.
This is an example of how to use it:
Class<?> c = Number.class;
Object o = Integer.valueOf(5);
System.out.println(c.isInstance(o));
this is more or less equivalent to:
Object o = Integer.valueOf(5);
System.out.println(o instanceof Number);
Except now the Number part no longer needs to be written at 'write the code' time, you can supply it, say, read it from a parameter. You'd have to, of course, dynamically construct the Class instance. You can do so either by string-lookup, or by getting the actual type of an actual object. For example:
String input = scanner.next(); // user types in "java.lang.Number"
Class<?> c = Class.forName(input);
Object o = Integer.valueOf(5);
System.out.println(c.isInstance(o));
Or:
Object i = Integer.valueOf(5);
Object d = Double.valueOf(10);
Class<?> c = i.getClass(); // will be java.lang.Integer.class
System.out.println(c.isInstance(d)); // false
But doing this latter bit is really dangerous. Often i.getClass() returns some hidden impl detail subtype (java is hierarchical and object oriented, anywhere, say, an ArrayList is needed, someone is free to make a new class: class MyVariantOfArrayList extends ArrayList, and use that - now you write ArrayList foo = getList(), but foo.getClass() doesn't return ArrayList - no, you invoke that method on the object the foo variable points at, so, it'd be MyVariantOfArrayList.class, not ArrayList.class.
It's possible Packable itself represents a type. But then it either needs to also have isInstance and isAssignableFrom and such (and you need to start questioning why you're badly reinventing the wheel here - java.lang.Class already exists!), or it needs a .getRepresentedClass() method. You can't call it .getClass(), as the JVM has already given all objects that method, and it would return Packable.class itself.

Classnames as a return type to a method?

Now I've been studying Java for some time now but there's a concept I'm struggling to wrap my head around. I'm used to methods like these
public int something () {
}
I know the above method will return an Integer or a String whatever data type you want. I've recently encountered a method like these
public customclassname methodname(){
}
now I was asking myself what on earth is the return type of the above method. How do I use the returned thing to do something else?
I also saw people passing objects to methods as parameters like this
public something methodname(Customclass customclass){
}
What's the deal with that too? In what scenario is the above "style" necessitated and what are the pitfalls to avoid?
Using objects instead of values like integers or whatnot is confusing me.
I know the above method will return an Integer or a String whatever data type you want.
Yes, that's correct. Now add to that the fact that classes are data types and this should become more clear. A Customclass that you define is still a data type that can be the return type of a method, or the type of a value passed in as a method parameter.
For "pitfalls to avoid" you should probably read up on Is Java "pass-by-reference" or "pass-by-value"?

why getClass() from superclass variable returns subclass class name? [duplicate]

This question already has answers here:
Dynamic dispatch and binding
(2 answers)
Closed 2 years ago.
Im confused, when i use getClass( ) from a superclass reference variable that's pointing to a subclass object, the result is the subclass.
Heres a simple example:
public `class` TestGetClass
{
public static void main(String[] args)
{
Object obj = new Integer(20);
System.out.println("obj class: " + obj.getClass());
}
}
The output gives me the Integer class instead of the Object class.
obj class: class java.lang.Integer
Can someone explain please
What you're looking for is simply:
Object.class.
obj.getClass() in java could plausibly be interpreted in two different ways:
It means: Take the expression 'obj', which is a reference (i.e., a pointer). Follow the pointer and find the object it is pointing at. Ask that object what its type is.
just like 1, except, because the variable type was Object, invoke the implementation of the getClass() method from the java.lang.Object class. i.e., no dynamic dispatch.
It means: Take the locally declared variable named obj. What type did I declare it as, right here in this method? Don't care about the object/pointer at all, just the declaration.
Now, the java lang spec is crystal clear: In java, #1 is what happens. #2 is not available (you can't opt out of dynamic dispatch. As a matter of obvious language design, private methods don't do it because they don't need it, and static methods don't do it because, by being static, they just aren't a part of the hierarchy in the first place - so those seeming exceptions really don't apply. There is no other way to opt out).
Here's the thing about option #2 though: is completely pointless.
In java, you can't have mystery meat variables. Somebody declares them, and the type is written right there in the source file. There is no such thing as 'eh, figure it all out at runtime'. Even java10's var doesn't work that way (it's still locked in, for sure, at compile time).
So, you already know. It is object, what point is there to repeat it?
If you want a java.lang.Class<?> instance that represents Object, there's syntax for this. it is:
Class<?> objClass = Object.class;

How to define a "good" get() method for a private variable in a class? [duplicate]

This question already has answers here:
Why make defensive copies in getters inside immutable classes?
(7 answers)
Is Java "pass-by-reference" or "pass-by-value"?
(93 answers)
Closed 3 years ago.
I'm learning Java and I have some doubts.
If defined a class with a private variable like
class test<A>{
private A var;
...
public A get(){
return var;
}
}
Is the get method wrong?
I think so because with this definition I can modify the variable "var" like
test<A> x = new test<A>();
A temp = x.get();
temp.set(*something*);
At the end x is changed (I tested it using Vector as A). If I understand correctly, this works because object reference (I miss C pointers, sob). Am I wrong? Maybe I don't understand the purpose of the keyword "private"! Thanks in advance!
Edit: I have no problems with "pass-by-reference" and "pass-by-value". I have doubts defining get() method for a private variable in a class (you don't say?). Please stop linking Is Java "pass-by-reference" or "pass-by-value"?
If your getter method is returning a reference to a mutable object, then this greatly weakens the quality of the encapsulation provided by your class, because it becomes possible to modify the state of an instance of your class without calling a method of the class.
One standard strategy to guard against this problem is what J. Bloch calls defensive copies (Effective Java, 3rd edition, Item 50: "Make defensive copies when needed").
This would mean creating a copy of var in the getter method, and returning that copy instead. How to do this depends on the design of A.
Because A is a type parameter, making a copy of the instance requires additional support in the design. To see how to achieve this using Java's cloning mechanism, see my answer to the post "Does it make sense to create a Copyable type interface instead of using Cloneable?".
If this is a problem, you can create a façade to protect your variable
public class Facade extends A {
A myObj;
public Facade (A obj) {
myObj =
}
public A get(){
return myObj.get();
}
public B set(Object val) {
throw new RuntimeException("Setting is not allowed");
}
}
This might be a bit too much detail for just starting, but you might review class java.util.concurrent.atomic.AtomicReference<V>, which is very similar to your example.
Generally speaking, placing instance variables in private variables, while providing access to the variable using a getter and a setter, is standard practice.
Note that your class name should be capitalized, type parameter 'V' is more standard, and the variable name would more usually be 'value'. Also, try to pick a more communicative name for the class. (Type parameter type variable could be 'ValueType', which would fit some preferences. But, single character type variable names are more usual.)
public class Wrapper<V> {
private V value;
public V get() {
return value;
}
public void set(V value) {
this.value = value;
}
}
I'd add some other point here: as others have said, you hand out the object reference and it can be modified, which could be bad.
Object orientation is about keeping the data and the code that works on it in one place. If you need getters, think what the callers of the getters need to do, and whether that action should rather be a method on the class that has the data. Your code could suffer from the Feature Envy code smell, as it violates the Tell, Don't Ask principle.
To fix this, remove the getter, and introduce new methods as needed. For example, if you have some data object that needs to get printed, you could pass the Printer to the object and have it print itself to the given Printer.
If you're dealing with a collection class (just a guess from your template parameter), you may need to keep the getter, but then you're probably not concerned with the caller changing the value anyway.

Why method is not called according to data type , if the value needs to be stored in a variable

The following java code will not execute.
class A{
int sqrt(int a)
{
}
float sqrt(int a)
{
}
int a1 = sqrt(a);
float b1= sqrt(b);
}
In interview i was asked by a question that why java compiler does not check the data type and call that method accordingly. What is the reason?
Those methods have the same signature (identifier + parameter list), which is illegal.
The reason the compiler won't allow this is that it is not always possible to infer the desired data type. For example, Java supports "boxing" of native values into objects, so you should be able to do this:
ArrayList<Object> list = new ArrayList<Object>();
list.add(a.sqrt(4));
In code like this, it would be literally impossible for the compiler to figure out whether you wanted to call the method that returns a float or the method that returns an int.
If you have 2 methods with same name and same parameters of same data types then java compiler will not even let you compile the code. It should say that method "sqrt" is already defined. So it's illegal in java.
I asked when i was a beginner in programming. . Let me give the answer myself. It always checks the return type of method and call that method accordingly . In case of
int a1 = sqrt(a);
it will call method whose return type is integer.

Categories