class a keyword or a Class? - java

When we create a class Class_Name, we code:
class Class_Name
{
}
Is the word class a keyword or it is a Class?

The word class is a keyword. It can be used to denote a class or to get a class object such as String.class.
This may be somewhat confusing as there is a class called Class. It's an object that represents a class itself.
For example,
Class<?> strClazz=String.class;
has the Class as a type and class as a keyword.
On an unrelated note, the Java documentation calls Class objects clazz to avoid conflict with keywords. Also, Class is technically a generic in that Foo.class will return a Class<Foo>, allowing for the lack of covariance to restrict class objects in parameters.

Yes class is a keyword to tell the java compiler that you are writing this piece of code as a class. YourClass.methodname is used to call methods of a class in a static way.
When we should call a function using its Class name in Java?
You should do this when you want to call a static method of a class.

Related

How to achieve functionality akin to an "abstract static" field

I've created an abstract class contains a method with an implementation. This method is called by subclasses to populate a list, which should be shared amongst all instances of each individual subclass (like an abstract static field which is different and static to each subclass). The issue is: abstract static fields do not exist, so how else might I be able to achieve this behaviour?
For context, the implemented method on the abstract class is for resolving classes from an unqualified name via the reflections8 package. This method calls an abstract method to get the packages to reflect, which just returns a String[] (as subclasses will want to search in different packages). This method then generates a Map<String, Class<?>> containing a mapping of the name of each reflected class to the Class, which is what I would like to share between instances of each specific subclass type (so that it doesn't have to reflect for the same subclass more than once). Ultimately, this method is called by the subclass in order to instantiate a class from its unqualified name.
Please forgive me if this is a rather strange way of doing things; I come from the land of iOS where we don't have package names attached to class names (so I can just call NSClassFromString("ClassName") and that's it).
EDIT: Check out this gist for the current implementation (and check out the comment for a usage example).
My thoughts: if you're wanting your subclasses to have their own respective static fields, it's best to just have those static fields declared in them rather than this abstract class.
From what I understand, your abstract class is really just a placeholder for this one implemented method. Do any of your subclasses override anything from the parent? If not, maybe it doesn't need to be an abstract class.
Plus, does your abstract class need any state? Because if not, you might be better off with this: change your abstract class to be a static class, and your implemented method be a static method, which accepts an "ClassName" argument. Then in your subclasses you can just directly call the method with your subclass' static fields using something akin to MyStaticClass. NSClassFromString(subclassStaticField);
There is no equivalent for abstract static for fields:
An instance field cannot be abstract. It really makes no sense. abstract means we are deferring some of the details to a subclass. But for an instance field there is nothing that it makes sense to defer.
A static field is not inherited anyway, so there is no way one could be used polymorphically. static fields with the same name in different classes are distinct variables.
You can (of course) use reflection to test if a field (static or instance) has been declared ... but that's not what abstract means in Java.
Solution:
If you want an instance field to exist in all of the subclasses of an abstract class, declare it as a regular field in the abstract class.
If you want a static field to exist in all subclasses, you have no choice but to explicitly declare it in each subclass. You won't be able to use it / them polymorphically.

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 .

Is it possible to declare anonymous class as abstract?

I am trying to find out, if it is possible to create anonymous inner class as abstract. I thought, that it doesn't make sense because I am trying to create instance of the abstract class, but the message from compiler confused me:
Class 'Anonymous class derived from Test' must either be declared abstract or implement abstract method 'method()' in Test
Code:
abstract class Test{
abstract void method();
}
Test o = new Test(){};
If it is possible to declare anonymous class as abstract, please let me know how to do that.
I would be greatful for answer.
See JLS Sec 15.9.5 (emphasis mine):
15.9.5. Anonymous Class Declarations
An anonymous class declaration is automatically derived from a class instance creation expression by the Java compiler.
An anonymous class is never abstract (§8.1.1.1).
An anonymous class is always implicitly final (§8.1.1.2).
An anonymous class is always an inner class (§8.1.3); it is never static (§8.1.1, §8.5.1).
you can't and does not make sense to declare anonymous class as abstract class as anonymous are used as local class only once.
i think you are getting this error because of similar issue Class must either be declared abstract or implement abstract method error
As quoted by Andy Turner the answer to your question is NO.
However I think you wanted to know something different.
Why do you get this compiler message?
Well the compiler is a bit misleading here. It offers two possible solutions based on that you are declaring a class (that anonymous class) and then also want to create an instance of that class:
make the derived class (which an anonymous class always is) abstract,
this is fine for normal and inner classes but it is not possible for anonymous classes, so the compiler should not suggest it in the first place
implement all methods and have no abstract methods in your anonymous class declaration
So to solve your actual problem: simply implement method() so your anonymous class declaration contains no more abstract methods
abstract class Test{
abstract void method();
}
Test o = new Test()
{
void method()
{
// do something
};
};
Now everything is declared and the compiler should not complain any more.

Using methods from other classes

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.

What is the difference between the class "Class" in the Java API and the "class" keyword?

What is the difference between the Java class Class (which extends Object) and the class keyword (the word that is used to create a class)?
In programming, reflection is the ability of a program to modify its own structure and behavior at runtime through analysis of runtime details, such as the actual implementing class of an object instance. The Class class is a part of the Java API for the purposes of reflection. Whereas the class keyword is a structure of the Java language marking the definition of a new class, the Class class is used to type variables and parameters as classes themselves. It's a way for the program to use class definitions themselves as objects to program around (you can programmatically enumerate over the class' public methods, for example).
Additionally, any instance o of type Object (that is, any object in Java at all) inherits the getClass instance method. This yields the actual runtime class of the object, irrespective of the compile-time code-stated class of the variable the object is stored in. For example, for some defined class X:
Object o = new X();
Class<?> type = o.getClass();
type will now be a reference to the X class itself, which matches the Class<?> generic description because the X class is in fact an instance of type Class<X>.
Every defined class also has one static variable called class referring back to the class itself. Calling getClass on an instance of class X will return the same Class<X> instance as that class' class static variable:
("some string").getClass() == String.class
It is worth noting that the primitive types all have a static class variable as well even though they are not Objects. It is also worth noting that a primitive type's class is not the same as the class of its wrapper class:
int.class != Integer.class
Class is a Java class just like Object and String are classes.
On the other hand, if we say:
Class<?> c = String.class;
What we get in return is a Class object of type String:
Class<String>
In short, both are essentially the same, but you can keep a reference of a String.class object using the Class class.
They're used for Java reflection which you can learn more about here: http://docs.oracle.com/javase/tutorial/reflect/
Class is a "Java class" that provide methods to manipulate "Java class" while class is a Java keyword used to declare a "Java class"
Class is a Java class type (that extends the Object class, as you said), "an extensible program-code-template for creating objects, providing initial values for state (member variables) and implementations of behavior (member functions, methods)." - Wikipedia
On the other hand, class, is a keyword, i.e. a reserved word by the language compiler (or interpreter, in other cases) that can not be used as an identifier or any other use. This specific keyword is used to declare custom class types.
Class objects are Objects of special types.. of class java.lang.Class used to represent class definiton.
class keyword is a keyword used to represent classes where you can put methods and variables.The most important thing to do with a Class Object is to perform Reflection API,it can be used to dynamically create objects,invoke methods and introspect them.You can also load multiple versions of a classes using java.lang.ClassLoader

Categories