Java Classes versus C++ Classes - java

I just started learning to develop for the Android, and I come from a strictly C++ background. I found that Java does not support Multiple Inheritance, but do we really have to create a seperate .java file for every new Activity?
I have a TabActivity, with 3 more Activitys that make up the tabs. I want to create a List View on one of the tabs, but I am starting to get confused. Do I need to make another .java file that extends ListActivity? I can see even a relatively small application becoming extremely large if I am going to need to create a seperate .java file for every activity.
SIDE NOTE
If I want to add the ListView to one of my tabs, how would I do that? Nothing I have found thus far mentions how to add new activities to other Activities.

The other answers give good points about interfaces and that is probably more what you are looking for. However, for further information, no you don't have to create a new .java file for every new class, there are alternatives. However, keep in mind that more classes is not necessarily a bad thing. Your options are...
Nested Class:
public class A {
public/private class B {
}
}
Instances of B can access private variables of A but cannot be constructed without an instance of A (this is an approach often used for button handlers, etc.)
Nested Static Class:
public class A {
public/private static class B {
}
}
Instances of B cannot access private variables of A but they do not require an instance of A in order to be constructed. Instances of B can be instantiated anywhere if B is declared public, or only in A's methods if B is declared private.
Anonymous Class:
public class A {
private void setupLayout() {
...
button.addClickListener(new ActionListener() {
public void actionPerfored(ActionEvent e)
{
handleClick();
}
});
}
}
This strange syntax creates a class that has no name and functions the same as a nested class (e.g. can access private variables). It's an alternative form of writing nested classes that is sometimes shorter but leads to very strange syntax.

Java doesn't support multiple inheritance on abstract or normal classes but on interfaces only.
What you can do is create abstract classes that extends a particular Activity and keep creating abstract classes until you have a class that inherit all your activity features.
Alternatively, is have a class that inherits multiple interfaces.

If you use an IDE to do this, the overhead of creating lots of file is much smaller.
However there are a few ways to have many classes in the same file. This includes a) using inner/nested classes b) anonymous classes c) enums d) package local classes.
The only thing you cannot do is easily if spread the definition of a class across multiple files.

Java does not support Multiple Inheritance
Workaround is you use interfaces
but do we really have to create a seperate .java file for every new Activity
No, if your activity can be done in an existing class or can be sub classed in an existing class. Java is built around creating classes for each activity.

Java doesn't allow multiple inheritance. But it does allow implementing multiple interfaces. You don't need to create a seperate file for each class (though it's a good practice). You can encapsulate sub-classes in the main class of your file.
ListView can be simply extended and you can use the corresponding extended class in the xml etc.

Java does kind of support multiple inheritance, if you just make the base classes abstract and call them interface instead of class.

You can simply declare a ListView in XML and call it in the Activity, no need to have a separate ListActivity, just for ListView. It's when your whole Activity is a ListView.
And as per the concerns about more classes, it's not a bad thing. More classes means more object oriented, not strictly though (Everything has a limit).
Multiple Inheritence was considered not good due to problem of diamond of death. So the work-around was to use Pure Virtual Classes known as Interface in Java (Interface means a normal class in Objective-C though).
I suggest you to read HeadFirst Java second edition, for better grip on terminology and their use. It's a good book for beginners.

Related

Is there any convention to store methods not particularly related to any class? [java]

I am currently learning Java and, while making a project, I created some methods that do not suit logically in any given class but are useful in the whole context of the project.
The best example I have is a method that splits camelCase worlds like this:
splitCamelCase -> Split Camel Case.
I have thought about creating a new abstract class called Toolbox and storing those methods there, but I wonder if there is any convention or best practice regarding this topic.
It's not uncommon to have utility classes (commonly named SomethingUtils) when it just doesn't make sense to put a method in an existing class.
There's nothing inherently wrong with it, but if you find yourself having a lot of methods or utility classes, then your design might be a bit off and you're programming in a more procedural than object oriented way.
As mentioned in comments, you don't make it an abstract class. It's a class filled with static methods working entirely on the parameters passed to them.
As kayaman sir has said if you are having too many utility classes and method it means that you code is more procedural rather than object oriented.
Nut if you still want to have a class which is just used to provide some utility then you can have such a class in java , just put some static method in them.
One of the best example of such a class is java.lang.Math.
for example following code will work
class MyUtilityClass
{
private MyUtilityClass()
{
// no object creation will be allowed
}
// make as many static methods you want
}
You can create your ToolBox Class and then you declare it as a package. After that you can import your ToolBox at the beginning of classes you want to use the methods from that ToolBox.

Subclass contained in parent class

Looking through some source code for a Settings App I found something that ressembles what you see below, where there are child classes of a class mentioned within the original class. These classes are not abstract and have no body.
public class mySettings extends PreferenceActivity {
...
//Class definition
...
public static class myColorSettings extends mySettings {/*empty*/ }
public static class myConnectSettings extends mySettings {/*empty*/}
}
In the actual app, there are buttons "My Color" and "My Connect" that each open up new activities (or fragments if the screen is dual pane).
So I have two questions: what is the use of declaring subclasses within a class itself - from an Object Oriented programming point of view - as shown above?
And my second question is, if the classes are clearly empty and not abstract, but the end result is not empty, what is the use of these empty declarations?
EDIT 1
As pointed out in the comment, the Android repo has a nearly identical setup. See the link http://tinyurl.com/nbkv7zg
(around line 1070)
Here is Oracle's answer to your first question:
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.
Source: http://docs.oracle.com/javase/tutorial/java/javaOO/nested.html
Without seeing the rest of the project's code, my best guess would be that those two classes, although empty, must be declared as required by some part of the PreferenceActivity parent class.
I'd call this generally a bad design.
Nested classes may be used as alternative to organizing them in a package, especially when their use is limited to or make only sense in the context of the containing class. If they are used outside, refactor them out.
As both classes are obviously empty, they are a complete waste and could be removed. Instead, each instance of the parent class could be used in a different role
mySettings colorSettings = new mySettings();
mySettings connectSettings = new mySettings();
Btw. starting the name of a class with lower case is a bad practice

Sharing Singleton logic between projects, with modifications for each project

I am developing two Android applications with similar -- but not identical -- logic, and I want to share code between them. Currently, I have a project for each application, and an additional project for shared classes. The shared-classes project is a library, and the application projects are linked to this library.
The problem I have is with a class that's responsible for getting data from the server and caching that data. The class is called DataSingleton. Fetching the data has some logic which is the same for both applications, and some which is different. My question is how to design the class to support this.
There are some limitations here:
The data Singleton should be a singleton, as implied by its name.
Some of the shared logic in the shared project uses the DataSingleton, so the DataSingleton must also be in the shared-classes project (otherwise I get a build error).
I don't want to put the application-specific logic in the shared project.
If this was C++, I would have 2 different classes name DataSingleton -- one in each application -- and then have the linker connect the correct class. Both classes could inherit from some common base class, to handle the code sharing for shared logic. Can I do something similar in Java?
If it helps, I can "initialize" the DataSingleton at the start of the application with some argument that will determine its behavior. I thought about passing a class to it, but then that class doesn't have access to the DataSingleton's private members.
What is the "right" way to do this?
Think about singleton. It is a class that does 3 thigs:
1. it has a business logic
2. it creates instance of itself
4. it holds this single instance and provides access to it.
You want to hold more than one implementations of your class. This means that you need interface and/or abstract base class and several concrete classes. But in this case the best solution is to separate #1 from #2 and #3: create hierarchy of DataFetchers (I am sorry, I changed your name DataSingleton because it does not describe the reality any more) and DataFetcherAccessor:
interface DataFetcher {}
class DataFetcher1 implements DataFetcher{}
class DataFetcher2 implements DataFetcher{}
class DataFetcherAccessor<A extends DataFetcher> {
private static A accessor;
public static void setImpl(Class<A> c) {
accessor = c.newInstance();
}
public static A getAccessor() [
return accessor;
}
}
There are obviously a lot of other solutions. For example you can use SPI to locate available implementation of your interface. You can also scan your classpath yourself and discover available implementation of interface DataFetcher or use Reflections for this.
Strip the DataSingleton in the shared project of the parts that will need to change in the different projects, define it as an abstract class and change its name to AbstractDataSingleton or something like that, then just create 2 separate classes in each product called DataSingleton or whatever and make them extend the AbstractDataSingleton in the shared project.

Object vs Extend in Java

I may be wrong as I have not got too much experience with Java, but here is a question.
I have a class which contains many methods (basically it is a simple library).
I create an object of this class let's say MyLibrary obj = new MyLibrary(parameters);
The parameters set up any necessary functionality for the library to run correctly.
Then I can call obj.getSomething/obj.setSomething/obj.createSomething etc etc...
In my main class I really need only one this kind of library object.
Now... Would it be more useful for me not to use it as an object, but put it as extends and then create a function inside of the library like a constructor which I would call manually?
EDIT:
The relation between the one class and MyLibrary is very close. Basically, I have many classes which do similar things but have some different higher layer functionality. So I separated method which must be in all those classes.
It seems it is very similar to shape class and triangle, circle, square example. So MyLibrary is similar to shape which contains all the foundation.
What you described strongly resembles a utility class, similar to Java's Collections. The class has only static methods, and a private constructor to prevent instantiations. This is a well-known idiomatic pattern in Java - you can use it to create your own groups of methods providing related functionality.
You should not extend, or even instantiate, utility classes at all. Starting with Java-5, you can statically import them so that you could use their methods without making an explicit reference to their class.
extends is used when you need an inheritance hierarchy. It seems more logical to put your code in two separate classes here, like you have it now.
Also, if your "library class" does multiple unrelated things, it should probably be split into multiple classes - one for each task.
You should really only use extends when you have a is-a relationship. So, you can think, is my main class a MyLibrary or should my class have a MyLibrary.
From your described problem, it sounds like having MyLibrary is the way to go.
With the limited detail that you have provided, you might want to consider the Singleton pattern.
extends should only be used when one object needs to inherit the characteristics and functionality of another one because they are very closely related. For example, if you have a Shape class, then you would extend Shape to create Circle, Square, and Triangle. Before you use extends you should learn more about inheritence and when you should and should not use it.
I would make this a static class to use. Similiar to javas MATH class API for math class. You can just use the methods of the class without making an object of it.
Well If your class if performing utility functions then you should mark all methods as static and use operations like
MyLibrary.doSomething();
MyLibrary.createSomething();
MyLibrary.getSomething();
But this wont allow you to keep some data members in the class and if you keep them they will be static as well.
I don't think so that extends suits your case.
Also if you want to keep only an object then you should look at Singleton A class for which only one instance can be created.
Assuming you are just using MyLibrary and may not alter it, you should use a wrapper that makes the whole thing a Singleton, as already proposed by Code-Guru.
public class MyLibraryWrapper {
private static MyLibrary instance = null;
private MyLibraryWrapper() {}
public static MyLibrary getInstance() {
if (instance == null)
instance = new MyLibrary();
return instance;
So in your code you would use
MyLibraryWrapper.getInstance().getSomething();
Best way to create singleton in java 1.5 or above is to use ENUM.
public enum Test {
INSTANCE;
}
INSTANCE is the only instance of Test class.

Why so many inner classes in Android?

I am a new fish in Android development. While reading books and Android source code I found out that there so many inner classes in the Android application. Why does Android need so many inner classes?
I am confused by these inner classes.
They are often the most efficient way of implementing a design.
An inner class can access the private members of the class which contains it, so using an inner class allows a split of functionality between classes without the need to add accessor methods for private variables.
Inner classes are not just in Android. I guess you need to understand why they are good in some cases.
Check this article about Inner classes: Inner classes: So what are inner classes good for anyway?.
Simply put, when translated into bytecode, inner classes are "rebuilt"
as external classes in the same package. This means any class in the
package can access this inner class. The owner/enclosing/father
classes’ private fields are morphed into protected fields as they are
accessible by the now external inner class.
OWASP Recommendation
So basically, it's just a "shortcut" that compromises the security of your own design.
So, there are not "needed" by Android in that sense.
I am guessing you have been doing C/C++ before. These inner classes are not Android specific. They come from Java. In Java, stacks (which in C/C++ we live by) do not exist in the same manner. Think of Java byte code as a blob of binary executable that exist inside one function (kind of like writing all of your code inside the main function in C/C++). But Java allows you to be "Object Oriented" and localize your code in classes for diffrent tasks. It also allows you to derive from another class and instantiate it at the same time. That is what you see in all the examples. The link that "Macarse" has provided explains this for a Java programmer.
This may also interest you:
Android: AsyncTask recommendations: private class or public class?
Its not about why, but which is preferred inner or outter classes for AsyncTasks, one of the most prone classes to be used as inner.

Categories