I have a super-class A with an abstract inner-class Inner, with another class B that extends A. Why doesn't A force B to implement the abstract inner-class?
I've already looked here, but it only specifies abstract methods in non-abstracts classes. Does the same principle apply here?
public class A {
...
abstract class Inner {
...
}
}
public class B extends A {
...
// Isn't forcing me to implement Inner
}
In many situations, there is no need to implement A.Inner. I was recently working with a UI-free browser library for Java. They had a class Element with subclasses like Anchor, Input, Span, Script, Style. Surely you wouldn't want to be forced to implement, for example, all the subclasses of Element? This is particularly true when the superclass is a member of someone else's code. Said superclass may have private methods referring to private subclasses.
An inner class, whether it's abstract or not, is basically syntactic sugar for a class that has a built-in reference to an instance of another class, its enclosing class. The fact that it is nested simply adds potential accessibility restrictions. Other than that, it's just like any other class (minus a few other restrictions on static members).
Because it would be a pointless restriction unless some code in B tried to instantiate A.Inner, in which case the existing rule would already catch it.
If you define a new concrete class that extends an abstract class, it has to implement the methods. But you haven't defined a new concrete class that extends Inner. You've defined a new class B that extends A; in a sense, B inherits the Inner class, but it's still abstract. (You can say B.Inner in some contexts, but from my testing it appears that the compiler treats it the same as A.Inner.)
Related
In context of Java, could a class replace the need of extending an abstract class by extending another non-abstract class and implementing an interface together, both of which combined have all the methods(abstract and implemented), of an abstract class?
In context of Java, could a class replace the need of extending an
abstract class by extending another non-abstract class and
implementing an interface together, both of which combined have all
the methods(abstract and implemented), of an abstract class?
Can it? Yes
Should it? No
An abstract class can be replaced by a concrete one, but you will be altering your system.
Do remember: an abstract class can not be instantiated, nor should it be, since it's not 'concrete enough' to make sense for your business. (If it does, it shouldn't have been an abstract class to begin with)
If you make it concrete, you risk that developers will use instances of the (what-should-be) abstract class.
If you change it the way you propose:
public void doSomething(MyAbstractClass instance){
// here we know there is an implementation provided by a subclass
}
would become
public void doSomething(MyShouldBeAbstractClass instance){
// here they can pass instances of the base class, which might have unsupported methods
}
For instance:
public String getConcreteInformation(){
throw new UnsupportedOperationException("Should be called on a child class");
}
and could lead to a lot of nasty bugs
I am trying to find out, if it is possible to create anonymous inner class as abstract. I thought, that it doesn't make sense because I am trying to create instance of the abstract class, but the message from compiler confused me:
Class 'Anonymous class derived from Test' must either be declared abstract or implement abstract method 'method()' in Test
Code:
abstract class Test{
abstract void method();
}
Test o = new Test(){};
If it is possible to declare anonymous class as abstract, please let me know how to do that.
I would be greatful for answer.
See JLS Sec 15.9.5 (emphasis mine):
15.9.5. Anonymous Class Declarations
An anonymous class declaration is automatically derived from a class instance creation expression by the Java compiler.
An anonymous class is never abstract (§8.1.1.1).
An anonymous class is always implicitly final (§8.1.1.2).
An anonymous class is always an inner class (§8.1.3); it is never static (§8.1.1, §8.5.1).
you can't and does not make sense to declare anonymous class as abstract class as anonymous are used as local class only once.
i think you are getting this error because of similar issue Class must either be declared abstract or implement abstract method error
As quoted by Andy Turner the answer to your question is NO.
However I think you wanted to know something different.
Why do you get this compiler message?
Well the compiler is a bit misleading here. It offers two possible solutions based on that you are declaring a class (that anonymous class) and then also want to create an instance of that class:
make the derived class (which an anonymous class always is) abstract,
this is fine for normal and inner classes but it is not possible for anonymous classes, so the compiler should not suggest it in the first place
implement all methods and have no abstract methods in your anonymous class declaration
So to solve your actual problem: simply implement method() so your anonymous class declaration contains no more abstract methods
abstract class Test{
abstract void method();
}
Test o = new Test()
{
void method()
{
// do something
};
};
Now everything is declared and the compiler should not complain any more.
I am wondering what does it mean to have a nested abstract class ? for example,
abstract class A{
abstract class B{
}
}
Are there any use cases or scenario that we might need such as design ? or is there something useful in such pattern ? and why Java allows us to do it ?
In design, you want the base class class A to present only an interface for its derived classes. This means, you don’t want anyone to actually instantiate an object of the base class. You only want to upcast to it (implicit upcasting, which gives you polymorphic behavior), so that its interface can be used. This is accomplished by making that class abstract using the abstract keyword. In other hand you want to use only part of functionality of class A so you create class B (as child) to reduce the coupling or implementation dependencies between systems and prevent duplicates.
But bear in mind when you define an inner class, code without inner classes is more maintainable and readable. When you access private data members of the outer class, the JDK compiler creates package-access member functions in the outer class for the inner class to access the private members. This leaves a security hole. In general we should avoid using inner classes. Use inner class only when an inner class is only relevant in the context of the outer class and/or inner class can be made private so that only outer class can access it. Inner classes are used primarily to implement helper classes like Iterators, Comparators etc which are used in the context of an outer class. About abstract class, it should be abstract to helpers, suppose your helpers should be too complicated to write abstract form for them.
In your case, I don't remember extensive usage of nested abstract classes, maybe in Swing world.
abstract classes are used to provide a partial implementation of a class for inheritance. it allows you to define the scheme of a class without providing the full definiton, so that it can be specified in a child class. it works somewhat like a Interface in that you can perform any operation specified in the abstract class upon an instance of any classes derived from it. Nested abstracted classes are designed to be inherited by other inner classes (even anonymous ones I think) but not by classes defined outside the outermost class.
public class HelloEveryone{
abstract class Hello{
void SayHello(){
System.out.println("Hello!");
}
abstract void SayHelloAlt();
}
public class HelloWorld extends Hello{
public void SayHelloAlt(){
System.out.println("HelloWorld!");
}
}
public class HelloUniverse extends Hello{
public void SayHelloAlt(){
System.out.println("HelloUniverse!");
}
}
void Go(){
ArrayList<Hello> hellos = new ArrayList<Hello>();
hellos.add(new HelloWorld());
hellos.add(new HelloUniverse());
for (Hello h : hellos){
h.SayHello();
h.SayHelloAlt();
}
}
}
static void main(){
HelloEveryone hello = new HelloEveryone();
hello.Go();
}
Can I define an abstract class without adding an abstract method?
Of course.
Declaring a class abstract only means that you don't allow it to be instantiated on its own.
Declaring a method abstract means that subclasses have to provide an implementation for that method.
The two are separate concepts, though obviously you can't have an abstract method in a non-abstract class. You can even have abstract classes with final methods but never the other way around.
Yes you can. The abstract class used in java signifies that you can't create an object of the class. And an abstract method the subclasses have to provide an implementation for that method.
So you can easily define an abstract class without any abstract method.
As for Example :
public abstract class AbstractClass{
public String nonAbstractMethodOne(String param1,String param2){
String param = param1 + param2;
return param;
}
public static void nonAbstractMethodTwo(String param){
System.out.println("Value of param is "+param);
}
}
This is fine.
Yes you can do it. Why don't you just try doing that?
YES You can create abstract class with out any abstract method the best example of abstract class without abstract method is HttpServlet
Abstract Method is a method which have no body, If you declared at least one method into the class, the class must be declared as an abstract its mandatory BUT if you declared the abstract class its not mandatory to declared the abstract method inside the class.
You cannot create objects of abstract class, which means that it cannot be instantiated.
Yes we can have an abstract class without Abstract Methods as both are independent concepts. Declaring a class abstract means that it can not be instantiated on its own and can only be sub classed. Declaring a method abstract means that Method will be defined in the subclass.
Yes, you can declare a class you cannot instantiate by itself with only methods that already have implementations. This would be useful if you wanted to add abstract methods in the future, or if you did not want the class to be directly instantiated even though it has no abstract properties.
yes, we can declare an abstract class without any abstract method. the purpose of declaring a class as abstract is not to instantiate the class.
so two cases
1) abstract class with abstract methods.
these type of classes, we must inherit a class from this abstract class and must override the abstract methods in our class,
ex: GenricServlet class
2) abstract class without abstract methods.
these type of classes, we must inherit a class from this abstract class,
ex: HttpServlet class
purpose of doing is although you if you don't implement your logic in child class you can get the parent logic
please check the HttpServlet source code
You can, the question in my mind is more should you. Right from the beginning, I'll say that there is no hard and fast answer. Do the right thing for your current situation.
To me inheritance implies an 'is-a' relationship. Imagine a dog class, which can be extended by more specialized sub types (Alsatian, Poodle, etc). In this case making the dog class abstract may be the right thing to do since sub-types are dogs. Now let's imagine that dogs need a collar. In this case inheritance doesn't make sense: it's nonsense to have a 'is-a' relationship between dogs and collars. This is definitely a 'has-a' relationship, collar is a collaborating object. Making collar abstract just so that dogs can have one doesn't make sense.
I often find that abstract classes with no abstract methods are really expressing a 'has-a' relationship. In these cases I usually find that the code can be better factored without using inheritance. I also find that abstract classes with no abstract method are often a code smell and at the very least should lead to questions being raised in a code review.
Again, this is entirely subjective. There may well be situations when an abstract class with no abstract methods makes sense, it's entirely up to interpretation and justification. Make the best decision for whatever you're working on.
yes you can do that.
declaring class abstract means that class will not be instantiated by any other class.
and there should be at least one abstract method inside that and meaning of that you can declare abstract method in that class if you are not declaring method than its ok.
example:
public abstract class abs {
protected int cx = 0, cy = 0;
public void p() {
System.out.print("hello");
}
}
this will work for sure.
Yes you can. Sometimes you may get asked this question that what is the purpose doing this?
The answer is: sometimes we have to restrict the class from instantiating by its own. In that case, we want user to extend our Abstract class and instantiate child class
Actually there is no mean if an abstract class doesnt have any abstract method . An abstract class is like a father. This father have some properties and behaviors,when you as a child want to be a child of the father, father says the child(you)that must be this way, its our MOTO, and if you don`t want to do, you are not my child.
Yes, you can define an abstract class without an abstract method. However, if there is no method inside you might better go with an interface
I have class B, which inherits from class A. The superclass A is abstract, containing one abstract method. I don't want to implement the abstract method in class B, therefore I need to declare class B as abstract as well. Declaring class B abstract, two things are working for me (the programs compile and run correctly):
1.) I don't declare any abstract methods in class B, even thought the class is abstract. This works, I assume, because the class inherits the abstract method of class A, and this is enough for the class to be declared as abstract: we don't need any other abstract methods directly declared in the class.
2.) I do declare the same abstract method in class B as it is declared in class A. This is some kind of overriding (?), not in the same sense as overriding in java (using the same header, but providing different implementation), here I just use again the same header of the method.
Both things are working, and I am not sure whether they are both Ok, and whether some of them is preferred (more correct) that the other. Are the two ways the same (do they mean the same to Java)?
Here I give some example classes, so that what I mean is more clear for you:
Case 1.):
public abstract class A {
public abstract String giveSum();
}
public abstract class B extends A {
}
Case 2.):
public abstract class A {
public abstract String giveSum();
}
public abstract class B extends A {
public abstract String giveSum();
}
Regards
In Java, the abstract class annotation indicates that the class cannot be directly instantiated. A class could be declared abstract simply because it should never be instantiated (perhaps it contains only static methods), or because its subclasses should be instantiated instead.
It is not a requirement that abstract classes contain abstract methods (the inverse is true: a class containing one or more abstract methods must be abstract.)
The question of whether you should duplicate the abstract method definition might be perceived as a style question - but I would be hard pressed to come up with an argument in favor of duplicating the definition (the only argument I can come up with is in the case where the class hierarchy might change the semantics or use of the method, and thus you'd like to provide an additional javadoc in class B.)
The primary argument against re-definition of the abstract method is that duplicate code is bad - it makes refactoring more cumbersome and such (all the classic "don't duplicate code" arguments apply.)
They are functionally equal, but the first one is preferred because it's shorter and isn't weird.
Go with #1. Rewriting the method declaration in the child class is confusing. And you actually don't need any abstract methods in an abstract class, regardless of whether the parent is abstract or not.
So, the question is: Which is preferred when sub classing an abstract class in java and don't want to provide implementation?
a) mark subclass as abstract too
b) mark subclass as abstract too AND re-write the method signature marked as abstract?
I would go for the first one:
a) Mark subclass as abstract too.
The former has already the abstract method declaration, there is no point in repeating it.
You are right, the two cases are equivalent. Case 1) is more simple, case 2) is code duplication - avoid it. But there may be one reason to do so:
If the method in class A does not return String but lets say C, class B may override it (since Java 5) with a more specific return type, lets say D (class extends C):
public abstract class A {
public abstract C giveSum();
}
public abstract class B extends A {
public abstract D giveSum();
}
public class C {
...
}
public class D extends C {
...
}