I am coming from Objective-C where we don't have packages and namespacing.
Android has android.text.format.DateFormat which has static methods that return java.text.DateFormat instances (getLongDateFormat() and getMediumDateFormat() specifically).
Are these methods referred to as "static methods" or "class methods" or both interchangeably?
Looking at Android documentation, how am I suppose to know that the android.text.format.DateFormat methods return a java.text.DateFormat instance and not an android.text.format.DateFormat instance (returning an instance of the latter is what I initially expected)?
How do I import the necessary packages to be able to use both of these classes in my source?
Is it possible to write my implementation code this way:
DateFormat df = DateFormat.getLongDateFormat(this.getActivity());
mLabel.setText(df.format(mEvent.getDate());
The other way I would write it would be to use the full package names, but this seems unnecessary:
java.text.DateFormat df = android.text.format.DateFormat.getLongDateFormat(this.getActivity());
mLabel.setText(df.format(mEvent.getDate());
Not sure why this is downvoted, it's a useful discussion.
1) I've always heard them referred to as "static methods".
2) The only way to see it is to follow the links. The documentation is definitely misleading in this case.
3/4) The typical way to do this in java is to not import one of the classes, and fully-qualify its class name. So if you elected to import java.text.DateFormat and not the android version, you'd do something like DateFormat df = android.text.format .DateFormat.getLongDateFormat(this.getActivity());
From the JLS:
A method that is declared static is called a class method.
I would say that I hear "static method" used more often than "class method", but both are in use and should be understood by competent Java developers.
The only option would be to hover the links on the return values. This is an example of extremely poor API design, with a name conflict built in, and the android.text.format.DateFormat should have been named something like DateFormatFactory. It appears that this class may have been intended to serve the same purpose as the java.text class originally and that API compatibility left it stuck. See java.sql.Date for a similar story.
Using import is a convenience only, allowing you to use the simple class name in your code. It's always legal to use a fully-qualified class name, and the compiler translates imported class names into fully-qualified ones. You can't import multiple classes with the same name because then there's no way to distinguish them
I suggest importing the class from java.text for two reasons: You'll probably be using it more often, and it's the more "standard" class. When faced with the choice of qualifying one of two classes with the same simple name, use the simple name for the one that developers would usually assume it refers to.
Related
I am a Java programmer using Ruby for the first time, and I have a few questions about how some features compare between the two languages.
Is the notion of a constructor relevant in Ruby? If yes, how does the behavior compare to Java constructors?
In Java, we generally keep separate .java files for different classes (when not nested). Is there a similar practice in Ruby? Or is each class itself not as important as in Java?
How do you extend a class (or .rb file)? I would like to extend a class and call super inside my local constructor to initialize some items.
How do you access the methods of a class in a .rb file, from a different class in another .rb file?
Are Ruby "gems" equivalent to Java packages?
1) Yes. There is concept of constructor which behaves like Java one. However, the constructor method is called initialize in Ruby, when in Java, the constructor has the same name as of class itself. eg:
class Foo
def initialize
# initialization logic here
end
end
2) Yes, it's rathe considered a best practice to store classes per file - separately, but it is not constrained by language.
3) For inheritance, there is different syntax in Ruby. Please consider following code:
class Parent
end
class Child < Parent
end
4) It is actually quite similar to Java, you use . to indicate method on object:
class Person
def name
"Tester"
end
end
p = Person.new
puts p.name
5) There is not really concept of packages in Ruby, but you might use modules to namespace your classes, eg:
module Foo1
class Biz
end
end
module Foo2
class Biz
end
end
b1 = Foo1::Biz.new
b2 = Foo2::Biz.new
Yes. No big difference.
Yes. More freedom in ruby though. (If you want to you can even define the same class in several files....) Apart from classes there are also modules that can be used as mixin - a sort of multiple inheritance.
The < operator is used for inheriting another class. It is the extends of ruby. In the subclass constructor you can call super just like in Java.
Instance methods are accessed just like in Ruby with a dot. Class methods can be accessed as in Java with a dot after the class name. Or with a double colon.
No. Ruby has no packages. Often modules are used around classes to provide a namespace in order to avoid clashes. Gems in ruby are more like a jar file (a maven dependency for example) in java.
Is constructor a relevant thing in Ruby? If yes, any change in behavior compared to Java?
No, there are no constructors in Ruby. Unlike Java, which has three different kinds of "methods" (instance methods, static methods, and constructors), Ruby has exactly one kind of methods: instance methods.
In Java, we generally keep separate .java files for different classes(if not nested). Is the approach same in Ruby?
No. You would use one file for related concepts. It might be a single class, but then again, it might not. For example, the set.rb file in the Ruby standard library contains both the Set and the SortedSet class.
It might also be that a single class is defined in multiple files. For example, the above-mentioned set.rb not only contains the Set and SortedSet class, it also contains a fragment of the Array class which has a to_set method for turning an array into a set.
Or Class itself is not much relevant?
Ruby is a class-based OO language, classes are very much relevant.
How can i extend one class (or a .rb file)? I would like to extend one class and call the super constructor inside my local constructor to initialize some items.
You can't "extend a file". You can, however extend classes, just like in Java.
How to access the Methods inside a class (.rb file) from another class (.rb file)?
Again, files have nothing to do with this.
You call methods on objects, just like in pretty much every other OO language, including Java. You don't "access methods inside a class".
Is packages in Java and Gems in Ruby are the same thing? We used to have multiple packages in a project for tests, utilities etc.Is the approach same in Ruby as well?
No. Gems are more like Maven artefacts. There is no analog to a Java package in Ruby, although one might use modules that way.
In Python you can do a:
from a import b as c
How would you do this in Java, as I have two imports that are clashing.
There is no import aliasing mechanism in Java. You cannot import two classes with the same name and use both of them unqualified.
Import one class and use the fully qualified name for the other one, i.e.
import com.text.Formatter;
private Formatter textFormatter;
private com.json.Formatter jsonFormatter;
As the other answers already stated, Java does not provide this feature.
Implementation of this feature has been requested multiple times, e.g. as JDK-4194542: class name aliasing or JDK-4214789: Extend import to allow renaming of imported type.
From the comments:
This is not an unreasonable request, though hardly essential. The occasional
use of fully qualified names is not an undue burden (unless the library
really reuses the same simple names right and left, which is bad style).
In any event, it doesn't pass the bar of price/performance for a language
change.
So I guess we will not see this feature in Java anytime soon :-P
It's probably worth noting that Groovy has this feature:
import java.util.Calendar
import com.example.Calendar as MyCalendar
MyCalendar myCalendar = new MyCalendar()
Java doesn't allow you to do that. You'll need to refer to one of the classes by its fully qualified name and only import the other one.
Today I filed a JEP draft to OpenJDK about this aliasing feature. I hope they will reconsider it.
If you are interested, you can find a JEP draft here: https://gist.github.com/cardil/b29a81efd64a09585076fe00e3d34de7
It's ridiculous that java doesn't have this yet. Scala has it
import com.text.Formatter
import com.json.{Formatter => JsonFormatter}
val Formatter textFormatter;
val JsonFormatter jsonFormatter;
Unless there are problems with non-default constructors you can always do this (while we all wait for the Java language specification to catch up):
public class YaddaYadda
{
private static class ZU extends eu.zrbj.util.ZrbjUtil_3_0 { }
public void foo (String s)
{
if (ZU.isNullOrEmpty(s))
{
// ...
For project-wide use the 'import' class can go into a separate class file, giving a single point of definition for the import.
This is a lifesaver especially with regard to 'library' classes, meaning collections of static utility functions. For one thing it gives you the ability to version these beasts - as shown in the example - without major inconvenience for the user.
Actually it is possible to create a shortcut so you can use shorter names in your code by doing something like this:
package com.mycompany.installer;
public abstract class ConfigurationReader {
private static class Implementation extends com.mycompany.installer.implementation.ConfigurationReader {}
public abstract String getLoaderVirtualClassPath();
public static QueryServiceConfigurationReader getInstance() {
return new Implementation();
}
}
In that way you only need to specify the long name once, and you can have as many specially named classes you want.
Another thing I like about this pattern is that you can name the implementing class the same as the abstract base class, and just place it in a different namespace. That is unrelated to the import/renaming pattern though.
Say I am using a Java library that has the following method
public static SomeInterface foo();
The interface SomeInterface has multiple implementations, some of which are protected within the library's package. One of these implementation is TheProtectedClass
What would be the best way to check if the object returned by foo() is an instance of TheProtectedClass?
My current plan is to create an Utils class that lives within my project but in the same package as the protected class. This Utils can refer to TheProtectedClass since it is in the same package and thus it can check if an object is instanceof TheProtectedClass.
Any other ideas?
EDIT: Some people are asking "why" so here is more context.
I am using jOOQ and in some part of my code, I want to know if the Field instance that I have is an instance of Lower.
Currently, I use field.getName().equals("lower") but this isn't as robust as I'd like it to be.
I realize that since Lower is a protected class, it isn't part of the API and that it can change but I am ok with that.
Class.forName("TheProtectedClass").isAssignableFrom(foo())
although it is a bad idea for many reasons. You're breaking the encapsulation and the abstraction here. If it's package-private, you shouldn't have to concern with it outside. If it's protected, you should explicitly inherit from it and use the API provided by class for this case.
The less obvious but more correct solution is to get an instance of TheProtectedClass, and compare it by
guaranteedTPCInstance.getClass().isAssignableFrom(foo())
, while still being kind of hacky, at least is more portable and OOPy IMO.
As to your idea of creating a class in the same package as TheProtectedClass to avoid being package-private - it's a viable solution, but a) it breaks the basic principle of encapsulation and the programming contract of the TPC class; packaging is done by library/class authors for a reason - to prevent irresponsible data access and using private API or undocumented proprietary methods, b) it's not always possible (and shouldn't be possible in case of properly designed library classes), since those classes can be not only package-private, but final or effectively final (anonymous inner classes etc) - for the reasons described by Bloch in EJ 2nd, "favor composition over inheritance" item, see also Good reasons to prohibit inheritance in Java? Use of final class in Java etc c) you can't do it with some Java library classes, as you can't define your class to be and use e.g. java.lang package. As such, the only "portable" solution is through reflection and through what I described.
tl;dr The fact you can piggyback another package by mimicking its package definition is an obvious C-style deficiency of Java's syntax (allowing programmer to do what he shouldn't be able to normally do; same goes with some specific reflection methods); hacks made this way are neither maintainable nor safe.
NOTE: If you you expect to do something in a internal implementation-dependent and, at the same time, portable and maintainable (e.g. impervious to implementation changes/class name changes etc) way, you're obviously expecting the impossible.
It appears that the best solution is to create a package in your project that has the same package as the package-private class and either expose TheProtectedClass.class as a Class<?> or simply add a simple method that checks if your Object is instanceof TheProtectedClass.
This does not require reflection, it is fast and relatively safe (compilation will break if the package-private class changes name).
I have a file Test.java and the following code inside it.
public class Abcd
{
//some code here
}
Now the class does not compile, but when I remove the public modifier , it compiles fine.
What is the reasoning behind Java allowing us to compile a class name that is different from the file name when it is not public.
I know it is a newbie question, but I'm not able to find a good explanation.
The rationale is to allow more than one top-level class per .java file.
Many classes—such as event listeners—are of local use only and the earliest versions of Java did not support nested classes. Without this relaxation of the "filename = class name" rule, each and every such class would have required its own file, with the unavoidable result of endless proliferation of small .java files and the scattering of tightly coupled code.
As soon as Java introduced nested classes, the importance of this rule waned significantly. Today you can go through many hundreds of Java files, never chancing upon one which takes advantage of it.
The reason is the same as for the door plates. If some person officially resides in the office (declared public) his/her name must be on the door tag. Like "Alex Jones" or "Detective Colombo". If somebody just visits the room, talks to an official or cleans the floor, their name does not have to be officially put on the door. Instead, the door can read "Utilities" or "Meeting room".
The Java specification states you can only have at most one public class per file. In this case, the class name should match the file name. All non-public classes are allowed to have any name, regardless of the file name.
I think allowing them is a prerequisite for nested classes. Anonymous Classes in particular dramatically reduce the number of .java files required. Without support for this, you would need lots of single method interface implementations in their own separate files from the main class they are used in. (I'm thinking of action listeners in particular)
There is a good explanation of all nested classes in the Nested Classes Java tutorial on Oracle's website, which has examples of each. It also has a reason they are useful, which I'll quote:
Why Use Nested Classes?
Compelling reasons for using nested classes include the following:
It is a way of logically grouping classes that are only used in one place: If a class is useful to only one other class, then it is logical to embed it in that class and keep the two together. Nesting such "helper classes" makes their package more streamlined.
It increases encapsulation: Consider two top-level classes, A and B, where B needs access to members of A that would otherwise be
declared private. By hiding class B within class A, A's members can be
declared private and B can access them. In addition, B itself can be
hidden from the outside world.
It can lead to more readable and maintainable code: Nesting small classes within top-level classes places the code closer to where it is
used.
(emphasis mine)
I am not familiar with Java spec back in the early days, but a quick search shows inner classes were added in Java 1.1.
I look at it the other way round. The natural state of affairs would be for the programmer to pick both the class name and the file name independently. Probably in order to simplify finding public classes from outside a package during compilation, there is a special restriction that a public class be in a file with the corresponding name.
Note that Java is case-sensitive, but the filesystem need not be. If the file's base name is "abcd", but the class is "Abcd", would that conform to the rule on a case-insensitive filesystem? Certainly not when ported to a case-sensitive one.
Or suppose you happened to have a class called ABCD, and a class Abcd (let's not get into that being a bad idea: it could happen) and the program is ported to a case insensitive filesystem. Now you not only have to rename files, but also classes, oops!
Or what if there is no file? Suppose you have a Java compiler which can take input on standard input. So then the class has to be named "StandardInput"?
If you rationally explore the implications of requiring file names to follow class names, you will find that it's a bad idea in more than one way.
Also one other point that many answers missed to point out is that without the public declaration, the JVM would never know which classes' main method needs to be invoked. All classes declared in one .java file can all have main methods, but the main method is run on only the class marked as public. HTH
Because of a java file can contains more than one class, it may have two classes in one java file. But a java file have to contain a class as the same name as file name if it contains a public class.
In Python you can do a:
from a import b as c
How would you do this in Java, as I have two imports that are clashing.
There is no import aliasing mechanism in Java. You cannot import two classes with the same name and use both of them unqualified.
Import one class and use the fully qualified name for the other one, i.e.
import com.text.Formatter;
private Formatter textFormatter;
private com.json.Formatter jsonFormatter;
As the other answers already stated, Java does not provide this feature.
Implementation of this feature has been requested multiple times, e.g. as JDK-4194542: class name aliasing or JDK-4214789: Extend import to allow renaming of imported type.
From the comments:
This is not an unreasonable request, though hardly essential. The occasional
use of fully qualified names is not an undue burden (unless the library
really reuses the same simple names right and left, which is bad style).
In any event, it doesn't pass the bar of price/performance for a language
change.
So I guess we will not see this feature in Java anytime soon :-P
It's probably worth noting that Groovy has this feature:
import java.util.Calendar
import com.example.Calendar as MyCalendar
MyCalendar myCalendar = new MyCalendar()
Java doesn't allow you to do that. You'll need to refer to one of the classes by its fully qualified name and only import the other one.
Today I filed a JEP draft to OpenJDK about this aliasing feature. I hope they will reconsider it.
If you are interested, you can find a JEP draft here: https://gist.github.com/cardil/b29a81efd64a09585076fe00e3d34de7
It's ridiculous that java doesn't have this yet. Scala has it
import com.text.Formatter
import com.json.{Formatter => JsonFormatter}
val Formatter textFormatter;
val JsonFormatter jsonFormatter;
Unless there are problems with non-default constructors you can always do this (while we all wait for the Java language specification to catch up):
public class YaddaYadda
{
private static class ZU extends eu.zrbj.util.ZrbjUtil_3_0 { }
public void foo (String s)
{
if (ZU.isNullOrEmpty(s))
{
// ...
For project-wide use the 'import' class can go into a separate class file, giving a single point of definition for the import.
This is a lifesaver especially with regard to 'library' classes, meaning collections of static utility functions. For one thing it gives you the ability to version these beasts - as shown in the example - without major inconvenience for the user.
Actually it is possible to create a shortcut so you can use shorter names in your code by doing something like this:
package com.mycompany.installer;
public abstract class ConfigurationReader {
private static class Implementation extends com.mycompany.installer.implementation.ConfigurationReader {}
public abstract String getLoaderVirtualClassPath();
public static QueryServiceConfigurationReader getInstance() {
return new Implementation();
}
}
In that way you only need to specify the long name once, and you can have as many specially named classes you want.
Another thing I like about this pattern is that you can name the implementing class the same as the abstract base class, and just place it in a different namespace. That is unrelated to the import/renaming pattern though.