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...
Related
If i have this code:
public class MySuperClass {
public String superString = "hello";
public MyChildClass makeChild() {
return new MyChildClass();
}
public class MyChildClass {
public String childString = "hi";
}
}
How can i get the MySuperClass instance from the MyChildClass instance?
Because i have this error:
There are VERY similar questions around stackoverflow, but this isn't a duplicate of any of them.
What is the mistake in my code? How can i achieve what i said above, without making a method in the nested class which returns MySuperClass.this ? Imagine i do not own the code of MySuperClass...
I think this can be done because in the MyChildClass i can access the super instance with MySuperClass.this, how can i get the MySuperClass instance attached to the child, from outside of the child class?
EDIT: i know casting is not the way to achieve this, it was an attempt to achieve what i wanted
You're mixing terms. "Child class" is pretty much always used for this relationship:
public class Parent {}
public class Child extends Parent {}
(And 'Parent' here, is termed the 'superclass' of Child).
In that context, 'how can I get my superclass from my child class' makes no sense. Child is an extension of Parent, when you write new Child() there is just one instance, and that one instance is a combination of the stuff in Child and in Parent. It's not 2 separate things.
What you're talking about are inner classes. This relationship:
public class Outer {
public class Inner {}
}
Inner/Outer, vs. Child/Parent or Sub/Super.
So, what you actually ask is: How do I get the outer class instance?
That is not possible. It is an implementation detail of Inner, and it is up to Inner to expose this. If it doesn't want to, you don't get to access it.
But there are hacks and workarounds.
Option #1: The code in Inner itself can do it
Within the {} that go with class Inner {} you can do it:
class Outer {
class Inner {
public Outer getOuterInstance() {
return Outer.this;
}
}
}
Option #2: Hack it
At the class/JVM level, inner/outer classes don't exist. They're all just classes. That's why, if you compile the above, you end up with 2 class files, not one: Outer.class as well as Outer$Inner.class. The outer instance that Inner has is represented by a field.
This field is generally called this$0, and is package private. So, something like:
Field f = Inner.class.getDeclaredField("this$0");
f.setAccessible(true);
Outer outer = (Outer) f.get(instanceOfInner);
But, in case the reflection code didn't already spell this out for you: Don't. This is horrible idea. A SecurityManager can stop you. The code is hard to read, this$0 doesn't make sense unless you riddle this with comments explaining what you're doing. Most of all, like any reflection, this is flat out not something the author of Outer/Inner intended for you to do, and whatever you use Outer for may simply not 'work' properly in some minor point release down the road, because you're not using this library in its intended fashion, therefore any support offered for it is lost. You pave your own road, which is bad, because you have no idea what the author truly intended, and you now effectively have to say that your libraries must never be updated without extensive testing, and not updating is a great formula to get yourself hacked. It's a bad idea in so many ways.
Also, the significantly reduced care for backwards compatibility as expressed by the current OpenJDK team (see project jigsaw which was the most breaking release of java in a good long while, how OpenJDK team almost decided to get rid of the SecurityManager within a single version jump until called back by the community, aggressive expansion of mostly pointless 'opens' checks, and more) - means that if you rely on this, don't be surprised if java18 or what not breaks your ability to do this, permanently.
So, do NOT do this.
Caveat: non-static inner classes bad.
The idea that the inner class actually has an invisible field of type outer is annoying and surprising. It stops garbage collection. It confuses your average java programmer because 'using' this java feature the way it was intended is very rare.
I therefore strongly suggest you always make your inner classes static, and if you really want an instance of Outer, make it explicit: Make Inner static, then give it a private final Outer outer; field.
It's equally efficient, it's very slightly more typing, but it is a lot more readable.
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.
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 9 years ago.
Improve this question
I was trying to understand when it can be useful to create an abstract interface.
I know that if you create an interface the methods have to be public, so is nice for a service. But what happens if service is an abstract interface? Does that make sense?
If I create a service declared abstract interface and some methods are private, the class that implements this interface sees the private methods and the other (another application's or similar) doesn't see this methods, correct?
I this is a correcte implementation?
Finally after a lot of people that can sleep by my fault I write my solution, ty for waiting.
package cat.base.gpt.domini;
public interface IExpMS extends Serializable{
... methods here..
}
public interface IExpMSDetallGIM extends IExpMS {
more methods here..
}
public interface IExpMSDetallOGC extends IExpMS{
..no methods just inheritance.
}
package cat.base.gpt.domini.impl;
import cat.base.gpt.domini.IClauExpedient;
import cat.base.gpt.domini.IExpMS;
public class ExpMS implements IExpMS{
..atributs and #overide methos interface
}
public class ExpMSDetallGim extends ExpMS implements IExpMSDetallGIM {..}
public class ExpMSDetallOGC extends ExpMS implements IExpMSDetallOGC {..}
*every method is public, atributs are private. maybe i can write methods in the interfaces protected, but i'm not really sure...if someone needs to see full code i can't post or send by email.
if ypu wanna see the databasze views to think about my solution here there are:
![IExpMSDetallGIM4
ty.
Interfaces are always abstract. They define the interface of a class, so they are only about public methods, regardless the language, I think.
And while private methods are implementation detail and NOT the interface, they cannot be declared in an interface.
If you want a private method to be the same in a set of classes, you can create a base abstract class with protected methods.
Abstract means "you cannot create a member of this type".
Interface is just a description of some of the classes' properties. They are always abstract, while you cannot create an instance of an interface.
Look at the link http://www.ronaldwidha.net/2008/06/16/a-good-example-of-abstract-class-vs-interface/ - it describes the code in C#, but it's the same thing, only the keywords differ.
i'm working with java..is the same?so interface = abstract interface?
In Java 7, yes. In Java 7 (or earlier) an interface is implicitly abstract. The interface itself does not include bodies for any of the methods that it specifies, so it makes no sense to create an instance.
In Java 8, it is possible to include default methods in an interface. These default methods have bodies with executable code in them, but (naturally) they cannot refer directly to the state of an instance. (Instance state variables are declared in the classes that implement interface ... and the default methods can't refer to stuff that has not, and may not ever be declared.)
However, you still cannot create an instance of a Java 8 interface, so it is still abstract in the sense that an abstract class is abstract.
You then ask this:
If I create a service declared abstract interface and some methods are private, the class that implements this interface sees the private methods and the other (another application's or similar) doesn't see this methods, correct?
That is correct ... but it is nothing to do with what the abstract keyword means in Java. In fact, that is describing how all Java classes behave ... vis-a-vis the visibility of private members.
The primary purpose of interfaces is to allow multiple different implementations of "the same thing". The user of the interface is not dependent on the particular implementation and this allows for good separation of concerns. New implementations can be added later and the program can be extended, without ever need to modify the code that is using them.
Imagine how you would write a program for summing up numbers from various data sources. You could write one separate program for every type of data source (e.g. csv, xls, database table). But then, the "summing up" logic would be repeated. If you wanted to add a new data source type, you'd have to write a whole program from scratch.
Interfaces allow to make it more flexible. You realize, that your summing up logic needs to operate on a list of numbers. It doesn't care where those numbers come from. So you define an interface:
interface NumberListProvider {
List<Double> readNumbers();
}
Then you make your whole complex algorithm dependent only on this interface and you provide different implementations (concrete classes), reading the numbers from csv, xls or various databases.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
I'm learning java and was wondering in what situation you would want to extend a class like here is suggested:
http://5upcodes.blogspot.fi/2013/08/java-inheritance.html
Thanks!
My favorite example of inheritance is the shapes example. All squares are shapes, but not all shapes are squares.
Assume you have a class called "shape". All shapes have perimeter, area etc. These would be the data members of your shapes class.
lets say you wanted to create a class called circle. circle could extend your shape class, so that it would still have the data members of the shape class, and you could add elements that are specific to the circle, such as a radius. (a square wouldn't have a radius).
The circle class would be said to "inherit" from the shape class, because it has all of the features of a shape, and also new features specific only to the circle class.
When you want to create a class that is generally similar to the super class(the class being extended), you extend it and customize it. Overwriting some of it's functions, and/or add functions.
This is a "is-a" scenario, one of the three OOP pillars (inheritance, encapsulation, polymorphism). If you have a class Animal, then you may want to extend a Dog class from Animal. A dog is an animal, but not the other way around. All animals have cells, but dogs have other features aside from that. That'd be a pretty basic idea of it.
The OOP good practice is to program towards interfaces. But in some cases you can take advantage using inheritance: for example, when your top class has a well-defined behavior (i mean concrete code), which all the child classes will inherit - this reduces code, complexity and give you a better maintenance scenario.
In the other hand, if your model is too abstract (the basic behavior is not very clear), then you should think about using interfaces.
And if you're creating real-life software, don't forget design patterns - someone may already solved your problem.
For simple reason we extend one class two another and the funda is called as INHERITANCE.
Say,if you want to create a program in which there are two vehicle class i.e.- Car and Boat, which has similar properties except some.
public class Vehicle
{
void engine()
}
protected class Car extends Vehicle
{
void tyres()
}
protected class Boat extends Vehicle
{
void propeller()
}
You see both vehicle has engines but has different modes as one moves with the help of tyres and another with propeller.
So, two avoid re-writing code of method engine, we inherited it in sub-classes.
Hope, this will help ya !
Extending class is one of basics of OOP, along with interfaces. Lets say, you have general class called Building. It has members like area, city where building is (or coordinates) etc.
Now, with extend, you can specify house to "Cottage", "SkyScraper" etc. They will have functionality of parent + something more (eg. number of levels for SkyScaraper).
The primary reason to use inheritance is to extend behavior of the base class.
For instance, if you're making a video game you might have a Character class that contains all the code needed for a character to navigate the world and do whatever else they do.
You could then extend Character with Player and NPC, so that Player (representing the player character) contains the logic that allows the person playing the game to control their character, and NPC (representing a Non-Player-Character) contains the logic allowing the computer to control the other characters. This way, all of the logic core to every character is encapsulated in the Character class, and the subclasses only have the logic needed to extend specific behavior.
For example, the Character class might have a method for movement.
protected void MoveToLocation(x, y)
{
//movement logic goes here
}
And then the Player class might contain a mouselistener to move the player to wherever is clicked.
public void mouseClicked (MouseEvent mouseEvent)
{
MoveToLocation(mouseEvent.getX(), mouseEvent.getY());
}
And NPC will figure it out on its own somehow
protected void decideWhereToGo()
{
int destinationX, destinationY;
//logic for determining destination
MoveToLocation(destinationX, destinationY);
}
Because they both inherit from Character they both know how to MoveToLocation, and if you ever want to change how that is done you only have to modify the code in one place and every Character (whether they are a Player or NPC they are still a Character by way of inheritence) will have the updated behavior.
When you extend a class, you have a parent-child relation between the original one and the new, extending one.
The child class, the one extending the parent class, will have each and every member of the parent class, without the need to declare them again. Even the private members, though you won't be able to access them directly.
You extend a class when you want the new class to have all the same features of the original, and something more. The child class may then either add new functionalities, or override some funcionalities of the parent class.
You may also use extension when you want to have a set of classes that are related and share some common functionality, but with different implementation when it comes to the details. For example, usually for graphical interfaces you have a Control class, which has functionalities related to rendering and positioning. Then you have its children called Button, Textbox, Combo etc. All have some implementation in common, but each is different in their details.
Make sure to study about interfaces, too. Sometimes you want a lot of related classes so that they have a common set of members, but no shared functionality. In cases like that, it may be better to implement an interface than to extend a common class. An interface is like a class, but with no implementation in it (it serves only to tell you which members its implementors should have).
Generally extending a class is so that you are creating class based on something. For example, in order to create an activity, you must extend Activity. If your class is to setup a IntentService, then you must extend your class to use IntentService.
public class AClassNameHere extends Activity implements OnClickListener {
public class ClassName extends IntentService{
You can extend the superclass to Override super class method to be specific to sub class
example:
In case your superclass is a generic class with generic behaviour, eg Animal class can be a generic class like
class Animal{
private String name;
public String getVoice(){
return "Animal";
}
}
Now you need to create say a class Cat which is of Type Animal but with different voice then you just extend the superclass Animal and just override the getVoice() method
like
class Cat extends Animal{
public String getVoice(){
return "mew";
}
}
Now if you have code like this:
Animal cat= new Cat();
cat.getVoice();//it will return "mew"
Practically this you can use in number of situations like
1. Extending an existing framework class to your custom class.
2. If you are developing any framework you can expose some classes which you want the user to customize.
But overriding introduces IS-A relationship.
There are three major drawbacks with inheritance. Even though the relationship is an "is a" relationship, consider these three while deciding to inheriting a class.
Partial inheritance is not possible. You can't extend partially.
It is statically linked. Inheritance relationship is static. You can't change that relationship at runtime.
You can't restrict the behavior through inheritance. (That is possible in C++ through private inheritance. But not in java )
Almost never. It's best only to extend classes that have been actively designed for it. Most class implementors give no thought to what will happen if people extend their classes. There are all manner of issues.
Composition is your best friend.
Vulnerabilities include
you can no longer correctly implement equals() or hashCode() in subclasses
you are violating encapsulation, and now rely on the internals of another class
you are vulnerable to changes in the parent class
you are required to accept any new methods that get added to the parent class
you must worry about the Liskov Substitution Principle, which can lead to subtle bugs
Josh Bloch, in his excellent book Effective Java, 2nd Edition, talks about this in several places, including items 8, 16 and 17.
considier, I am writing a code for class GUIManager of simple MineSweeperGame.
Here,
class GUIManager{
class GameBoardManager{...}
class IconManager{...}
class BoardMenuBar{...}
class BoardManager{...}
class DataManager{...}
}
But the real uneasy thing I felt is,
I need exactly one instance of every inner classes.
I made those inner classes only to promote grouping and readability
There is no way to communicate this information(given in blockquote) with the future-developers of this code.
Hence my question is,
Any special type of classes is possible such that only one objects of that class can be created? i.e creating 2 objects will give compilation error. or what I must do now to insist the (blockqouted) information.
Making the scenario worse,
public class GUIManager extends JFrame
{
final GameBoardManager gUIGameBoard;
final BoardMenuBar menuBar;
final GameInfoDisplayer gameInfoDisplayer;
final DataManager dataManager;
final IconManager iconManager;
.....
}
while accessing the elements, I have to use, gUIGameBoard.boardButton[][] , gUIGameBoard.dimensionOfBoard , gUIGameBoard.boardColor etc...
While accessing in this way, it sounds like.. I have many objects for GameBoardManager and here I am accessing the element of gUIGameBoard. But the real fact is there is only one GameBoardManager is only possible for a GUIManager. This is the similar case to other inner-classes object too.
Hence my question is?
I must have only one GameBoardManager for a GUIManager, Whether is it possible to group related items without creating a inner-class. Since, while accessing inner-class object it sounds like I am having many.
If the constructors of all your inner classes are private, nobody other than GUIManager will be able to instantiate one. Add a comment and this is a reasonable approach.
However, your class may need restructuring - that's a lot of inner classes!