What are these notations in class diagrams? - java

I know basics of UML and java's OO interpretations using class diagrams. But after looking at this class, I felt weird. What are the member variables and what do they represent in the actual language? I guessed the first one which is a boolean type (If I'm right), but what are the other member variables especially those which take some arguments? Any help would be appreciated. Thanks

This diagram you include is not strict uml. From what i can understand it means the following:
You have a class called ElectricFan
Your class has the following member variables (power, speed, maxSpeed, type, etc). In parenthesis i guess that the author has included the values applicable to each member variable.
Also, the author includes the methods that are applicable in this class (i.e. switchOnOff(), changeSpeed(), etc).
An important piece of information that the author doesn't include is the visibility and type of the member variables as well method arguments and return types.
If you are interested in learning more about UML you could start by reading Marting Fowler's UML distilled (http://www.amazon.com/UML-Distilled-Standard-Modeling-Language/dp/0321193687).

The values given in brackets are not arguments, instead they seem like enumerator types.
As far as the speed parameter is concerned it looks like an unsigned int.

Related

Java - what is a a prototype?

In a lecture on Java, a computer science professor states that Java interfaces of a class are prototypes for public methods, plus descriptions of their behaviors.
(Source https://www.youtube.com/watch?v=-c4I3gFYe3w #8:47)
And at 8:13 in the video he says go to discussion section with teaching assistants to learn what he means by prototype.
What does "prototype" mean in Java in the above context?
I think the use of the word prototype in this context is unfortunate, some languages like JavaScript use something called prototypical inheritance which is totally different than what is being discussed in the lecture. I think the word 'contract' would be more appropriate. A Java interface is a language feature that allows the author of a class to declare that any concrete implementations of that class will provide implementations of all methods declared in any interfaces they implement.
It is used to allow Java classes to form several is-a relationships without resorting to multiple inheritance (not allowed in Java). You could have a Car class the inherits from a Vehicle class but implements a Product interface, therefor the Car is both a Vehicle and a Product.
What does "prototype" mean in Java in the above context?
The word "prototype" is not standard Java terminology. It is not used in the JLS, and it is not mentioned in the Java Tutorial Glossary. In short there is no Java specific meaning.
Your lecturer is using this word in a broader sense rather than a Java-specific sense. In fact, his usage matches "function prototype" as described in this Wikipedia page.
Unfortunately, the "IT English" language is full of examples where a word or phrase means different (and sometimes contradictory) things in different contexts. There are other meanings for "template" that you will come across in IT. For instance:
In C++ "template" refers to what Java calls a generic class or method.
In Javascript, an object has a "template" attribute that gives the objects methods.
More generally, template-based typing is an alternative (more dynamic) way of doing OO typing.
But the fact that these meanings exist does not mean that your lecturer was wrong to refer to interface method signatures as "templates".
"prototype" is not the the best/right terminus to be used. interfaces are more like "contracts", that implementing classes have to fulfill.
The method's heads/definitions will have to be implemented in the implementing class (using implements keyword in the class head/class definition/public class xy implements ...).
I guess this naming conventions leave much room for many ideological debates.
Or the author had some sort of a mental lapsus and mapped the construct of prototypical inheritance from javascript into java in his mind somehow.
Interfaces are not prototypes for classes in Java.
In languages like C & C++, which compiles to machine code sirectly, compiler should be aware of the nature of any identifier (variable/class/functions) before they are references anywhere in the program. That mean those languages require to know the nature of the identifier to generate a machine code output that is related to it.
In simple words, C++ compiler should be aware of methods and member of a class before that class is used anywhere in the code. To accomplish that, you should define the class before the code line where it is used, or you should at least declare its nature. Declaring only the nature of a function or a class creates a 'prototype'.
In Java, an 'interface' is something like description of a class. This defines what all methods a particular kind of class should mandatory have. You can then create classes that implements those interface. Main purpose that interfaces serve in java is the possibility that a Variable declared as of a particular interface type can hold objects of any class that implements the object.
He tells it in C/C++ way, let me explain, in C++ you can define prototypes for methods at the header files of classes so that other classes can recognize these methods, also in C where there is no class concept, you can define prototypes at the beginning of file and then at somewhere in same file you can implement these prototypes, so that methods can be used even before their implementation is provided. So in Java interfaces provide pretty much same way, you can define prototypes for methods(method headers) that will be implemented by classes that implement this interface.
In a lecture on Java, a computer science professor states that:
Java interfaces of a class are:
1. are prototypes for public methods,
2. plus descriptions of their behaviors.
For 1. Is ok: - yes, they are prototypes for implemented public methods of a class.
For 2. This part could be a little bit tricky. :)
why?
we know: interface definition (contain prototypes), but doesn't define (describe) methods behavior.
computer science professor states: "... plus descriptions of their behaviors.". This is correct only if we look inside class that implements that interface (interface implementation = prototype definitions or descriptions).
Yes, a little bit tricky to understand :)
Bibliography:
Definition vs Description
Context-dependent
Name visibility - C++ Tutorials
ExtraWork:
Note: not tested, just thinking! :)
C++:
// C++ namespace just with prototypes:
// could be used like interface similar with Java?
// hm, could we then define (describe) prototypes?
// could we then inherit namespace? :)
namespace anIntf{
void politeHello(char *msg);
void bigThankYou();
}
Prototypes provide the signatures of the functions you will use
within your code. They are somewhat optional, if you can order
your code such that you only use functions that are previously
defined then you can get away without defining them
Below a prototype for a function that sums two integers is given.
int add(int a, int b);
I found this question because i have the same impression as that teacher.
In early C (and C++ i think) a function, for example "a" (something around lexic analysis or syntactic, whatever) can not be called, for example inside main, before it's declaration, because the compiler doesn't know it (yet).
The way to solve it was, either to declare it before it's usage (before main in the example), or to create a prototype of it (before main in the example) which just specifies the name, return values and parameters; but not the code of the function itself, leaving this last one for wherever now is placed even after it's called.
These prototypes are basically the contents of the include (.h) files
So I think is a way to understand interfaces or the way they say in java "a contract" which states the "header" but not the real body, in this case of a class or methods

Breaking java generics naming convention? [duplicate]

This question already has answers here:
Generic type parameter naming convention for Java (with multiple chars)?
(5 answers)
Closed 7 years ago.
I have an interface whose declaration is as follows:
/**
* #param T - the type of entity.
* #param C - the type of entity container will be returned.
*/
public interface FindByNamedQuery<T extends Serializable, C extends Collection<T>> extends Command {
C executeNamedQuery(String namedQuery);
}
I wonder if I can (should) break the Java naming convention to do this:
public interface FindByNamedQuery<ENTITY_TYPE extends Serializable, RETURNED_CONTAINER extends Collection<ENTITY_TYPE>> extends Command {
RETURNED_CONTAINER executeNamedQuery(String namedQuery);
}
I am beginning to disagree with the single-character convention, after using it since the mid-1990s.
I find the readable names more readable. This is helpful in understanding both the implementation and interface of generic types.
The ambiguity problem seems overstated for Java. Few class names are all-uppercase. Constants are not used in the same context as class names.
It's true that the #param JavaDoc elements can provide a longer description. But it's also true that the JavaDocs are not necessarily visible. (For example, there's a content assist in Eclipse that shows the type parameter names.)
For example, compare :
public final class EventProducer<L extends IEventListener<E>,E>
implements IEventProducer<L,E> {
to:
public final class EventProducer<LISTENER extends IEventListener<EVENT>,EVENT>
implements IEventProducer<LISTENER, EVENT> {
Although the single-character names have been recommended as a convention by Sun/Oracle, conventions can be changed. The consequences of challenging this convention are minor. If you and your team prefer meaningful names for your type parameters, I personally would go for it.
Edit (2015)
Google style for Java allows both single-letter names and multi-character class-like names ending in T.
5.2.8 Type variable names
Each type variable is named in one of two styles:
A single capital letter, optionally followed by a single numeral (such as E, T, X, T2)
A name in the form used for classes (see Section 5.2.2, Class names), followed by the capital letter T (examples: RequestT,
FooBarT).
I wonder if I can (should) break the java naming convention to do this:
No, this should be avoided as it becomes easier to confuse the type parameters with constants and other identifiers.
Here's a quote from the official trail on generics:
Type Parameter Naming Conventions
By convention, type parameter names are single, uppercase letters. This stands in sharp contrast to the variable naming conventions that you already know about, and with good reason: Without this convention, it would be difficult to tell the difference between a type variable and an ordinary class or interface name.
The most commonly used type parameter names are:
E - Element (used extensively by the Java Collections Framework)
K - Key
N - Number
T - Type
V - Value
S,U,V etc. - 2nd, 3rd, 4th types
You'll see these names used throughout the Java SE API and the rest of this tutorial.
Using TDescription is pretty common in C#. It maintains the T name but is also descriptive at the same time, like so:
public interface FindByNamedQuery<
TEntityType extends Serialiazble,
TReturnedContainer extends Collections<TEntityType>> extends Command
{
TReturnedContainer executeNamedQuery(String namedQuery);
}
As others have said ALL_CAPS almost always indicates a constant.
IMO, "it would be difficult to tell the difference between a type variable and an ordinary class or interface name." does not apply here, because the T prefix easily identifies it as a type variable.
Again, this is C# but see MSDN: Naming Conventions For Generics
In all other cases, the official
Microsoft guidelines for generic
naming conventions are:
Name generic type parameters with descriptive names, unless a single
letter name is completely self
explanatory and a descriptive name
would not add value.
public interface ISessionChannel<TSession>
{...}
public delegate TOutput Converter<TInput,TOutput>(TInput from);
Consider indicating constraints placed on a type parameter in the name of parameter. For example, a parameter constrained to ISession may be called TSession.
The compiler might not complain, but your teammates might not appreciate you using what looks to be a constant in a place where they're expecting a type parameter.
I think this is the gripe of many people using generics. I don't quite agree with Sun's statement that if you use a full fledged name then it will confuse with an existing class name or something else. In that case we can start the placeholder name with a dollar like this:
public class HashMap<$Key,$Value> implements Map<$Key,$Value>{}
No one in their sane mind names a class starting with a dollar sign. And a dollar sign also is used to denote a placeholder many templating languages velocity, struts, spring, etc. I think this is the way to go.
I have got more details about this and the reasoning behind not having to use a single letter notation in my blog post if anyone is interested.
http://readsethu.wordpress.com/2012/05/23/a-generic-class-and-why-is-it-confusing/
Like Allen before, my advice comes more from C# (which I use extensively since 5 months) than Java (which I played with, but it never went very far...), but I find Java and C# code quite similar in spirit (that is, when compared by, say, C++)
Anyway, when using a C#/Java generic (or a C++ template) on a simple type, I usually use T:
// C++
template<typename T>
class MyClass { /* ... */ } ;
// C#
public MyClass<T> { /* etc. */ }
// Java
public MyClass<T> { /* etc. */ }
Usually, the type T goes with the class, so there is no need to describe it more.
But when really describing the type adds to the code clarity, I do it.
Or when I have two or more types in the same generic/template declaration, it helps to make the difference between two types. For example (real life example in C#) :
// C++
template<typename T_Data, typename T_Underlying>
class MyClass { /* ... */ } ;
// C#
public MyClass<T_Data, T_Underlying> { /* etc. */ }
// Java
public MyClass<T_Data, T_Underlying> { /* etc. */ }
This way, it is easy to make the difference between the two typenames in the code, where T and U are, well... kinda anonymous: For those using Visual C++, going in debug inside Dinkumware's STL code, full of T, _U, and other mono-letter typenames can be quite frustrating... I guess the same goes for C# or Java code.
You will note that in each case (C++, Java or C#), I don't follow the convention somewhere in my type namings: The reason is that sometimes, you just have to try something else instead of following the herd, even if in the end, you'll find you're wrong.
In the current case, the violation of naming convention is not critical (there are worst problems in Java than this petty crime), and at the very last, you'll learn personally and exactly WHY it is wrong, instead of quoting old documents.
And if you find in the end you're right, well...
I would name type variables similar to types, in camel casing, but prefixed with "_".
public interface FindByNamedQuery
<_EntityType extends Serialiazble,
_ReturnedContainer extends Collections<_EntityType>>
extends Command
{
_ReturnedContainer executeNamedQuery(String namedQuery);
}

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.

What are the default modifier fields for an enum type?

This is a homework question, so I'm not looking for a direct answer. I need a push in the right direction. I'm simply not understanding the question. My answer to this was "The values are, in fact, instances of their own enumeration type." Which came back incorrect. I'm looking at the API now...is this referring to the methods listed in the methods summary?
I'm noticing from this page that modifier types for Java in general refer to access control (private, public, protected) and non-access modifiers (static, final, abstract, volatile).
I'm putting public, protected for my next answer as I see those two listed within the API for access control. Am I thinking about this correctly?
Got back my homework, turns out I was correct.
The modifiers for each constant are implicitly declared, as mentioned in the Java Language Specification, §8.9 Enums. As a corollary, consider which modifiers are associated with all-upper-case identifiers in the widely used Google Java Style or Java Coding Style Guide?
As the homework should be over a while ago and for anyone like me looking for a quick answer:
public static final
For each enum constant c declared in the body of the declaration of E,
E has an implicitly declared public static final field of type E that
has the same name as c. The field has a variable initializer
consisting of c, and is annotated by the same annotations as c.
(taken from trashgod's link: Java Language Specification, §8.9 Enums)
I believe you are correct. In java, all the values in an Enum have the type of that Enum. Instead of being treated like magic values as they are in many other languages, they are instances of a type, a very beautiful OO way of thinking about things.
"The values are, in fact, instances of their own enumeration type."
This is factually correct, but it does not answer the question you were asked about the implicit modifiers for enum values. That is why it is the wrong answer.

Generic type parameter naming convention for Java (with multiple chars)?

In some interfaces I wrote I'd like to name generic type parameters with more than one character to make the code more readable.
Something like....
Map<Key,Value>
Instead of this...
Map<K,V>
But when it comes to methods, the type-parameters look like java-classes which is also confusing.
public void put(Key key, Value value)
This seems like Key and Value are classes. I found or thought of some notations, but nothing like a convention from Sun or a general best-practice.
Alternatives I guessed or found...
Map<KEY,VALUE>
Map<TKey,TValue>
Oracle recommends the following in Java Tutorials > Generics > Generic Types:
Type Parameter Naming Conventions
By convention, type parameter names are single, uppercase letters. This stands in sharp contrast to the variable naming conventions that you already know about, and with good reason: Without this convention, it would be difficult to tell the difference between a type variable and an ordinary class or interface name.
The most commonly used type parameter names are:
E - Element (used extensively by the Java Collections Framework)
K - Key
N - Number
T - Type
V - Value
S,U,V etc. - 2nd, 3rd, 4th types
You'll see these names used throughout the Java SE API and the rest of this lesson.
I'd stick to it to avoid the confusion among the developers and possible maintainers.
Append Type
A good discussion can be found in the comments on the DZone page, Naming Conventions for Parameterized Types.
See the comment by Erwin Mueller. His suggestion makes perfect obvious sense to me: Append the word Type.
Call an apple an apple, a car a car. The name in question is the name of a data type, right? (In OOP, a class essentially defines a new data type.) So call it a “Type”.
Mueller’s example, drawn from the original post’s article:
public interface ResourceAccessor < ResourceType , ArgumentType , ResultType > {
public ResultType run ( ResourceType resource , ArgumentType argument );
}
Append T
A duplicate Question provides this Answer by Andy Thomas. Note the excerpt from Google’s style guide that suggests a multi-character type name should end in a single uppercase T.
Yes, you can use multi-character names for type variables, as long as they are clearly distinguished from class names.
This differs from the convention suggested by Sun with the introduction of generics in 2004. However:
More than one convention exists.
Multi-character names are consistent with other Java styles, such as Google’s style for Java.
The readable names are (surprise!) more readable.
Readability
In some interfaces I wrote I’d like to name generic type parameter with more than one character to make the code more readable.
Readability is good.
Compare:
public final class EventProducer<L extends IEventListener<E>,E>
implements IEventProducer<L,E> {
to:
public final class EventProducer<LISTENER extends IEventListener<EVENT>,EVENT>
implements IEventProducer<LISTENER, EVENT> {
or, with Google’s multi-character convention:
public final class EventProducer<ListenerT extends IEventListener<EventT>,EventT>
implements IEventProducer<ListenerT, EventT> {
public final class EventProducer<ListenerT extends IEventListener<EventT>,EventT>
implements IEventProducer<ListenerT, EventT> {
Google style
The Google Java Style Guide allows both single-letter names and multi-character class-like names ending in T.
5.2.8 Type variable names
Each type variable is named in one of two styles:
A single capital letter, optionally followed by a single numeral (such as E, T, X, T2)
A name in the form used for classes (see Section 5.2.2, Class names), followed by the capital letter T (examples: RequestT, FooBarT).
Issues
“Without this convention, it would be difficult to tell the difference between a type variable and an ordinary class or interface name.” – from the Oracle tutorials, “Generic types”
Single-character names are not the only way to distinguish type parameters from class names, as we’ve seen above.
Why not just document the type parameter meaning in the JavaDoc?
It’s true that the #param JavaDoc elements can provide a longer description. But it’s also true that the JavaDocs are not necessarily visible. (For example, there’s a content assist in Eclipse that shows the type parameter names.)
Multi-character type parameter names don’t follow the Oracle convention!
Many of Sun’s original conventions are followed nearly universally in Java programming.
However, this particular convention is not.
The best choice among competing conventions is a matter of opinion. The consequences of choosing a convention other than Oracle’s in this case are minor. You and your team can choose a convention that best meets your needs.
You can use javadoc to at least give users of your generic class a clue. I still don't like it (I agree with #chaper29) but the docs help.
eg,
/**
*
* #param <R> - row
* #param <C> - column
* #param <E> - cell element
*/
public class GenericTable<R, C, E> {
}
The other thing I have been known to do is use my IDE to refactor a class breaking the convention. Then work on the code and refactor back to single letters. Makes it easier for me anyway if many type parameters are used.
The reason why the official naming convention reccommends using single letter is the following:
Without this convention, it would be difficult to tell the difference
between a type variable and an ordinary class or interface name.
I think with modern IDEs that reason is no longer valid as eg. IntelliJ Idea shows generic type parameters with different colors than regular classes.
Code with generic type as displayed in IntelliJ Idea 2016.1
Because of that distinction I use longer descriptive names for my generic types, with same convention as regular types. I avoid adding prefixes and suffixes such as T or Type as I consider them unnecessary noise and no longer needed to visually distinguish generic types.
Note: As I am not a user of Eclipse or Netbeans, I do not know whether they offers a similliar feature.

Categories

Resources