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
Related
I'm wondering if there is any difference between creating a class in a new file and declaring one inside of another class, would it still be able to be referenced from outside of the class? I'm wondering because it would help my workplace be more organized.
Here is the full documentation for nested classes.
If you want to know when to use inner classes (from link):
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.
Yes, you can access your inner classes from other classes. (read about controlling access to members of a class).
Here you can find an example on how to access inner class from "outside" of the class.
This question already has answers here:
When to use inner classes in Java for helper classes
(10 answers)
Closed 8 years ago.
So I have a ClassA:
public ClassA {
String key;
List<ClassB> value;
}
And this ClassA is mapped to a database table (with 2 columns having key -> list of values) and the values here get stored as a row in there.
public ClassB {
Integer data1;
...
String dataN;
/* constructors and some getters/setters follow */
}
To clarify, ClassB just contains some data that is being stored in database.
When ClassA is being saved, List<ClassB> is being converted to JSON string and getting saved.
There are 2 ways to define ClassB.
Either have it as a regular class
Define it as a inner class(not sure if static or not) inside classA.
ClassB is currently not being used anywhere else in the project.
What do you think should be the right way and why?
I am bit confused regarding nested classes and I cannot distinguish if they are being misused or not.
Personally, if the class is small (for example just an helper) and is not to be used anywhere else, I would prefer doing an inner class. However, this is mostly a matter of opinion.
I think the best in these case is to make sure everyone in your dev team work the same way so it is easier for everyone to debug.
Note that there is a difference between inner class and nested class. A nested (static) class is an inner class declared static, while a simple inner class is normally not static.
Nested static class can be accessed anywhere using Class.NestedStaticClass.
See Nested class documentation for more details and example.
Here an interesting quote from the link I gave u before :
Serialization of inner classes, including local and anonymous classes,
is strongly discouraged. When the Java compiler compiles certain
constructs, such as inner classes, it creates synthetic constructs;
these are classes, methods, fields, and other constructs that do not
have a corresponding construct in the source code. Synthetic
constructs enable Java compilers to implement new Java language
features without changes to the JVM. However, synthetic constructs can
vary among different Java compiler implementations, which means that
.class files can vary among different implementations as well.
Consequently, you may have compatibility issues if you serialize an
inner class and then deserialize it with a different JRE
implementation. See the section Implicit and Synthetic Parameters in
the section Obtaining Names of Method Parameters for more information
about the synthetic constructs generated when an inner class is
compiled.
You might also consider using Anonymous inner class. An anonymous inner class is a class coded directly in the instanciation. For example
new ParentClassName(constructorArgs) {
members..
}
ClassB is currently not being used anywhere else in the project.
I think the key word here is "currently".
If you imagine a situation in which ClassB might be useful in other places in the project (say, if that project grows in a particular way, or if there are other tables that might map to the same structure in the future), then it should probably be a "normal" class.
If the class is logically tied to ClassA. For example, ClassA represents a train and ClassB train cars, which are always related to trains and never to other vehicles which are not trains, then you should define it as a nested class or inner class of ClassA.
Whether to make it nested or inner depends on the type of connection between an object of class ClassB and one of ClassA. It's not always a clear-cut issue, but remember that static nested classes can exist independently of their parent class. (e.g. you can manufacture a train car before you ever create a train object that it will be part of, and you can move train cars between trains), while inner classes always contain an invisible reference to their parent object, and such an object has to exist before you can create an object of the inner class.
All else being equal, I think I would gamble on a static nested class as an initial solution. If I realize that there are other places that need the same class, it's going to be relatively easy to refactor it.
I am curious as to how the concept of "inheritance" takes place in the world of object oriented programming. Let me explain my dilemma (I came across this dilemma while studying Java but I hope that my question is generic in nature) :
Suppose there is a class A and a class B. Class A "inherits" Class B. What does this actually mean? Does the compiler make a "new" class, which is THEN instantiated into an object which contains the elements of both the classes A and B behind the scenes? If that's the case, then how are the access restrictions implemented according to the access specifiers?
For a moment, I wondered if it happens in the following manner :
An object of class A is created and then an object of class B is created. Java then somehow "link" the members of A to the members of B and make it appear as if they belonged to the same class and it does that according to the access specifiers.
But then, it occurred to me that there is a fault with this theory. Suppose two different classes, B and C are inheriting class A. Then, if we are going to make objects of class B and class C, then they'll have their OWN copies of the elements of class A. So this theory fails too.
I was just trying to explain the confusion about inheritance that I have in my mind. It's giving me headache. Please help.
EDIT : This is a link to a discussion related to my question which i found on this site.
Do subclasses inherit private fields?
I may fail, but I'm going to take a stab at an explanation on this for you.
In honesty, I think you may be making what is really a very classic mistake in how you conceive object programming - and that's making the distinction between objects and classes. Object creation in virtually any object-oriented language is one of construction based on a class definition. From your question, it sounds as though you are mentally modeling an OO language in general and object inheritance in particular as aggregating discrete objects, where in reality the objects are being defined in terms of aggregated class definitions.
public class A
{
public A();
}
public class B:A
{
public B();
}
public class C:B
{
public C();
}
In your A->B->C model, C's definition is in terms of its own unique properties plus all the members of its immediate ancestor, B, which, in turn, is defined in terms of its own unique properties plus all the members of its immediate ancestor, A. The process of creating the object is still a unique and discrete event, and the object, despite its multi-layered heritage, is still only one object at instantiation time.
Regarding the visibility of certain members: When a class author designs and builds a class, he makes certain decisions about what he makes available in two distinct perspectives: that which is exposed to consumers of the class, and that which is exposed or available to subclasses. Members and fields declared private are every bit a part of descendant classes, even if they are "contractually" forbidden to be accessed by subclasses. You could make a crude analogy that a TV has a "public" interface of an on/off button, volume control, and color controls, but has "internal" controls not intended for the consumer such as the internal electronic components, or the power supply. They're still very much there even though they are not "visible" or "available" to consumers or subclasses.
Now, that said, there are constructs in most OO languages that reflect the properties you describe - multiple objects - and that involve a design pattern known as Composition (or, sometimes, Aggregation. This is where a class isn't derived from an ancestor class - typically because the class is declared "sealed" (C#) or "final" (Java) (or other designation that prohibits inheritance). That forces a developer interested in using the class to make it a member of another class, such that when the an object of the class is instantiated, you DO have discrete objects of both classes.
You might have the following:
public final class InterestingThing
{
//definitions
public InterestingThing()
}
public final class MyThing
{
InterestingThing _interestingThing = new InterestingThing();
public MyThing()
}
This is very much the kind of scenario you were describing in your original question, in which the creation of MyThing implies the distinct creation of an InterestingThing. Keep in mind, too this structure is generally forced by the design and definition of the original class of interest.
Ultimately, objects are defined by their classes, and multiply-inherited classes are still just a class, but in a refined, hopefully increasingly robust, hierarchy based on good, incremental object design.
I hope, in some way, this explanation helps to answer your question.
Class A "inherits" Class B. What does this actually mean?
If class A extends class B, it inherits all members (fields and methods) of B, i.e. class A will have these members even through they are not declared in the body of class A.
Whether class A is permitted to access a particular member is an unrelated matter.
An object of class A is created and then an object of class B is created. Java then somehow "link" the members of A to the members of B and make it appear as if they belonged to the same class and it does that according to the access specifiers.
No. A single object of class A is created. That object just happens to have all inherited members, too. For instance, if you have:
class B {
private int x;
}
class A extends B {
private int y;
}
The runtime will store, for every object of class A, the value of x and the value of y.
That code in class A does not access the value of x is enforced by verifying that the source code of A does not use the name x upon compilation, and by verifying that the bytecode of A does not refer to the field x upon loading the class at runtime. Put differently, access modifiers are independent of memory layout.
What's the reason of making top-level class non-public in Java?
Let's say we have Foo.java, there could be
class Foo {
}
or
public class Foo {
}
I understand that there will be some class - visibility issues with the former example (probably it won't be visible from other packages). But anyway, are there any reasons why someone may want to do as in the first code sample?
UPD: What cons I see in the former solution: nobody cares that it's non-public. That class can be simply extended by some other public class in the same package later, then, non-public part of the class may bring you visibility/access issues.
Here is an example.
No one needs to know about existence of our ConcreteDocument.
DocumentIF.java
public interface DocumentIF {
}
ConcreteDocument.java
class ConcreteDocument implements DocumentIF {
}
DocumentFactory.java
public class DocumentFactory {
public DocumentIF createDocument() {
return new ConcreteDocument();
}
}
Typically, you make a class package-private because you don't want the class to be used outside the package. When a top-level class isn't public, it's private to the package.
Say you have a package with a number of classes that must communicate the same sort of data with one another. But this data structure is an implementation detail and so you don't want it being used by user code. Making the transfer class package private maintains this sort of package level encapsulation.
I understand that there will be some class - visibility issues with the former example (probably it won't be visible from other packages).
That seems to me to be reason enough to use it if you want to keep the class private to that one package.
Just noticed another use! It seems you can only have one public top-level class per code file, but any number of non-public top-level classes. Haven't verified it personally, but if true that could be quite useful to prevent cluttering your project folder and to group classes with related functionality that aren't needed outside of the package.
Classes without a public or protected modifier are only visible inside the package they reside. If you think of components and interfaces there is a reason for leaving out the public modifier. Let's say you have a public class MyCompontent that internally uses other classes, but does not want to publish those to the outside world (users of the component) it makes sense to leave out the visibility modifier.
It is considered good design to keep the visibility of a class to the most minimum required. The reasons that I can think of:
The class can easily change in the future without causing breakages in external packages as the external packages do not have access to the class. In this regard it might be even better to start off a class by making it a private inner class.
The class being package visible cannot be extended by classes in external packages. This again makes it easier for this class to change without causing breaking changes in external packages. If this class was not meant to be extended then it would be even better to make this final.
A public visible class becomes a part of the exported API of your library. If you are a library designer, it is better to keep your exported API as small as possible because you do not want to confuse your consumer with un-necessary classes/details. Item 1 would again hold good in this case.
The book "Effective Java" by Josh Bloch is an excellent reference for Idiomatic Java code and design.
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.