Ruby features vs Java - java

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.

Related

Groovy's extension-module compared to java's inheritance

Is groovy's extension module feature a hybrid form of java's inheritance feature? Why are the extension-module needs to be declared as static?
Short answer is I think yes. It is a bit difficult to answer clearly, since the inheritance for the extension methods is done completely by the runtime (and the static compiler). As such it has nothing to do with how Java does inheritance.
To answer the second question... They are static, because for situations in which you need state you usually use the meta class. Extension methods are initially thought of as convenience methods or to make the API more Groovy. As such, they are a special form of methods added to the meta class. You can see them as simplified version. But that also means they don't have all the abilities. Implementing extension methods, that can keep local state on a per "self"-object basis (basically what fields/properties would do) is actually difficult to do efficient... but you could always use per instance meta classes for this.
For all extensive purposes they are syntactic sugar so that a static method appears to be more OOP like. There is no inheritance because static methods in Java and Groovy do not participate in inheritance (that is classes do not inherit static methods).
The methods need to be static because the compiler does not know how to instantiate the surrounding class of the extension method.
However I believe there are languages that do allow for methods to be defined outside of the enclosing class and do some sort inheritance but not many do not (I believe CLOS and Dylan do). Also they are many languages that appear to allow methods to be added but the type of "object" is actually changed/hidden to some other type. This is called adhoc polymorphism (e.g. Clojure, Haskell, sort of Golang and sort of Scala) but again has nothing to do with inclusional polymorphism (Java inheritance).
Unfortunately the reference documentation and other docs don't define the semantics of extension methods:
Q. Can they override instance methods?
I tested extension methods via use Category methods and metaClass expando methods. Neither approach overrides instance methods. I didn't test extension modules installed via module descriptor.
Q. Can they be overridden by extension methods on subclasses?
I tested that, too. use methods and metaClass extension methods don't get overridden by extension methods on subclasses.
Q. Can they call inherited super methods?
No, since they're implemented via static methods.
Q. Can they call private methods?
Experiments showed that they can, surprisingly.
Q. Can they access private instance variables?
No, since they're implemented via static methods.
Q. Are they callable from Java methods?
Maybe, if the extension module is on the classpath when compiling the calling code. I didn't test it.
Conclusion: Extension methods are not a form of inheritance. They seem to be a dynamic form of Universal Function Call Syntax (UFCS), that is, when the language can't find a method variable.foo(arguments) it looks for a static extension function foo(variable, arguments) to call. [Please correct my hypothesis if wrong!]
You asked why they're defined as static. That seems to match the semantics: A static function that's not involved in inheritance, although its calling syntax makes it look like a convenient method call.
You can write an extension method like an instance method using the #groovy.lang.Category annotation. That does AST transformations at compile time to turn it into a suitable static method.
Also see Groovy traits. That is a form of (mixin) inheritance.

Why does Java allow us to compile a class with a name different than the file 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.

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

Using a function in two unrelated Java classes

I have two classes in my Java project that are not 'related' to each other (one inherits from Thread, and one is a custom object. However, they both need to use the same function, which takes two String arguments and does soem file writing stuff. Where do I best put this function? Code duplication is ugly, but I also wouldn't want to create a whole new class just for this one function.
I have the feeling I am missing a very obvious way to do this here, but I can't think of an easy way.
[a function], which takes two String arguments and does soem file writing stuff
As others have suggested, you can place that function in a separate class, which both your existing classes could then access. Others have suggested calling the class Utility or something similar. I recommend not naming the class in that manner. My objections are twofold.
One would expect that all the code in your program was useful. That is, it had utility, so such a name conveys no information about the class.
It might be argued that Utility is a suitable name because the class is utilized by others. But in that case the name describes how the class is used, not what it does. Classes should be named by what they do, rather than how they are used, because how they are used can change without what they do changing. Consider that Java has a string class, which can be used to hold a name, a description or a text fragment. The class does things with a "string of characters"; it might or might not be used for a name, so string was a good name for it, but name was not.
So I'd suggest a different name for that class. Something that describes the kind of manipulation it does to the file, or describes the format of the file.
Create a Utility class and put all common utility methods in it.
Sounds like an ideal candidate for a FileUtils class that only has static functions. Take a look at SwingUtilities to see what I'm talking about.
You could make the function static in just one of the classes and then reference the static method in the other, assuming there aren't variables being used that require the object to have been instantiated already.
Alternatively, create another class to store all your static methods like that.
To answer the first part of your question - To the best of my knowledge it is impossible to have a function standalone in java; ergo - the function must go into a class.
The second part is more fun - A utility class is a good idea. A better idea may be to expand on what KitsuneYMG wrote; Let your class take responsibility for it's own reading/writing. Then delegate the read/write operation to the utility class. This allows your read/write to be manipulated independently of the rest of the file operations.
Just my 2c (+:

Is a Ruby module equivalent to a Java Interface?

As I understand it, an interface is Java is intended to enforce a design by laying out methods for classes implementing the interface to fill in. Is this the idea with a Ruby module also? I see that just like with Interfaces in Java, you can't instantiate a module in Ruby.
The short answer is no.
Here's the reasoning, a Java/C# interface defines the method signatures an implementing class will provide at minimum.
Additionally:
With ruby modules there is no such contract because of the duck-typing.
Modules are just a way to extract out common functionality for easy re-use. The closest relation is C# extension methods, but those aren't an exact match since they exist in a static context.
Modules can add state to an existing class.
Modules can have static methods
Modules can act as namespaces
Example:
module SimpleConversation
class NamespacedExample
def poke
puts "ouch"
end
end
attr_accessor :partner_name
def converse
partner_name ||= "Slowpoke"
speak + "\n#{partner_name}: Yes they are"
end
def self.yay
puts "yay"
end
end
class Foo
include SimpleConversation
attr_accessor :name
def speak
name ||= "Speedy"
"#{name}: tacos are yummy"
end
end
x = Foo.new
x.name = "Joe"
x.partner_name = "Max"
puts x.speak
puts x.converse
y = SimpleConversation::NamespacedExample.new
y.poke
SimpleConversation.yay
I think I'd equate a module to something more akin to an extension method in C#. You're adding functionality to an existing class that is actually defined elsewhere. There isn't an exact analog in either C# or Java, but I definitely wouldn't think of it as an interface because the implementation is derived as well as the interface.
A Module in ruby is a bit of scope/namespace that can be added to other things. They are used for two distinct but related purposes: bundling up a bunch of related things (constants, classes, etc.) that belong together and then adding them into some other scope (like multiple inheritance).
For example, there are modules called things like Comparable and Enumerable and so forth that encapsulate the functionality you'd expect something to have if these adjectives applied. By providing a basic definition (a method that compares two instances for Comparable and an iterator for Enumerable) you can import the module and find yourself with the full interface.
On the other hand there are modules like Net that you would seldom include in a class but which provide a bundle of functionality such as Net::HTTP, Net::FTP, Net::SMTP, and so on.
In the middle there are things like Math and Process which might be used one way or the other.
-- MarkusQ
No. A module in ruby is more akin to a static class. I am not a Java developer, but I am guessing that Java interfaces are similar to C# interfaces, i.e., they define a contract, but not an implementation.
I should not that, while I have experience in ruby, it is in video game creation (RGSS/2). I am sure that I am ignorant of many things a veteran ruby programmer would know.
From formal point of view modules in Ruby implement design
pattern called "mixin".
http://en.wikipedia.org/wiki/Mixin
It can be compared to PHP traits.
http://php.net/manual/en/language.oop5.traits.php
Such architecture is useful in languages that don't allow multiple inheritance, e.g. Ruby, PHP.

Categories

Resources