In java, what's the relationship between field and class? - java

Please refer to this API. The link is:
http://download.carrot2.org/stable/javadoc/org/carrot2/text/preprocessing/pipeline/CompletePreprocessingPipeline.html
Class CompletePreprocessingPipeline
Field Summary
DocumentAssigner documentAssigner
Document assigner used by the algorithm, contains bindable attributes.
Then I found some example using completePreprocessingPipeline this way
completePreprocessingPipeline().documentAssigner()exactPhraseAssignment(true)
I do not understand the relationship between "completePreprocessingPipeline" and "documentAssigner" in terms of "field vs.class".

A class contains fields. All instance of that class have those fields.
http://download.oracle.com/javase/tutorial/java/javaOO/classes.html
In the first example, The Bicycle class has three fields cadence, dear and speed.
This is standard Java code structure, nothing special about it. I suggest you learn some Java and the Javadocs may make more sense.

Your example must be from some other language. Maybe a scripting language that can run on the JVM or see Java libraries.
What might be true in java:
CompletePreprocessingPipeline completePreprocessingPipeline = new CompletePreprocessingPipeline();
completePreprocessingPipeline.documentAssigner.exactPhraseAssignment = true;
You instantiate a class, and get an object. Then you can refer to fields in the object, if the field modifier allows it (if it were public for example)

A field is a member variable of a class. The type of the field may indeed be another class.
In this case their appears to be a "getter method" .documentAssigner() which returns the documentAssigner field, which is of the type DocumentAssigner.

I do not understand the relationship
between
"completePreprocessingPipeline" and
"documentAssigner" in terms of "field
vs.class".
That's because your question doesn't make sense. Both completePreprocessingPipeline() and documentAssigner() are methods. No fields at all in that code. Ad there is a missing '.'.

Related

What are all the number of ways the immutability of a class can be broken? [duplicate]

I made my class immutable by following all java standards
A. Defined class as final
B. declared all fields as private and final
C. No setter method
D. No method changes the state of object
E. declared all method as final
F. Safer/defencieve copying of collection/ non mutable object fields.
These are the priliminary checkpoints I made when desigining immutable class.
But one question left, my object can still be modified by java reflection, am I right?
Or is there any point I missed in the class?
Thanks in advance.
There's no hiding from reflection - even immutable classes are not immune. There is nothing you can do about it, though, so "cannot be modified through reflection" is not one of the criteria of immutability.
Yes. Reflection can still access / change it. You can't really plan against that. If someone's altering your object with reflection, I would doubt the quality of code they're writing.
Immutable classes are fantastic to ensure thread safe applications. Immutable objects are ALWAYS thread safe. If you're looking for more great information, please read Effective Java. It's a MUST READ for any Java developer.
Yes, still it can be modified through reflection. Apart from that it seems you took required care to make it immutable.

Class design, case for static methods

I had a discussion about usage of static method, briefly the argument is should a class definition have a method as static or instance method in the following scenario. There is a class that defines an entity i.e, what its properties are and what operations are allowed on it.
class dummy{
String name;
String content;
String someRandomOpeation(){
....
}
static String createKey( String inputName, String inputContent ){
return inputName+inputContent;
}
}
The class definition also has a static method that takes in some arguments (say content and date, which defines an instance logically) and use it to construct a key (a string) and return the same. Now if an instance of the message is created it would have the content and date as fields. Is the argument that I can get a key given a name and content and not have to create an instance valid to have the static method. Or does the fact that a pair of name and content logically define an instance say that an instance to be created and get a key from that?
Having a method as static just because you do not wish to instantiate is NOT a valid argument. According to design we use static methods in helper/util classes which may or may not have any properties of its own. These classes basically help in performing some common action which many different classes can use. Also the functions are so modular that they only use the arguments passed to the function to derive the output.
The class mentioned by you will not work because you cannot make a static reference to a non static field constant in JAVA.
Moreover, the disadvantage of using static methods strictly associated with its class fields is that you can not override them.
Is the argument that I can get a key given a name and content and not
have to create an instance valid to have the static method.
No. In this case you almost do not need a class at all. You can always pass data members to class methods, but that does not mean that we do not need classes.
There is an additional argument - encapsulation. It is much clearer and niced to have an instance method getKey() with no arguments and hide the implementation details.
Or does the fact that a pair of name and content logically define an
instance say that an instance to be created and get a key from that?
Also no. The fact itself does not mean that you should create an instance.
The first question here is wether we need a class or not. Do we really have some meaningfull objects, instances of something (dummy)? For example, if I have a library, it obviously make sense to have a class Book, as I have lots of books around. Do you have such a situation? Is this key logically associated with an instance of whatever (dummy here), in a way that Author and ISBN are logically associated with a Book? Does instances of this concept (dummy) has some relationships with some other concepts? Like a Book can be rented.
If most of these answers is yes - than this method should be instance method with no arguments.
Or...
Do you maybe only need kind of a "service" that calculates a key from 2 strings? It this all you need? Are there some other similar "services" that you need, independent on instances. If these answers are mostly "yes", that you do not even need a class. Or you can have a class "Services", with no attributes and with this static method and arguments (and maybe additional methods).
There is also a mixed situation. You still need instances for some other purpose, but you also need a createKey method that is totally independent on any instance, and only provide some global service that is somehow related with the class logic. Then a static method can make sense.
I think your way of thinking is kind of function-oriented instead of object oriented. I think you need a "click" in your mind, which would help you understand the right purpose and the meaning of objects and classes.

Convention for methods declaration in Java

Is there a convention in Java on where to declare fields - before or after methods?
Class layout: see here http://java.sun.com/docs/codeconv/html/CodeConventions.doc2.html#1852
The following table describes the parts of a class or interface declaration, in the order that they should appear
Class/interface documentation comment (/*.../)
class or interface statement
Class/interface implementation comment (/.../), if necessary
Class (static) variables
Instance variables
Constructors
Methods
Most of the code I saw declared fields first, then methods (which is also suggested by the Java code conventions guide: http://www.oracle.com/technetwork/java/codeconventions-141855.html#1852)
Standard Java code conventions from Sun: http://java.sun.com/docs/codeconv/CodeConventions.pdf
And Oracle: http://www.oracle.com/technetwork/java/codeconvtoc-136057.html
Fields before methods is the most common style.
I've mostly seen them at the top. One engineer I respect puts them at the bottom (to emphasize that you shouldnt be thinking about them :). You can avoid the Thinking About problem entirely by coding to interface, not classes. Also, take your vitamins. And floss!
From most code I've seen, fields get declared before methods. This isn't set in stone, as some people follow the common C++ practice of putting public fields and methods first, and then private fields and methods. I wouldn't treat it as a strict guideline; just ask yourself what makes your code more understandable by another person.
According to Sun's "Code Conventions for the Java Programming language", this is indeed the case: static fields first, then instance fields, then constructors, then methods.
However this part of the conventions is not quite as widely confirmed to as others: while using non-capitalized class names or capitalized variable names will immediately yield protests from the vast majority of Java programmers, many will accept putting fields next to the methods that operate on them.

why MyClass.class exists in java and MyField.field isn't?

Let's say I have:
class A {
Integer b;
void c() {}
}
Why does Java have this syntax: A.class, and doesn't have a syntax like this: b.field, c.method?
Is there any use that is so common for class literals?
The A.class syntax looks like a field access, but in fact it is a result of a special syntax rule in a context where normal field access is simply not allowed; i.e. where A is a class name.
Here is what the grammar in the JLS says:
Primary:
ParExpression
NonWildcardTypeArguments (
ExplicitGenericInvocationSuffix | this Arguments)
this [Arguments]
super SuperSuffix
Literal
new Creator
Identifier { . Identifier }[ IdentifierSuffix]
BasicType {[]} .class
void.class
Note that there is no equivalent syntax for field or method.
(Aside: The grammar allows b.field, but the JLS states that b.field means the contents of a field named "field" ... and it is a compilation error if no such field exists. Ditto for c.method, with the addition that a field c must exist. So neither of these constructs mean what you want them to mean ... )
Why does this limitation exist? Well, I guess because the Java language designers did not see the need to clutter up the language syntax / semantics to support convenient access to the Field and Method objects. (See * below for some of the problems of changing Java to allow what you want.)
Java reflection is not designed to be easy to use. In Java, it is best practice use static typing where possible. It is more efficient, and less fragile. Limit your use of reflection to the few cases where static typing simply won't work.
This may irk you if you are used to programming to a language where everything is dynamic. But you are better off not fighting it.
Is there any use that is so common for class literals?
I guess, the main reason they supported this for classes is that it avoids programs calling Class.forName("some horrible string") each time you need to do something reflectively. You could call it a compromise / small concession to usability for reflection.
I guess the other reason is that the <type>.class syntax didn't break anything, because class was already a keyword. (IIRC, the syntax was added in Java 1.1.)
* If the language designers tried to retrofit support for this kind of thing there would be all sorts of problems:
The changes would introduce ambiguities into the language, making compilation and other parser-dependent tasks harder.
The changes would undoubtedly break existing code, whether or not method and field were turned into keywords.
You cannot treat b.field as an implicit object attribute, because it doesn't apply to objects. Rather b.field would need to apply to field / attribute identifiers. But unless we make field a reserved word, we have the anomalous situation that you can create a field called field but you cannot refer to it in Java sourcecode.
For c.method, there is the problem that there can be multiple visible methods called c. A second issue that if there is a field called c and a method called c, then c.method could be a reference to an field called method on the object referred to by the c field.
I take it you want this info for logging and such. It is most unfortunate that such information is not available although the compiler has full access to such information.
One with a little creativity you can get the information using reflection. I can't provide any examples for asthere are little requirements to follow and I'm not in the mood to completely waste my time :)
I'm not sure if I fully understand your question. You are being unclear in what you mean by A.class syntax. You can use the reflections API to get the class from a given object by:
A a = new A()
Class c = a.getClass()
or
Class c = A.class;
Then do some things using c.
The reflections API is mostly used for debugging tools, since Java has support for polymorphism, you can always know the actual Class of an object at runtime, so the reflections API was developed to help debug problems (sub-class given, when super-class behavior is expected, etc.).
The reason there is no b.field or c.method, is because they have no meaning and no functional purpose in Java. You cannot create a reference to a method, and a field cannot change its type at runtime, these things are set at compile-time. Java is a very rigid language, without much in the way of runtime-flexibility (unless you use dynamic class loading, but even then you need some information on the loaded objects). If you have come from a flexible language like Ruby or Javascript, then you might find Java a little controlling for your tastes.
However, having the compiler help you figure our potential problems in your code is very helpful.
In java, Not everything is an object.
You can have
A a = new A()
Class cls = a.getClass()
or directly from the class
A.class
With this you get the object for the class.
With reflection you can get methods and fields but this gets complicated. Since not everything is an object. This is not a language like Scala or Ruby where everything is an object.
Reflection tutorial : http://download.oracle.com/javase/tutorial/reflect/index.html
BTW: You did not specify the public/private/protected , so by default your things are declared package private. This is package level protected access http://download.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html

Synonym for "Class" in java language not in English language?

Whenever we talk about objects we have instances, methods : functions : behavior, member variable: state, like so many interchangeable words. but for "Class" till now i didnt see people who have used some other word. So is there any other word in java which can be used(or in use)(dont tell any English synonym) which i can use. while explaining my code.
EDIT: Dont invent looking at this question it should be in use which i might not know
The concept of class is related to 'universal' and all that logic (abstraction/universal against instantiation/particular) comes from Aristotle (derived from Plato) philosophy. The OOP seems to take concepts from that filosophy.
The question for me is very relevant. Here is a link from wikipedia (http://en.wikipedia.org/wiki/Aristotle#Universals_and_particulars), and if you read this resume you could understand the relations between Aristotle philosophy and OOP.
Aristotle disagreed with Plato on this point, arguing that all universals are instantiated. Aristotle argued that there are no universals that are unattached to existing things. According to Aristotle, if a universal exists, either as a particular or a relation, then there must have been, must be currently, or must be in the future, something on which the universal can be predicated. Consequently, according to Aristotle, if it is not the case that some universal can be predicated to an object that exists at some period of time, then it does not exist.
Cool ah?
I hope it helps...
Instances, methods, functions, behaviour, etc., are all English words, so I don't quite comprehend your restriction.
So, for Class: Type.
Actually, those all have slightly different meanings: A method is a function attached to a class (they are often incorrectly used interchangably), while behaviour refers at a higher level to what a function/method does.
State refers to the specific value of a variable, or of many variables combined.
To answer your question, another word for class would be object, as you said yourself.
[Edit] It appears I spoke too tongue-in-cheek. As many people have pointed out, 'object' can also refer to an instance of a class. I think your safest bet would be to use class when you mean a class, instance when you mean an instance, spade a spade etc.
Well I heard people referring to it as a blueprint (meaning that it is a definition of what kind of state and what operations an instance will provide).
I'm pretty sure that class is the best way to describe a class in Java.
It is a pretty specific idea, and any synonym will not be able to capture the full meaning of the word.
I saw many times the word Clazz used in the code to avoid the reserved word. Does that help?
Prototype?
I would suggest "Mould" to describe the role of a class
Refer to SoloLearn on google playstore.
Class is also known as Object Factory.
But FYKI, only "class" keyword is used to create a class.
Good luck

Categories

Resources