Java: Nested classes, interfaces Vs Package [closed] - java

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I was reading nested classes will enable group classes & interfaces logically.
I feel this we can achieve using package as well by placing related classes in a package.
If this is the case, where exactly the Nested class and Nested interface come into play? When should we consider using them?

There is one main thing that you can do with nested classes/interfaces, that you cannot do with packages: You can have types that are private to a specific class. Standalone interfaces and classes can only be public or have the default (package-wide) visibility. This can be quite helpful if you wish to limit the access to the internals of an implementation.
In addition, non-static nested classes will contain an implicit reference to the parent object. This reduces the amount of code that you need to write - no need for parameterized new MyObject(this) constructor calls - although it may also increase the size of a type inadvertently if the parent object field is not used.
I would say that to a degree the use of inner classes is a matter of design and personal preference. For example, in my own projects I often choose to split-off an inner type to a separate file when its code becomes too large for my tastes. In public objects, however, the need to hide the details of an implementation may be more important.
PS: By the way, the Java compiler creates a separate class file for each type anyway - from the POV of the JVM whatever you do is mostly the same...

Let's look at a grouping.
class Container {
public class Item {
... can use Container.this to access its container.
}
private List<Item> items = ...;
public Item createNewItem() {
Item item = new Item();
items.add(item);
return item;
}
}
The interesting design offers to every Item the access to the Container it is in.
The same mechanism is used in standard java SE with Iterator implementations. The implementation class often is an embedded class of the collection, thus having access to it.
I do not know the context of your citation, but that might be what was meant.
This pattern allows access to private members of the containing class, and the alternative would need an extra constructor argument to maintain a link to the containing object.

Nested classes (that are not static) have access to instance fields of the outer class that non-nested classes wouldn't have.
You can declare a nested class or interface to be private. This is useful when the implementation of a class benefits from defining other classes or interfaces; since the class or interface is an implementation detail, it should be hidden from clients that use the outer class. You can't do this if the class or interface is at the top level. (You can make it package-private, but it will still be visible to other classes in the same package, which may not be desirable. I think it depends on how tightly the implementation of the nested class is coupled to the implementation of the outer class. If the code in the nested class doesn't make sense independently of the code in the outer class, then it should probably be nested.)
Other than those, it's a choice of how to name things. In Android, many classes that extend View have their own nested LayoutParams classes (over a dozen of them). I suppose they could have put all those classes at the top level and given them names like AbsListViewLayoutParams, TableRowLayoutParams, etc. (instead of AbsListView.LayoutParams, etc.), but the actual choice makes it clear that these are classes with similar purposes that are closely related to their "parent" classes. Setting up 17 packages or so to group those related classes together could have caused some other problems (perhaps they would no longer be able to access package-private members of other classes that they needed), and seems obnoxious even if it doesn't create this kind of problem.

Related

Is it meaningful to have abstract classes just for purpose of layering structure? [closed]

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 3 years ago.
Improve this question
Assume a Java class (e.g. a helper class), which has a great bundle of methods that could be separated into different layers. By layers, I mean the design of clearer responsibilities for each class and a reduction of complexity. Is it meaningful in this case, by using abstract class, to achieve the goal, in the sense of clean code and software design?
I encountered the situation in a project where there is a helper class having too much complexity and simply too many rows. The class is somehow playing vital roles, acting as a kind of type helper assisting other objects to fetch and manipulate type information. Each time a new/existing type would need extra type info, this class comes into help, therefore becomes heavier and more complicated in implementing methods. Though I can surely categorize and separate those methods into many classes. I found there be a structural correlation between those methods. Please see the code example below:
Assume a Type can have some TypeProperty:s. Assume also in code that there are a Type class and a TypeProperty class, both with essential getters and setters, meanwhile a Helper class Helper.
public class Helper{
static final T CONSTANT_A = new A(...);
static final T CONSTANT_B = new B(...);
final Type theType;
//constructor etc.
Type getType(){
return theType;
}
Type getTypeByKey(Key typeKey){
//...
}
Collection<TypeProperty> getPropertiesByType(Type t){
//...
}
Collection<TypeProperty> getProperties(){
return theType.getProperties();
}
TypeProperty findSpecificPropertyInTypeByKey(Key propertyKey){
Set<TypeProperty> properties= theType.getProperties();
//loop through the properties and get the property,
//else return null or cast exception if not found
}
boolean isTypeChangeable(){
return findSpecificPropertyInTypeByKey().isChangeable();
}
//many more methods
}
I expect to refactor the Helper class so that the code is easier to maintain and expand, as well as, to be less complex. I think it is possible to separate the methods into different classes, however, this might lead to too many classes and the responsibilities are not straight-forward as they are not in a helper class(es). While in the meantime, the idea of utilizing abstract classes comes into my mind. Would it be meaningful then? Say that after refactoring, there would be
a TopLevelHelper having methods revolving the type itself, e.g. isTypeChangeable & getType(), as well as, all Constants;
a SecondLevelHelper extending TopLevelHelper, which bears the logics as middleware, e.g. getProperties and getPropertiesByType;
a LastLevelHelper extending SecondLevelHelper, which does the concrete and detailed works, e.g. findSpecificPropertyInTypeByKey.
Though none of these classes would have abstract methods but concrete implementations since none of the methods in higher-level helpers would be overridden. It does not seem that such a design is appropriate usage of abstract classes, still, I feel it separates responsibilities into three layers. Should it be done like this or should other techniques be used in this situation?
There's no definite answer of course, but I think you should stick with what you have. Abstract classes are mostly meaningful for implementing template methods and similar patterns. Splitting a class on different hierarchy levels does feel weird in your case, because the methods do seem to belong to different groups, rather than different levels. If java allowed multiple inheritance, traits, or something similar, you could make the mixin classes.
However, a class with multiple methods is fine. Although OOP design guidelines often say you should limit your class to eg 5 method, you class seems more of a smart data structure than a class, and your methods are mostly accessors and properties. So, since they are simple and conceptually similar, there's no real problem having many of them. Java itself does it all the time (for example, see string & collection classes reference).
I would say that layering is not a good approach.
From what you are saying about that 3 layers, they have different responsibilities. If all this 3 responsibilities are coded in the same class, it breaks the Single Responsibility Principle. So the solution that naturally follows is to split each one in its own class and use composition. By doing this you also adhere to the principle that says composition is preferable to inheritance.

How interfaces in java used for code reuse? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I am learning java, and came to know that Java doesn't support multiple inheritance. So, java introduced interfaces for that. How does the problem of multiple inheritance is solved by interface?
What I read online : "Inheritance in java means code reuse".
If i implement an interface in class say A, I will have to give my own implementation for it in A, and same in B, which means methods in interface (say I) will have different implementation in A and B. How does it use the code re-usability feature?
You haven't given proper citations for any of the assertions that you make in your Question, so it is impossible to know what they are actually saying ... or why you think that they are say these incorrect or misleading things.
I am learning java, and came to know that Java doesn't support multiple inheritance.
That is correct.
So, java introduced interfaces for that.
That is INCORRECT. Java introduced interfaces to support polymorphism. Specifically polymorphism that does not depend on class inheritance.
How does the problem of multiple inheritance is solved by interface?
It isn't.
Multiple inheritances are about inheritance of method and field declarations from multiple parent classes. Interfaces does not provide that, and it does not solve the problem.
Interfaces do allow you to declare a common API (or APIS) and implement that API without necessarily sharing code. But with careful design you can do code-sharing under the hood any; e.g. by using the Delegation design pattern.
What I read online : "Inheritance in java means code reuse".
I doubt that what it actually said. Anyway, it is INCORRECT.
Inheritance (of classes) is one way to achieve code reuse, but it is only one of many ways to achieve reuse. There are many others.
If i implement an interface in class say A, I will have to give my own implementation for it in A, and same in B, which means methods in interface (say I) will have different implementation in A and B.
I presume that you mean something like this:
public interface I {
void someMethod();
}
public class A implements I {
void someMethod() {
// some code
}
}
public class B implements I {
void someMethod() {
// some code
}
}
How does it use the code re-usability feature?
There is no code reuse in that example. But this is not inheritance of classes (which I described as one way to achieve code reuse). It is a class implementing an interface.
(Now in Java 8, you can put code into interfaces in certain circumstances; read up on the default methods feature. And that does allow direct code reuse via an interface. But I doubt that is what the sources you have been looking at are talking about.)
Java solved the problem of multiple inheritance (or rather the problems that come with this feature) by allowing single inheritance, that is allowing only one super class. This design created a new problem of a class that needs to implement multiple contracts. a contract, like is explained in #Kermi's answer, allows other objects to refer to the same Object as different types, for various purposes, the most common one is for storing in Collections. an interface can be regarded as a super class that has no implementation (all the methods are pure virtual if you like)
So, Java removed the problems that come with multiple inheritance (the famous diamond problem) but also the advantages that come with it such as code reusability. This design follows the principal of making Java simple and easy and predictable by removing "advanced" (some say confusing) C++ features like multiple inheritance, operator overloading, pointer manipulation (among others).
There are several technics that allow Java to restore most of the code reusability of multiple inheritance. One such technic is composition: so if we take #Kermi's example, you can have a GeneralAnimal class that implements the most common behavior of an Animal. every Dog instance holds a reference to a GeneralAnimal instance (obtained through ctor or factory or dependency injection or ...) and can delegate some messages (=method calls) to that instance. The same is done in Cat instances and so on.
Interface doesn't resolve multiple inheritance problem or rather it doesn't create a multiple inheritance problem. It gives you a possibility to reuse existing implementations.
For example:
class Dog implements Comparable<Dog>, Animal
As your class implements 2 interfaces you can use them in difeerent ways. To use TreeSet object needs to implement Comparable methods (it is not the only possibility). When Dog is passed to TreeSet implementation of that structure is then sure that object has compareTo(Dog dog) method and can use it.
But than you want to store a List of Animals, and than iterate through that list with execution method declared for Animal, than you would not use Comparable interface, but Animal.
List<Animals> animals = new ArrayList<>();
animals.add(dog);
animals.add(cat);
for (Animal animal : animals) {
animal.walk();
}
Interface is a criterion, I think.
A and B should conform to it. In addition, A and B do different things such as ArrayList and LinkedList.
"Inheritance in java means code reuse" is right, but Interface is not. It embodies a norm.
When you learn Collections, you will understand it clearly.

Understanding inner classes (Why inner classes exist) [closed]

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 6 years ago.
Improve this question
I was reading Thinking in Java, about why inner classes exist and what problem they help solve.
The most compelling reason the book tries to give is:
Each inner class can independently inherit from an implementation.
Thus, the inner class is not limited by whether the outer class is
already inheriting from an implementation.
Please help review my understanding:
Inner classes exist since Java doesn't support Multiple Inheritance. This (multiple inheritances) can be done within an Inner class which it is that the Outer class can have multiple inner classes, and each of them can inherit from different classes. So in this way, The multiple inheritances can be implemented. Another reason I can think of is Inner classes address the OOP design principle composition better than inheritance.
Updated
Most of the explanation I found just like the answers below. for example, Inner class used in the GUI framework to deal with the event handler. Not mentioned the reason quoted in the book.I am not saying the answers below are not the good. Actually. I really appreciated them(+1). I just want to know Is there something problem with the book?
It is a little puzzling why you thought of the idea of multiple inheritance after reading the most compelling reason you have quoted from the book. Multiple inheritance comes into question when a class (inner or not) wants to inherit behavior from more than one concrete implementation. Thus, unlike some other languages, in Java, you can not define a class like:
class Child extends Father, Mother {
// Child wants to inherit some behavior from Father and some from Mother
}
As you can see, nothing that only inner classes do can rectify or work around this Java decision (not to support multiple inheritance) in a straightforward way.
Then why do they exist, you may wonder! Well, in Java every class is either top-level or inner (also called nested). Any class that is defined inside another class is an inner class and any class that isn't so is a top-level class.
Naturally, one might wonder why to define classes (i.e. behavior) inside other classes. Aren't top-level classes enough?
The answer is yes. Java could always have only top-level classes. But the idea (perhaps) was there was no good reason to restrict classes from being members of other classes! Just like any predefined type (e.g. Integer, String etc.) can be a member of a class:
class Person {
private String name; // a field the models a Person's name
}
a programmer should be able to define a behavior of one's interest inside the class:
class Person {
private String name; // a field the models a Person's name
private Address address; // address is a type defined here
static class Address {
String street;
String city;
}
}
There's a lot going on here, especially with these things like private, static etc. which are called the modifiers. There are many technical details about them, but let us come back to them later. The essential idea is to be able to define behavior as a part of another class. Could the Address class be defined outside Person class, as a top-level class? Of course. But having this facility comes in handy.
Now, since this facility was introduced, it started serving another purpose and that purpose is called providing code as data. This is how design patterns emerge and it was thought until about 10 years ago that inner classes can be used to provide the data in the form of code. Perhaps this is somewhat puzzling to you. Consider the following code that I have taken almost verbatim from the JDK class: java.lang.String.java:
public static final Comparator<String> CASE_INSENSITIVE_ORDER
= new CaseInsensitiveComparator();
private static class CaseInsensitiveComparator
implements Comparator<String> {
public int compare(String s1, String s2) {
int n1 = s1.length();
int n2 = s2.length();
// details excluded for brevity
// return -1, 0, 1 appropriately
}
}
What has happened here?
We need a way to compare a String to another String and we need to be able to do a case-insensitive comparison. So, we created an implementation of the Comparator interface right inside the outer class: String! Isn't this handy? If inner class wouldn't be there, this would have to be:
public class String {
// ... the whole String class implementation
}
class CaseInsensitiveComparator
implements Comparator<String> {
// implements the comparator method
}
and that's not 'bad' per se, but it means a lot of classes polluting the name space. Inner classes restrict the scope of a behavior to the outer class. That comes in handy, as you'd perhaps see. The data in this case is the implementation of the Comparator interface and the code is well, the same, because we are _new_ing up the inner class we defined.
This feature was exploited further using the anonymous inner classes (especially in the cases where you wanted the code to serve as data) up until Java 7 and they were effectively replaced by Lambda Expressions in Java 8. Nowadays, you might not see any new code that uses anonymous inner classes (in other words, language evolves).
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.
Oracle Documentation: Understanding inner classes
Below SO question might be interesting to you -
What is the reason for making a nested class static in HashMap or LinkedList?
UPDATE
Not mentioned the reason quoted in the book. ... I just want to know
Is there something problem with the book?
I don't think there is any problem with the statement you have highlighted.
Each inner class can independently inherit from an implementation: That's true right. Just like an outer class, it can inherit from an implementation independently. Just think both of them as separate class.
Thus, the inner class is not limited by whether the outer class is already inheriting from an implementation: As both are separate class, it doesn't matter whether outer class is already inheriting from an implementation. Inner class can inherit from an implementation too. After all it's a class too.
If you are looking for use-cases, I can only tell you what I use them for frequently, which are basically these 2 things:
Static inner classes I use for helping to implement some internal logic. These are usually some form of tuples, or some simple containers. For example: Maps have "Entries" in them which are basically just pairs.
Representing runtime parent-child relationships. These are non-static inner classes. For example: I have a Job class which may instantiate multiple Task inner classes that need to see the data in the job for their processing.
There may be more use-cases of course...

to use procedures from a class, when is the best time to extend a class vs. create an instance of that class? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
In Java, I created a class CommonExcelFunctions to store procedures I use across a couple projects. there are no abstract procedures in the class. To use these, I'm trying to decide if I should make my other projects extend this class, or if I should instantiate it and access them all through the instantiated object. which way makes the most sense?
Never ever use inheritance just for the sake of code reuse. The subclass relationship should be a meaningful is-a relationship, especially in a language like Java where you have only single-inheritance.
For such utility functions you describe static would probably best. Otherwise, use composition, i.e. create a member.
Similar to what #AlexisKing mentioned, I often will create a utility class (such as ExcelFunctionsUtil and create a bunch of static methods in there. This is nice when the code is to be reused in multiple places, but inheritance doesn't make sense. I think inheritance only makes sense if the sub-class could actually be considered an extension or child type of the parent class. For instance, if you created an UncommonExcelFunctions class, that would seem to be an appropriate child of CommonExcelFunctions, but an Accounting class would not make sense.
Normally when in doubt, we ask ourselves the basics. Are we having a is-a relationship or has-a relationship.
If your new classes is indeed having an is-a relationship with your CommonExcelFunction class, then you probably can extends it.
So that answers your first question - best time to extend a class.
Else if it acts like a utility class, and some examples like those provided in Java (Example: Math.max, Math.min). You can implement your methods in the class as static (No instantiation required for usage of method).
Think about this:
Scanner scn = new Scanner(System.in); //Scanner class using instance methods
Math.max() //Math class using static methods
Why would Java want to implement the methods in Scanner as non-static while in Math class as static? You probably know the answer if you spend some time to think about it.
It is not necessary if you have some methods that we want to use directly for example (get the exponent of a number, get the max of 2 numbers, rounding off a value..etc).
However it makes more sense to create instance methods (E.g. Scanner class) when we may need more than one type of scanner (Example: scanning console input, scan from file).
You should always prefer composition to inheritance.
Your new class is not a 'CommonExcelFunctions' it just uses functions from CommonExcelFunctions.
You probably will not call functions from CommonExcelFunctions on instances of your new class. There's no need to pollute interface of your new class with methods from CommonExcelFunctions. It would break encapsulation.
When you use composition you can easily tests classes that use CommonExcelFunctions passing a mock.
When you use inheritance it's very difficult to test your class (partial mocks suck).
For example go language does not support inheritance at all.
See Effective java, item 16 "Favor composition over inheritance".

Purpose of having super class as an abstract class in Java [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Super class being an abstract class creates an overhead for all its sub classes to compulsorily define its abstract methods. I understand that it's very basic but I need to know why do programmers usually make super class as an abstract class, though we can do similar things using a super class as a non abstract class.
An abstract superclass is one way to provide re-usable code.
You can extend the abstract class and inherit the code. This is sometimes more convenient than using static methods or object composition to share code.
The abstract class can "fix" parts of the code (by making it final). This is called the "template method" pattern (and this is not possible with an interface, which cannot provide final methods).
Of course, you can achieve both with a non-abstract superclass as well.
An abstract class has the additional benefit that it does not have to provide a complete implementation (that would make sense to instantiate on its own), some parts can be left specified, but unimplemented (the abstract methods).
imagine you have a common behaviour where only small details are specific to the implementation - then you can put all the common behaviour in a abstract base class and having some abstract methods that the implementing classes need to fill.
For example a abstract repository base class might implement all the details to contact your server, etc. and concrete repositories just need to fill in the details to read the right object from the right table, etc.
Abstarct classes are meant for 'abstracting'. means if some classes are having common behaviour, instead of writing evry time the same thing in each class, write that in one class and ask the other classes to use it [by making the classes as subclasses to the abstract class]. This is nothing but inheritance. To summarise: Use abstract classes when you want default behaviour for some classes Use interfaces when you want different behaviour different classes.
For More explanations Refer below links:
http://www.javacoffeebreak.com/faq/faq0084.html
http://docs.oracle.com/javase/tutorial/java/IandI/abstract.html
several usage of abstract class:
act as the protocol when tranfering data between objects, the two customers need not to know other class's structure. ----- just like the interface
define the abstract operation, which hides the detailed implementation of concrete class, for example, I have a class called AbstractPayment, which define the opration of charging money from customer, then the concrete classese of it could be: PaypalPayment, AlipayPayment, BankPayment and others. BUT, for the class customer, it only needs to know the AbstractPayment.
after some time, if you need to add another ConcretePayment, or modify one other payment, the customer class won't change.
Abstraction is largely used in design patterns, I suggest you to read following:
Abstract Factory Pattern
STO

Categories

Resources