I know that Java is mostly object oriented language since you can do things like encapsulation, inheritance, and run-time polymorphism.
But when I watch a lot of talks on youtube about RxJava they say under Android you work with imperative rules? Does this relate to the life-cycle methods?
When I work with POJO's isn't that Object Oriented? Does this have to with how we handle data through our architecture layers? I'm getting confused with all these 'paradigms' and 'styles' especially since RxAndroid is getting thrown into the mix with 'functional-reactive' style.
First of all: Android is an operating system, not a programming language. That language is mainly object oriented, but lately a lot of effort is going into making java more suitable for functional programming. Frameworks such as RxJava emphasize that, too.
Of course, there are different programming models that can be used on the Android platform.
Coming from there: there is simply no sense in assuming that this large, complex environment can be reduced to some simple, always correct single word description. It is a combination of many different aspects.
Or as the US citizens say: in pluribus unum.
Android itself is a platform, not a language, so the question contains a category mistake.
In general, the only way this kind of question can be definitively answered is by resort to fundamental definitions. These were stated by Peter Wegner in 1987 in the paper 'Dimensions of Object-based Language Design'.
Wegner provides the following definitions:
Object-based: a language is object-based if it supports objects as a language feature.
Class-based: an object-based language is class-based (classical) if every object has a class.
Object-oriented: an object-based language is object-oriented if its objects belong to classes and class hierarchies can be incrementally designed by an inheritance mechanism.
I think you've got it a little bit wrong.
Java is an imperative language. You'd be better to ask what the difference between declarative vs imperative programming, or the difference between object oriented and functional programming.
Here is a great article on imperative vs declarative:
https://tylermcginnis.com/imperative-vs-declarative-programming/
Here is a stack overflow answer explaining the difference between object oriented and functional:
Functional programming vs Object Oriented programming
Android provides a framework written in java. Android isn't a language, but Java is. Java is an object oriented language.
I hope that clears things up a bit.
Some people say that Java is more like a hybrid, taking this piece from this article:
That said, Java is not a pure Object-Oriented language. Someone said Java is a hybrid, which, IMO, is an accurate description. I would posit Java is a dirty hybrid of an OO language. Consider:
String s = string2.trim();
First, since "String" is immutable, the above code reeks of functional programming. The "trim()" operation should cause the whitespace to be trimmed off both ends of "string2", without needing reassignment. That is to say, operations should act on the data as close to the object as possible. This, to me, makes Java feel dirty (it also leads to tightly-coupled systems due to the prevalence of "get" accessor methods, but that's another topic entirely). Ahem, what? That example is perfectly OO. Object-orientation does not make mutable state necessary. Actually, since strings are passed around so often, the lack of mutator methods really just saves a lot of headache.
Second, Java cannot alter the behaviour of all messages. It mixes the types of "operations" available to objects, depending on their type. The "+" is equally applicable to ints as it is Strings, but not to Matrices, or Colors. This isn't so bad, because you can do matrix.add( matrix ), but serves to illustrate the point about Java being 'dirty' (or 'impure', if you prefer).
Lastly, it is a hybrid to provide performance gains. Even though Smalltalk has an advanced virtual machine, its inability (when I was using it) to provide a machine-correlated bytecode for integer math placed a significant performance impact on its entire environment. Being a hybrid, Java cannot be called a true Object-Oriented language. But then, why does it matter?Use the right tool for the job and life will be happy!*
So:
You can work all like procedural programming if you want, and not use anything of OOP, but also, is not pure OOP programming, because not everything in Java is an object.
Also:
Java8 introduces some concepts about Functional programming, one of them is the use of lambdas.
In resume, Java is imperative, OOP and functional language(dep on version).
Related
I just started learning java yesterday since i want to make android apps. So far i only know c. I am reading a book called "Head first java" and it keeps talking about object and classes which are pretty new to me. I just have one question and if someone can clarify this for me that'd be very helpful:
What is/are the difference(s) between classes(java) and structures(c)?
ps: I'd also love if you can recommend me a book that really is for absolute beginners because the book i'm reading right now doesn't have enough details for those that are completely new to object oriented programming. Thank you.
No. You don't get inheritance, methods, abstract methods, polymorphism, and many more object oriented concepts with Structs.
You can try to make C conform to object oriented behavior using structs, but that's different from using an object oriented language.
"Aren't classes in Java equivalent to structures in c?"
Short answer, No.
My answer is too short cause the differences is the difference between two completely different paradigms, and it needs a complete book (not even a chapter) like : "Thinking in java".
Java classes perform several roles, only one of which is (implicitly) defining the layout of the data structure called the instance of that class, but you are right in thinking that objects are essentially data structures, just like instances of struct.
The main difference is that C's struct is something much more raw and "close to the metal" than a Java class. Basically, with much additional framework code and strict adherence to many conventions you could reimplement a good part of Java's objects, but the syntax would not be as clean as in Java.
There are many other differences, such as what exactly is covered by compiler's static checking, automatic memory management, etc. In the end, differences outweigh similarities, but as a point of understanding, it is not wrong to compare Java objects with C structs.
I know, that I am contradicting the view of a lot of people here, but you are right, a class really is nothing more or less than a struct with a lot of bells and whistles.
To be precise, the C++ language actually specifies that an instance of a class without virtual functions and/or virtual inheritance has the same memory layout as a C struct with the same data members in the same order.
All that is added to the struct to provide runtime polymorphism is a single v-table pointer, which is used to look up the virtual members. Inheritance is generated by including the base class structures as data members of the child class struct.
Of course, when you think about it for a second, you realize that classes must be implemented with structs, one way or another. C++/Java classes must be implemented somehow, after all. And it helps to remind yourself that object orientation is not primarily a language feature, it is a paradigm that can be used in any imperative programming language. It can be used in Java, in C++, in C, in Pascal, in Fortran, and even in assembler. All which the so-called object oriented languages add, is syntactic sugar to handle all the technical stuff of object orientation.
Nevertheless, it is important to learn all the bells and whistles when you start working in C++ or Java.
I've noticed that Java, Python, Perl, and Haskell/Clojure have distinctively different treatment of static functions. In particular,
1) What are the idiomatic differences in the way static functions are implemented and utilized in different languages.
2) Do some of these languages have "more complete" separation and support of static vs statefull methods than others?
For example :
In clojure, all functions are, essentially, static - allowing for extreme modular composability , not associated with any thing in the object-ether. Clojure-functional programming can be described to java programmers as similar to static functions.
Meanwhile, in traditional idiomatic Java, there is often a mixture, where object-oriented features maintain internal state, relying on external static methods for certain, often stateless transformational operations.
Then, there is the scripting world : I've noticed in Perl and Python that the concepts of differentiating static vs stateful code are not stressed quite as much (UPDATE:As per comment - maybe this is due to the multi-paradigm nature).
And finally, we have the object-oriented breed of PHP-5 developers, who seem to code similarly to java developers in its their treatment of static vs stateful (object scoped) functions.
Any other insights into the differences in how different programmers, from different backgrounds, treat static functionality would really help me to review code with a few PHP/Perl developers that I work with.
The relevant distinction may be the programming paradigm emphasized by language. Functional languages such as Haskell & Clojure aim to eliminate side effects and emphasize determinism; encapsulating mutability or state in thinks like monads. This is in contrast to Imperative languages. Perl & PHP are multi-paradigm languages, so it is possible to implement imperative styles such as procedural and object oriented coding, or even emulate functional styles.
In collaborating with imperative programmers it might be worth focusing on loose coupling and side effect free design patterns such as Dependency Injection.
This is little different from what already been asked for here
I would like to know what topics/APIs are most important for Java interviews. for example -
Concurrency,
Collections
.....and like that.
The reason is because implementations like ConcurrentHashMap (read here) have so much details in them, that one would like to discuss about them as it covers many important aspects
java.io - difference between streams and writers. Buffered streams.
java.util - the collection framework. Set and List. What's HashMap, TreeMap. Some questions on efficiency of concrete collections
java.lang - wrapper types, autoboxing
java.util.concurrent - synchronization aids, atomic primitives, executors, concurrent collections.
multithreading - object monitors, synchronized keyword, methods - static and non-static.
I'd say there are two things you need for every java interview:
For Basic knowledge of the Language, consult your favorite book or the Sun Java Tutorial
For Best Practices read Effective Java by Joshua Bloch
Apart from that, read whatever seems appropriate to the job description, but I'd say these two are elementary.
I guess these packages are relevant for every java job:
java.lang (Core classes)
java.io (File and Resource I/O)
java.util (Collections Framework)
java.text (Text parsing / manipulation)
IMHO its more important to have a firm understanding of the concepts rather than specific knowledge of the API and especially the internal workings of specific classes. For example;
knowing that HashMap is not synchronized is important
knowing how this might affect a multithreaded app is important
knowing what kind of solutions exist for this problem is important
I wouldn't worry too much about specific API details like individual methods of ConcurrentHashMap, unless you're interviewing for a job that is advertised as needing a lot of advanced threading logic.
A thorough understanding of the basic Java API's is more important, and books like Effective Java can help there. At least as important though is to know higher level concepts like Object Orientation and Design Patterns.
Understanding what Polymorphism, Encapsulation and Inheritance are, and when and how to use them, is vital. Know how to decide between Polymorphism and Delegation (is-a versus has-a is a decent start, but the Liskov Substitution Principle is a better guide), and why you may want to favor composition over inheritance. I highly recommend "Agile Software Development" by Robert Martin for this subject. Or check out this link for an initial overview.
Know some of the core patterns like singleton, factory, facade and observer. Read the GoF book and/or Head First Design Patterns.
I also recommend learning about refactoring, unit testing, dependency injection and mocking.
All these subject won't just help you during interviews, they will make you a better developer.
We usually require the following knowledge on new developers:
Low level (programming) questions:
http://www.interview-questions-java.com/
Antipatterns:
http://en.wikipedia.org/wiki/Anti-pattern
Design:
http://en.wikipedia.org/wiki/Design_Patterns
On some of the interviews I have been to, there is also the java.io package covered, sometimes with absurd questions on what kind of exceptions would some rarely used method declare to throw, or whether some strange looking constructor overload exists.
Concurrency is always important for higher-level positions, but I think that knowing the concepts well (and understanding them ofc) would win you more points than specific API knowledge.
Some other APIs that get mentioned at interviews are Reflection (maybe couple questions on what can be achieved with it) and also java.lang.ref.Reference and its subclasses.
I ask some basic questions ('whats the difference between a list and a set?', 'whats an interface?', etc) and then I go off the resume. If hibernate is on there 5 times, I expect the candidate to be able to define ORM. You would be surprised how often it happens that they can't. I am also interested in how the candidate approaches software -- do they have a passion for it? And it is very important that the candidate believes in TDD. Naturally, if its a really senior position, the questions will be more advanced (e.g. 'whats ThreadLocal and when do you use it'), but for most candidates this is not necessary.
Completely agree with Luke here. We can not stick to some API's to prepare for Core Java interviews. I think a complete understanding of the OOPS concept in Java is must. Have good knowledge of oops shows the interviewer that the person can learn new API's easily and quick.
Topics that should be covered are as follows:
OOPS Concept
Upcasting & DownCasting
Threading
Collection framework.
Here is a good post to get started. Core Java Interview Q & A
I am wondering if Java is orthogonal or not, and if yes, then which are its features that make it orthogonal. How can you determine if a language is orthogonal or not? For example, I found on some website that C++ is not orthogonal, but no explanations, why not. What other languages are orthogonal? Please help me, because there is almost no information on the internet about this topic.
Thanks
The Art of UNIX Programming, Chapter 4. Modularity, Orthogonality, Page 89:
Orthogonality
Orthogonality is one of the most
important properties that can help
make even complex designs compact. In
a purely orthogonal design, operations
do not have side effects; each action
(whether it's an API call, a macro
invocation, or a language operation)
changes just one thing without
affecting others. There is one and
only one way to change each property
of whatever system you are
controlling.
Programming Language Pragmatics, Chapter 6, Page 228:
Orthogonality means that features can
be used in any combination, that the
combinations all make sense, and that
the meaning of a given feature is
consistent, regardless of the other
features with which it is combined.
On Lisp, 5.2 Orthogonality:
An orthogonal language is one in which
you can express a lot by combining a
small number of operators in a lot of
different ways.
I think an orthogonal programming language would be one where each of its features have minimal or no side effects, so they can be used without thinking about how that usage will affect other features. I borrow this from the definition of an orthogonal API.
In Java you'd have to evaluate for example if there is a combination of keywords/constructs that could affect each other when used simultaneously on an identifier. For example when applying public and static to a method, they do not interfere with each other, so these two are orthogonal (no side effects besides what the keyword is intended to do)
You'd have to do that to all its features to prove the orthogonality. That is one way to go about it. I do not think there exists a clear cut is or is not orthogonal in this matter either.
Using the term orthogonal programming language is unusual. Typically, in computer science you are really talking about orthogonal instruction-sets. However, if we are to extend the meaning to the grammar of a language:
"...meaning [the language] has a relatively small number of basic constructs and a set of rules for combining those constructs. Every construct has a type associated with it and there are no restrictions on those types...." see ALGOL
Then we can assume that if not all instructions in the language can work on all datatypes will yield non-orthogonality. This however does not mean that the converse is true, that is to say if all language instructions do work on all data types, it does not necessarily mean that the language is orthogonal.
More formally, an orthogonal language would have exactly ONE way to do a given operation. Non-orthogonal languages would have more than one way to achieve the same effect.
Simplest example:
for loop; vs. while loop;
for and while are non-orthogonal.
Orthogonality is feature of your design independent of the language. Sure some language make it easier for you to have an orthogonal design for your system but you shouldn't focus on a specific language to keep your system's design as orthogonal as possible.
Orthogonality is not really a language feature as such, even though some languages have features that promote orthogonality (such as annotations, built-in AOP, ..). Regarding orthogonality in Java: I have written a little case study about this using log4j as example: "Orthogonality By Example" - you might find this useful.
Lack of Orthogonality in C:
An array can contain any data type except void
Parameters are passed by value but array are passed by reference
A programming language is consider orthogonal if:
there is a relatively small set of primitive constructs that can combine in a relatively small number of ways to build data and control structures
every possible structure is legal
For example a language with 4 primitive data types (Int, Float, Double, Char) and two
type operators (Array and Pointer) can create a relatively large number of data structures.
So the advantage of orthogonality is to make the language simple and regular because there are less exceptions.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
Much of my programming background is in Java, and I'm still doing most of my programming in Java. However, I'm starting to learn Python for some side projects at work, and I'd like to learn it as independent of my Java background as possible - i.e. I don't want to just program Java in Python. What are some things I should look out for?
A quick example - when looking through the Python tutorial, I came across the fact that defaulted mutable parameters of a function (such as a list) are persisted (remembered from call to call). This was counter-intuitive to me as a Java programmer and hard to get my head around. (See here and here if you don't understand the example.)
Someone also provided me with this list, which I found helpful, but short. Anyone have any other examples of how a Java programmer might tend to misuse Python...? Or things a Java programmer would falsely assume or have trouble understanding?
Edit: Ok, a brief overview of the reasons addressed by the article I linked to to prevent duplicates in the answers (as suggested by Bill the Lizard). (Please let me know if I make a mistake in phrasing, I've only just started with Python so I may not understand all the concepts fully. And a disclaimer - these are going to be very brief, so if you don't understand what it's getting at check out the link.)
A static method in Java does not translate to a Python classmethod
A switch statement in Java translates to a hash table in Python
Don't use XML
Getters and setters are evil (hey, I'm just quoting :) )
Code duplication is often a necessary evil in Java (e.g. method overloading), but not in Python
(And if you find this question at all interesting, check out the link anyway. :) It's quite good.)
Don't put everything into classes. Python's built-in list and dictionaries will take you far.
Don't worry about keeping one class per module. Divide modules by purpose, not by class.
Use inheritance for behavior, not interfaces. Don't create an "Animal" class for "Dog" and "Cat" to inherit from, just so you can have a generic "make_sound" method.
Just do this:
class Dog(object):
def make_sound(self):
return "woof!"
class Cat(object):
def make_sound(self):
return "meow!"
class LolCat(object):
def make_sound(self):
return "i can has cheezburger?"
The referenced article has some good advice that can easily be misquoted and misunderstood. And some bad advice.
Leave Java behind. Start fresh. "do not trust your [Java-based] instincts". Saying things are "counter-intuitive" is a bad habit in any programming discipline. When learning a new language, start fresh, and drop your habits. Your intuition must be wrong.
Languages are different. Otherwise, they'd be the same language with different syntax, and there'd be simple translators. Because there are not simple translators, there's no simple mapping. That means that intuition is unhelpful and dangerous.
"A static method in Java does not translate to a Python classmethod." This kind of thing is really limited and unhelpful. Python has a staticmethod decorator. It also has a classmethod decorator, for which Java has no equivalent.
This point, BTW, also included the much more helpful advice on not needlessly wrapping everything in a class. "The idiomatic translation of a Java static method is usually a module-level function".
The Java switch statement in Java can be implemented several ways. First, and foremost, it's usually an if elif elif elif construct. The article is unhelpful in this respect. If you're absolutely sure this is too slow (and can prove it) you can use a Python dictionary as a slightly faster mapping from value to block of code. Blindly translating switch to dictionary (without thinking) is really bad advice.
Don't use XML. Doesn't make sense when taken out of context. In context it means don't rely on XML to add flexibility. Java relies on describing stuff in XML; WSDL files, for example, repeat information that's obvious from inspecting the code. Python relies on introspection instead of restating everything in XML.
But Python has excellent XML processing libraries. Several.
Getters and setters are not required in Python they way they're required in Java. First, you have better introspection in Python, so you don't need getters and setters to help make dynamic bean objects. (For that, you use collections.namedtuple).
However, you have the property decorator which will bundle getters (and setters) into an attribute-like construct. The point is that Python prefers naked attributes; when necessary, we can bundle getters and setters to appear as if there's a simple attribute.
Also, Python has descriptor classes if properties aren't sophisticated enough.
Code duplication is often a necessary evil in Java (e.g. method overloading), but not in Python. Correct. Python uses optional arguments instead of method overloading.
The bullet point went on to talk about closure; that isn't as helpful as the simple advice to use default argument values wisely.
One thing you might be used to in Java that you won't find in Python is strict privacy. This is not so much something to look out for as it is something not to look for (I am embarrassed by how long I searched for a Python equivalent to 'private' when I started out!). Instead, Python has much more transparency and easier introspection than Java. This falls under what is sometimes described as the "we're all consenting adults here" philosophy. There are a few conventions and language mechanisms to help prevent accidental use of "unpublic" methods and so forth, but the whole mindset of information hiding is virtually absent in Python.
The biggest one I can think of is not understanding or not fully utilizing duck typing. In Java you're required to specify very explicit and detailed type information upfront. In Python typing is both dynamic and largely implicit. The philosophy is that you should be thinking about your program at a higher level than nominal types. For example, in Python, you don't use inheritance to model substitutability. Substitutability comes by default as a result of duck typing. Inheritance is only a programmer convenience for reusing implementation.
Similarly, the Pythonic idiom is "beg forgiveness, don't ask permission". Explicit typing is considered evil. Don't check whether a parameter is a certain type upfront. Just try to do whatever you need to do with the parameter. If it doesn't conform to the proper interface, it will throw a very clear exception and you will be able to find the problem very quickly. If someone passes a parameter of a type that was nominally unexpected but has the same interface as what you expected, then you've gained flexibility for free.
The most important thing, from a Java POV, is that it's perfectly ok to not make classes for everything. There are many situations where a procedural approach is simpler and shorter.
The next most important thing is that you will have to get over the notion that the type of an object controls what it may do; rather, the code controls what objects must be able to support at runtime (this is by virtue of duck-typing).
Oh, and use native lists and dicts (not customized descendants) as far as possible.
The way exceptions are treated in Python is different from
how they are treated in Java. While in Java the advice
is to use exceptions only for exceptional conditions this is not
so with Python.
In Python things like Iterator makes use of exception mechanism to signal that there are no more items.But such a design is not considered as good practice in Java.
As Alex Martelli puts in his book Python in a Nutshell
the exception mechanism with other languages (and applicable to Java)
is LBYL (Look Before You Leap) :
is to check in advance, before attempting an operation, for all circumstances that might make the operation invalid.
Where as with Python the approach is EAFP (it's easier to Ask for forgiveness than permission)
A corrollary to "Don't use classes for everything": callbacks.
The Java way for doing callbacks relies on passing objects that implement the callback interface (for example ActionListener with its actionPerformed() method). Nothing of this sort is necessary in Python, you can directly pass methods or even locally defined functions:
def handler():
print("click!")
button.onclick(handler)
Or even lambdas:
button.onclick(lambda: print("click!\n"))