As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
What is the purpose of nested classes?
Any examples?
I don't really see the need for them. Why not just create a new class? It seems really unorganized when using a nested class.
Why Use Nested Classes?
There are several compelling reasons for using nested classes, among them:
It is a way of logically grouping classes that are only used in one place.
It increases encapsulation.
Nested classes can lead to more readable and maintainable code.
Logical grouping of classes—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.
Increased 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.
More readable, maintainable code—Nesting small classes within top-level classes places the code closer to where it is used.
Uses for nested classes:
eliminate namespace pollution
provide the nested class access to private members of the outer class
organize related code together
hide implementations of interfaces from the outside world
There are probably other uses, but these, off the top of my head, should be enough to suggest that there might, actually, be a use for them.
It is a way of logically grouping classes that are only used in one place.
It increases encapsulation.
Nested classes can lead to more readable and maintainable code.
Related
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
Is it best practice to have all the classes public in a Java project? I have noticed that in all Java projects I have worked with, there have only been public classes.
It isn't a guideline, no.
The information hiding principle tells us to only exposed what is required, and nothing more, to minimize coupling.
So, for example, if a class lets you handle logic in a separate class easier, and is only used by that class, there's no reason to have it public, nor should you make it public.
The simple answer to your question is "no!"
The slightly more complicated one is that you should only make a class public if it needs to be used by other classes outside it's own package. But if, like me, you break you project up into many packages for readability, then then if will often be the case that your classes will need to be public to be usable.
While your question is simple to ask, it is far from simple in its nature. Much will depend upon the kind of code your writing. It you're writing a library then use externally is probably high on your agenda. In an application less so.
I have found that I prefer the public approach. I try and design for reuse because it keeps my options open, causes me to think more carefully about my implementation because of the reuse issues, and that leads to better code. But it really is horses for courses, you are the biggest variable in this equation.
It depends, For top level class's, If you want other class's in a different package to view your class you should mark it public. If you only want class's in the same package to view you class mark it default(no-modifier).
So, your question is really, should all top level classes be public? I think it boils down to the usage of the package access that you do in your project. This question was relevant to that, some time ago.
Usually most classes are indeed public but there are cases when you might want to use default or private scope as well.
A class using the default scope is only accessible to other classes in the same package. In case of helper classes for example it's often a good practice to limit their use this way as your code becomes more encapsulated. The private scope can often be used for inner classes for the same reason.
No it is not. There are lot of classes with other access specifiers or even anonymous. For an example, you can write private or anonymous classes that can be registered to listeners like
'ActionListener' and 'ItemListener'. Just like that, for various purposes, we do write lot of classes with no public specifier. It really helps to separate your work into pieces.
However, in Java, normally every source file contains a public class. That is because if your source file's name is 'Reader.java', you cannot have a private or other access specifier for the class 'Reader' inside that source file. It must be public or default. Apart from that, no other class can have the access specifier 'public' instead of 'Reader' class.
Other thing is, private, protected and other types (except default) of classes cannot be written in a source file as "Independent classes". For an example, following is an error
Check.java
private class Check
{
}
It definitely is not best practice. You are seeing it because most programmers don't know that a top-level class doesn't have to be public.
Ideally, a package isn't just a way to organize classes into groups. There is no minimum or maximum number of classes that belong in a single package; rather, subpackages should be created only when there is a need for package-level classes and/or members. Java APIs do this a lot, and since the javadoc distributed from Sun/Oracle is generated for protected-level classes and members, some packages may appear to be sparse, even to the point of appearing nonsensically so.
For instance, the javax.swing.colorchooser package appears to have only four classes, but it actually has 17 (actual number may vary depending on the version of Java). Four are public; the rest are only for use with JColorChooser internals.
I've found that an inner class that is becoming too big to be easily maintained as an inner class is usually a good candidate for being a non-public top-level class.
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
Using a getter/setter in the internal code of a class instead of accessing the instance variable directly, is it good or bad practice? At least for setters one could add additional code validating the value, but for the getters it's just overhead? How intelligent is the Java compiler, if my getters/setters just set/get the value directly, will Java optimize my code and replace the getters/setters by direct access to the instance variables, so there's no method calling overhead?
It is more common to access the field directly. The value of a setFieldName method is more obvious for programmers using your code in other classes. With the implementation details hidden, they might not realize what ranges of values are acceptable, so keeping fields private and forcing other developers to go through a setter makes sense. But inside your own class, the case for using a setter is much weaker. If you look at the source for the java API you'll find that getter / setter methods are generally not used within a class.
There is no need to do that inside a class, unless want to perform additional operations in those getters / setters.
The access to the class members can be direct to the class internally, as:
The reason for hiding is mainly to hide the implementation (and there's no need to hide the implementation from the class itself)
The getters and setters access the members directly, so to call them just to avoid access the members directly is somewhat, umm... redundant.
Regarding performance - I honestly think that in most cases, you shouldn't think about it, you should decide whether to call a method or access directly in terms of readability, scalability and maintenance, not in terms of whether it will take another nano second or not. This approach pays off in the long run. There are places for optimizations, and you should be efficient, but keeping your code clear and maintainable is much more important once the code base is over 20 lines.
Accessing directly is a good thing. However, no one can say getter/setter access is bad, inside the same class. If you are developing a Java bean, you will definitely understand what I am saying. Think you are trying to get the user input of a JTextField as a String. In this case, the getter methods will allow you to do lot of things including String truncating, trim, uppercase, lowercase, etc. If you are trying to do this all just by accessing the direct variable (eg: String s = textField.getText()), you will find it quite difficult to do it. So, what I think is, the good or bad depends on the situation and what you are developing
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 12 years ago.
Some might like to argue that this is a candidate for the least important issue of all times. Yet code style is a very important topic for me, and I want to ensure that I write code in a readable way - for me and the majority of developers.
That's why I'm wondering where you guys are declaring your inner classes.
I'm following the following method ordering scheme, because it is quite common:
public void foo() {
usedByFoo();
}
private void usedByFoo() {
}
public void bar() {
}
I order them from top to bottom, every method as close to where it is used.
Now I could do the same with inner classes, like this:
class Outer {
private Inner inner;
private class Inner {};
public Outer() {
}
...
}
I think this is the most consistent style to follow for me, but I've also often seen people declare all inner classes either at the top or at the bottom of the file.
Which style should I follow, given my way of ordering methods? What is the most common way to do this?
I would declare inner-classes in the bottom of the file - usually you're not interested in their implementations and just want to get to your main class' methods, so they shouldn't get in the way.
My preferred style is to put them wherever they seem to make most sense. Usually this is at the bottom so they're out the way, but sometimes I find it makes more sense to put them before a certain group of methods (if these are the methods that use the inner class.)
If the class gets too unwieldy with loads of methods and inner classes though, it's probably a bad design choice (cohesion is too low.) I've sometimes let classes get this way by accident and they're horrible to deal with later - these days if I can see one going that way I'll generally refactor it out, perhaps even into its own package. If you get to the point where you've got so many inner classes you don't know what to do with them, I'd take this approach. There's even some that advise against using inner classes at all for this reason (though I disagree - they're a valuable resource when used properly, you just need to take care they don't get out of hand.
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 12 years ago.
what is the advanrages oop over structural programming?
The main advantage that it allows you to control the complexity. You can create an object which represenets some real one, put the logic inside it and hide all the implementation details behind some interface, which is public.
That way, the client has no idea how the object is implemented but deals with public interface to control it. For understanding suggest the program interface of the car:
public interface Car {
void speedUp(int mvh);
void breakDown(int mvh);
}
Then, you can have a lot of implementations - Ferrari or WV, or something else. They all will have some implementation details, but all have the common interface, and don't need cleint to be aware of implementation details.
Object Oriented Programming has many benefits over structured programming. some of them are reusability,reliability and maintainability.OOP akso helps to reduce large to smaller more manageable problems.In terms of extensibility and reusability,for instance:"Encapsulation allows the internal implementations of a class to be modified without requiring changes to its services (i.e methods).It is also allows new classes to be added to a system,without major modifications to the system.Inheritance allows the class hierarchy to be further refined, and combined with polymorphism, the superclass doed not have know about the new class, i.e, modifications do not have to be made at the superclass"
If you understand what Object orientated programming is about the answer is self evident. OO programming is a superset of procedural code can do, so by definition it is richer in helping you solve any problem.
It allows you to define and assign responsibility for a given set of data to a given set of code, and it allows you to group responsibilities into a unified interface.
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 12 years ago.
Why is it convention to place getters and setters after constructors within classes?
I would rather see them placed immediately after class fields, before the constructors, in order to see which of the private fields are accessible via getter & setter methods. Especially if the methods' bodies are single return or assignment statements.
The Java coding convention states that methods (getters and setters are methods) should be after constructors declarations. It just a convention and it exists to make code easier to read in general.
If you judge that the code is more readable with getters//setters after fields rather than after constructor, you're free to do it.
Resources :
Java code conventions - Class and Interface Declarations
Java code conventions - Why Have Code Conventions
My take is that you have fields, then constructors, then methods so you can read through the class saying: "this is what makes up the object, this is how you build it, and having built-it here's what you can do with it".
That said, it's entirely subjective. If another layout makes sense for you and your team in your domain of interest, then do it differently. The only thing you should be wary of is making sure that your projects are internally consistent. It can be very off-putting to see code style change class-by-class.