Is there a way to refer to any inner class?
I would like to specify a return type compatible with an inner class e.g.
Class<OuterClass.*> some_method();
I understand this syntax is invalid. Is there a way to express this?
I know I can't use something like Class<? extends OuterClass> because an inner class doesn't extend an outer class.
Well, you can refer to specific inner classes, at least:
<T extends OuterClass.InnerClass> Class<T> some_method()
Besides that, what would you gain by returning an object of any inner class? That would be comparable to returning any object plus the fact that the inner instance has a special relation to the outer instance. However, you'd probably not be able to directly use that special relation anyways.
Edit:
As others pointed out already InnerClass might be a super class extended by other inner classes. This would allow you to return any class, that extends that class.
If you'd use an interface, you aren't restricted to inner classes only, since for this restriction you'd need non-static inner interfaces. However, inner interfaces are static by default.
I would rather define an (inner) interface, let all inner class implement it, and then :
Class<OuterClass.MyInterface> someMethod();
This would be more type secure than trying to refer to any inner class. And you wouldn't have any problem the day you need another inner class for another usage, or the day you decide to extract a class.
No there isn't. Just as you cannot reference packages with wildcards:
Class<com.example.*> some_method();
Class<com.example.?> some_method();
The use cases for such declarations would be so limited, it just wouldn't make it into the JLS. Note, you cannot use such "location match types" outside the scope of generics either. E.g. you cannot declare:
void some_method(OuterClass.* argument);
void some_method(com.example.* argument);
Class<InnerClass> is allowed in java. Are you looking for something specific?
public class Client
{
interface InnerType
{
}
public class InnerClass implements InnerType
{
}
public Class<? extends Client.InnerType> test()
{
return InnerClass.class;
}
}
You can define marker interface and Implement it by Inner class.
<T implements CustomMarkerInterface> Class<T> some_method()
So this would be applicable to all inner classes of OuterClass
public class Outer {
public class Inner implements CustomMarkerInterface{
}
public class Inner1 implements CustomMarkerInterface{
}
public class Inner2 implements CustomMarkerInterface{
}
}
Related
According to this document, and many similar documents, a concrete class is described as:
A concrete class in Java is any such class which has implementation of all of its inherited members either from interface or abstract class
And can used like this:
public abstract class A {
public abstract void methodA();
}
interface B {
public void printB();
}
public class C extends A implements B {
public void methodA() {
System.out.print("I am abstract implementation");
}
public void printB() {
System.out.print("I am interface implementation");
}
}
In the above example class C is a concrete class.
Is this the only way to create a concrete class. Can you give me more info about concrete class?
A concrete class is a class that has an implementation for all of its methods that were inherited from abstract or implemented via interfaces. It also does not define any abstract methods of its own. This means that an instance of the class can be created/allocated with the new keyword without having to implement any methods first. Therefore it can be inferred that any class that is not an abstract class or interface is a concrete class.
In your code above, C will be a concrete class as it implements all abstract methods inherited from A and implemented from B. Also, it does not define any abstract methods of its own.
The simplest definition of a concrete class is that it's a class that is not abstract.
As per name suggests, concrete means Solid, it means having no any row part or unimplemented things(methods).So we can conclude that concrete classes are those classes that can be instantiated with new key word.
MyClass myClass = new MyClass();
1.concrete class is a class which can never become
an abstract or interface .It can extend or implement or both.
2.The class is said to be concrete if all its methods and variables has defined.
A concrete class in Java is any such class which has implementation of all of its inherited members either from interface or abstract class
In the above program, representing abstract as public class will sometimes show some compile time errors to define that in its own file. As simple, just avoid using public keyword or modifier while using abstract class in your program to avoid some uncertainty. Any method that is invoked using new keyword (object creation) other than abstract and interface classes is called as concrete class.
I am making changes to a Java class of ours, and I noticed the following line of code:
OurClass<OurInterface1> ourClass = new OurClass<OurInterface1>() {};
What I find strange about that line is that OurClass is an abstract class - here's the definition of OurClass:
public abstract class OurClass<T extends OurInterface1> implements OurInterface2<T>
When I remove the {} at the end of the line, Eclipse tells me Cannot instantiate the type OurClass<OurInterface1>, but when I put the {} back, everything is OK.
How does {} allow you to instantiate an abstract class?
Adding the {} introduces the syntax for an anonymous inner class.
The anonymous class expression consists of the following:
The new operator
The name of an interface to implement or a class to extend. In this example, the anonymous class is implementing the interface HelloWorld.
Parentheses that contain the arguments to a constructor, just like a normal class instance creation expression. Note: When you implement an interface, there is no constructor, so you use an empty pair of parentheses, as in this example.
A body, which is a class declaration body. More specifically, in the body, method declarations are allowed but statements are not.
You are declaring an anonymous inner class that subclasses OurClass. The body of this class is empty: {}. This anonymous inner class is not abstract, so you are able to instantiate it.
When you remove the {}, the compiler thinks that you are directly instantiating OurClass, an abstract class, so it disallows it.
You can actually extend and override methods on the fly when you instantiate off an interface or extendible class. This is called an anonymous inner class.
What you did in your example is create an anonymous inner class, but it had no effect because you didn't override anything. You could have put overridden methods in those curly brackets {}.
OurClass<OurInterface1> ourClass = new OurClass<OurInterface1>() {};
A commonly applied use of anonymous inner class is on the Runnable interface, which defines a single void run() method. You can implicitly instantiate an object that implements Runnable and override run() on the fly.
Runnable someTask = new Runnable() {
#Override
public void run() {
System.out.println("Running a task!");
}
};
Anonymous inner classes are disliked by a lot of developers because they are pretty verbose. Fortunately in Java 8, you can use lambda expressions to replace most anonymous inner classes that implement a single method. The compiler infers the anonymous inner class for you basically, allowing you to write the code more concisely.
Runnable someTask = () -> System.out.println("Running a task!");
The block after the call to the new operator (new OurClass<OurInterface1>() {}) is infact creating an instance of an anonymous class which extends OutClass.
Since this class is no longer abstract, there's no problem to instantiate it.
You cannot instantiate an abstract class without implementing the abstract functions within the class. This is usually done by instatiating abstract classes with implemented class.
Refer: https://docs.oracle.com/javase/tutorial/java/IandI/abstract.html
In your case, the {} used after the instantiation allows you to implement any of the abstract functions in the abstract class.
For example,
Consider
public abstract class DummyClass {
abstract void test() ;
}
is the abstract class with a abstract function.
The class can be initiated by:
DummyClass d = new DummyClass(){
void test(){
//test() implementation here
}
} ;
Hope this helps! :)
What does it means to declare a non-static inner class as final?
I have tried many links on google and stackoverflow.com as well but all of them seem to be dealing about inner classes accessing final members not final inner classes itself.
I found this link on google but even it doesn't explains it.
Thanx in advance!
There is no semantic difference between making a top-level class final and making an inner class final: it tells the compiler that you cannot inherit from the class. Marking classes final is sometimes done to let the compiler skip a virtual table lookup, but this is often regarded as premature micro-optimization.
It has the same semantics as an outer class being declared final: the class cannot be extended.
Consider this example:
public class MyClass {
public class A {
}
public class B extends A {
}
}
If you add the final modifier to A it will generate a compilation error.
Well, inner classes are not any way different from outer classes in that context. So the following code is perfectly valid.
class Outer {
int some_member;
class Inner {
void method();
}
}
class OuterExtendsInner extends Outer.Inner{
}
As we all know, the purpose of declaring a class final is that we prevent any outside intruder from subclassing the class and exploit its facilities, the same way we can do in case of inner classes.
I'm trying to use extends (inheritance) in Java. I made a quick abstract class to extend from, and then extended it. However my IDE now is saying that "An enclosing instance that contains abstract_class is required" and gives my constructor for the derived classes big error lines. What on earth is it going on about? The abstract class doesn't have or need any sort of constructor.
Just for reference, I'm using extends rather than implements in part because the implementation details that I don't want to have to maintain for every derived class which are identical involve using reflection on this.
Edit: I've read some of the responses. What in God's name is a static (or non-static, for that matter) class? And just to irritate all of you, it didn't solve the problem.
// some_class.java
public class some_class {
public static abstract class abstract_class {
...
}
...
}
// Model.java
public class Model extends some_class.abstract_class {
public Model(...) {
// No enclosing instance! Critical error.
...
}
...
}
And I thought that C++'s header files were bad.
The code you posted seems to compile just fine for me. Try doing a clean build in your IDE and it should work.
Just for your own curiosity, Java has 2 types of inner classes: static and regular or (non-static). If you don't include the static keyword for an inner class definition, it means that an instance of that class will always require an instance of the parent class. For ex:
public class MyClassOuter {
//...
public class MyClassInner {
//..
}
}
If you write that, it is understood that any instance of MyClassInner will have an implicit reference to an instance of MyClassOuter.
Static, on the other, hand implies no such thing. It is just a class definition that happens to be inside another class definition. The outer class is used almost like a package (though not quite).
if you have
interface MyInterface
{
abstract class MyAbstractClass {
// ...
}
}
and then you try
class ConcreteClass extends MyAbstractClass {
}
You will get the error described. The fix is to either move MyAbstractClass to a top-level class (put it in it's own file - not strictly necessary for non-public classes, but keeps the code organized.) Alternatively, add the static modifier to the MyAbstractClass declaration.
The "enclosing instance" message almost certainly implies that you have a (non-static) inner class for your superclass. In most cases, inner classes can and should be static - that's likely the best workaround here. Alternatively, as the message says, you will need to use an enclosing instance of the "outer" class, if your parent really makes sense as a non-static inner class.
Posting some code will help disambiguate between these causes and suggest the best way to resolve it. I'll also be able to give examples of the resolutions with the right class names - currently I don't think arbitrary names will help that much as it sounds like you hadn't identified the inner/outer class issue.
You need to in your child class add in the constructor super() that super class can be created.
class A{
.
.
.
class B{
. . .
}
}
if you want to access the Class B and it it is not static inner class you can write the code as
A.B objOfB = new A(). new B();
Is it possible to have an inner class inside the interface in java ???
You can. But here's what O'Reilly says about it:
Nested Classes in Interfaces?
Java supports the concept of nested classes in interfaces. The syntax and dynamics work just like nested classes declared in a class. However, declaring a class nested inside an interface would be extremely bad programming. An interface is an abstraction of a concept, not an implementation of one. Therefore, implementation details should be left out of interfaces. Remember, just because you can cut off your hand with a saw doesn't mean that it's a particularly good idea.
That said, I could see an argument for a static utility class nested into an interface. Though why it would need to be nested into the interface instead of being a stand-alone class is completely subjective.
I agree that this should be generally rare, but I do like to use inner classes in interfaces for services when the interface method needs to return multiple pieces of information, as it's really part of the contract and not the implementation. For example:
public interface ComplexOperationService {
ComplexOperationResponse doComplexOperation( String param1, Object param2 );
public static class ComplexOperationResponse {
public int completionCode;
public String completionMessage;
public List<Object> data;
// Or use private members & getters if you like...
}
}
Obviously this could be done in a separate class as well, but to me it feels like I'm keeping the whole API defined by the interface in one spot, rather than spread out.
Yes, it is possible but it is not common practice.
interface Test
{
class Inner
{ }
}
class TestImpl implements Test
{
public static void main(String[] arg)
{
Inner inner = new Inner();
}
}
Doesn't answer your question directly, but on a related note you can also nest an interface inside another interface. This is acceptable, especially if you want to provide views. Java's collection classes do this, for example Map.java in the case of the Map.Entry view:
public interface Map<K,V> {
...
public static interface Entry<K,V> {
....
}
}
This is acceptable because you're not mixing implementation details into your interface. You're only specifying another contract.
Yes. Straight from the language spec:
An inner class is a nested class that is not explicitly or implicitly declared static.
And (boldface mine):
A nested class is any class whose declaration occurs within the body of another class or interface.
One use case for this that I find quite useful is if you have a builder that creates an instance of the Interface. If the builder is a static member of the Interface, you can create an instance like this:
DigitalObject o = new DigitalObject.Builder(content).title(name).build();
It is legal, but I only really do it with nested interfaces (as already mentioned) or nested enums. For example:
public interface MyInterface {
public enum Type { ONE, TWO, THREE }
public Type getType();
public enum Status { GOOD, BAD, UNKNOWN }
public Status getStatus();
}