Using methods from other classes - java

The difference between (a) import somePackage.someClass; and (b)someClass object = new someClass(); is that (a) will allow call the methods from the imported class without creating new instances of it, while (b) will create an object using the template class and therefore the methods for the class someClass will belong to the object object. So if I want to use a method someMethod() from someClass in (b) I'd call it through the object object. Is it how it works?

Yes you can use static methods from a class directly
Yes you can use methods from a class by creating an object
But more important thing than just the above options available is when to use which. First type of call is to class methods whereas the second class is to instance methods.
Instance Methods vs Class Methods: Each class represents a set of attributes and behaviour. Instance methods usually represent the behaviour. example if Person is a class and Robb is an object, then robb.weight can be attribute, robb.write() would be an instance method and Person.type() (ans: species) or Person.population (ans: total number of instances) can be class methods.
Also you represent instance methods in textual writing as ClassName#instanceMethod and ClassName.classMethods

No, you are wrong
Simplistically if the class that you want to use is not in the same package then you need to import it, or fully path the class e.g. java.util.ArrayList.
If the methods are not static, then you will need to create a new Instance of the class you want to use.

You can use methods from other class directly only if it is a static method. You will also have to add static in your import statement if you want to use the method name directly without prefixing it will the class name.
For non-static methods you have to create instance of the class and then call that method.

Related

is it possible for an interface to have an already instanced object as an attribute?

I am creating an interface with many implementing classes and there is an attribute they must all have;
I guess it's better to put that attribute in their interface than writing many constructor lines, but attributes can only be static final and require to be immediately initialized.
public interface Interface{
static final AttrType attribute = new AttrType( *something* );
I have 2 problems: this attribute is a class and its constructor needs some other type parameters not just ints, and also it shouldn't be initialized here, I need all implementing classes of the interface to work on the same instance of AttrType which as i said I won't instantiate in the interface.
So, as I am not expert enough, is there a way to do this in the interface or I should just write a line in every subclass' constructor to put in the one AttrType instance they need?
Java interfaces describe what a class can do, rather than what a class is. Therefore, an interface only describes methods.
You could handle this in a few ways:
Using an interface, you could have a getter for the variable, which would force the implementing classes to have the variable. Something like "public AttrType getAttribute();"
Or you could create a class, probably abstract, which implements the interface and has the variable, and its getter and setter. The subclasses all would inherit this variable and behavior.
Would it be possible to add also a common base class to go with your common interface which all the classes could inherit? Then the common base class constructor could contain the attribute instance. Also you could consider using an abstract class instead of interface.

Java - Why is it necesary to use Class class's instance methods write classname.class.method or instance.getClass().method?

Why is it necesary to use Class class's methods to write classname.class.method or instance.getClass().method?
For example:
public class SomeClass{
public static void main (String[] args){
SomeClass sm = new SomeClass();
//The correct ways:
System.out.println(sm.getClass().getName());
//or
System.out.println(SomeClass.class.getName());
}
}
Class class's instance methods need a class (it can be seen when in System.out.println(sm.getClass().getName(); because sm.getClass() returns a class) so why is not correct to write System.out.println(SomeClass.getName(); and it is necessary to write "class" in the middle if getName() method is called by a class? Is it because SomeClass class is not considered an instance of Class class? Why sm.getClass() is considered an instance of Class class then?
Thank you.
new SomeClass() creates an instance of the SomeClass class :
SomeClass someClass = new SomeClass();
It doesn't provide the Class instance of SomeClass as the getClass() instance method of Object class does :
Class<? extends SomeClass> clazz = new SomeClass().getClass();
These are two totally different things.
Why is it necesary to use Class class's methods to write classname.class.method or instance.getClass().method?
Java has no free-standing functions, so in order to invoke any function, you have to invoke it as a member of a class. And if you want to invoke a function that belongs to class A, you have to invoke it as a method of class A. I know this is a tautology; but this is what your question, as stated, calls for.
why is not correct to write System.out.println(SomeClass().getName();
It is not correct to write that, because it is not valid java syntax. Java reserves the class-name-followed-by-parentheses construct to stand for identifying constructors. (And it must be prefixed by new.)
it is necessary to write "class" in the middle if getName() method is called by a class?
Besides not supporting free-standing functions, java does not support any free-standing code whatsoever, so in order to call anything, the calling code must be in a class, so all methods are called by a class.
Is it because SomeClass class is not considered an instance of Class class?
Uhm, yes.
Why sm.getClass() is considered an instance of Class class then?
It is not considered an instance of a class. But it does return an instance of a class.
I am breaking the line to understand the easy way.Hope so it will be helpful
SomeClass sm = new SomeClass();
Class clazz1 = sm.getClass(); //sm.getClass() returns Class object
System.out.println(clazz1.getName());
Class clazz2 = SomeClass.class; //SomeClass.class returns Class object
System.out.println(clazz2.getName());
That means getName() method is available in Class class .

Can we add the more methods in Object class of java?

We all know that Object class is the super class in Java. Can we add methods into the Object class?
And, if we make a new class with the name Object then will the functionality of that class affect the super class Object?
Can we add methods into the Object class?
No. You can subclass it, but you cannot modify it (without modifying the JDK's and JRE's runtime jars; which is a Bad Idea™).
And, if we make a new class with the name Object then will the functionality of that class affect the super class Object?
No, they'll be separate classes. Of course, calling a class Object would be confusing and surprising to people reading the code.

What is constructor in java, if it is not a member of class?

What do we we call a constructor, if it is not a member of a class as stated in Oracle doc: http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html
I think the term "member" was defined to exclude constructors for the sake of convenience. Constructors, even public ones, are not inherited; members are inherited (unless they are static and/or private). It would be awkward when talking about the rules of inheritance to always have to say "members except constructors".
From the Java Language Specification, §8.2:
Constructors, static initializers, and instance initializers are not members and therefore are not inherited.
Just call constructors "constructors".
Its a special method that every class has, which is called after creation of the object. in JVM its called using invokespecial so, lets just call it a special method?
And since there is just 1 special method in Java - they all call it "constructor"
All the doc is saying is that the constructor is not inherited by default. Since the constructor is a method that is invoked on the construction of the object in the memory heap, then once you create a subclass that inherits from a super class, the constructor of the super class is not invoked by default.
For instance if you have a class Vehicle and a subclass Car, assume the Vehicle constructor is as follows:
public Vehicle(String vehName) {
this.vehName = vehName;
}
Then, even though your class Car inherits from class Vehicle, the vehName member (field) will not be set as the constructor above does.
So you will need to do something like this:
public Car(String vehName) {
super(vehName);
}
Hope that helps
In Java, a class body (the area between braces) can contain the following key items: (1) Fields (2) Methods (3) Other Classes (nested classes) (4) Constructors (5) Initializers
An object created from a particular class shall take the shape that is similar to the blueprint (class) from which it's created. Now, if you look at items that can be contained in a class body, only item (1) to (3) help in determining what sort of object can be created from a particular class definition.
Constructors and initializers only play part in actual creation of the object (e.g. initialization of already defined fields), but do not determine what shape/state that object shall carry, and what behaviors it will display.
For this reason, to me, it make sense to call item (1) to (3) class members (i.e. class members are those items within a class body that determine how an object created from the class looks like and behave); whereas constructors and initializers are not members because their absence in a class definition does not affect a class state and behavior.
As such, only class members can be inherited as the whole point behind inheritance is to enable a subclass reuse state and behavior of its superclass.
A Constructor is a method which is in a class which is used to create a new instance of that class.
Being a member of a class just means that the item in question is in the class.
Constructor is a method which name is same as the class. It is used to initialize the object of class. It's implicit in action. Parametric constructor initialize object with different value.

How to get instance of main class android?

I have one class which is calling other classes, this class is my main. Is it possible to get somehow instance of this main class, that in others classes i could call main class methods ?
If yes so how this should be done in android with java?
Thanks.
If you are creating the other classes in your main class, one approach would be to pass the current instance of your main class (i.e. `this') as a parameter to the constructors of the other classes, and have them store that reference for future use.
Alternately, you could simply pass the current instance of your main class as a parameter to the method you are calling, that needs to be able to call back.
Use Singleton design pattern to achieve this.
Or if you want, you may use Static methods analogy for reusing the methods too.
For example:
public class Helper{
public static void doSomething(){
//do something here
}
}
Now in your other classes, use the above method as below:
Helper.doSomething();

Categories