Does the class need to have the abstract keyword before it?
Or Does it need to have unimplemented (abstract) methods?
Can any normal class be extended?
Yes, all methods which are not final (static is also a bit different form the rest), can be overridden, unless the class itself is declared final. Abstract methods are only used if you do not provide any implementation in the base class.
Can any normal class be extended?
Yes :) Unless it has the final modifier.
No it doesn't need to have the word abstract, the word abstract just wont allow you to create an instance of that class directly, if you use the word abstract you can only create an instance of the classes that extend that abstract class.
AbstractClass abs = new ChildClass();
Yes you can extend a class without it needing to be defined as abstract. What this means is that you will be overriding methods. For example, you might make a class
DifferentString extends String
then,
public String toString()
{
return "Something different";
}
This will mean you can change the original behaviour of the parent class.
Reference:
http://docs.oracle.com/javase/tutorial/java/IandI/abstract.html
As others have also said, yes - but it is good practice to avoid doing so if you can possibly help it, because you can end up with what is known as the fragile base class problem more easily.
Yes, but if the class is marked as final, it can't be extended.
class Foo {
//some code here
}
class Boo extends Foo {
}
There are some concept confusions here. Unimplemented methods reside in an interface, and you can implement that interface.
You can extend any class as long as its not final.
Edit: What I meant to say that it is preferable to put Unimplemented methods in interfaces as well. Sorry for the poor wording. Abstract classes can have unimplemented methods as well, though you will end up with a complex and rigid hierarchy.
.
Related
I am little confused about abstract class in java. I know that whenever there is an abstract method in the class compiler force developer to mark class abstract. But even we don't have any abstract method in the class we still mark the whole class as abstract. I am not getting the point why we can do this. what is the purpose to allow developer to mark class abstract when there is no abstract method. One can say that reason is that we don't want to create instance of that class. If that the reason then marking constructor of the class private is more suitable rather than marking class abstract.
There is a very useful reason for having an abstract class without abstract methods: Providing default implementations for overridable methods.
There are several perfect examples in the JDK itself. Look - for example - at a WindowAdapter. It implements the WindowListener interface (among others), but provides empty not-doing-anything method implementations. In most cases you want to register a window listener that only overrides one or two of the interface methods. Then your own class simply extends WindowAdapter instead of implementing WindowListener.
Note, that with Java 8 default methods in interfaces this reason does not hold anymore, and in fact abstract classes without abstract methods do not make sense anymore.
I think it's to allow subclasses to be created but not the main class.
I guess your class has method stubs in it, otherwise tyere would be no reason not to instantiate it. It is generally better to use abstract methods for this.
For restricting the class to be instantiated.. Example HttpServlet class.. it is defined abstract but has no abstract methods.. We can use these methods in the subclasses but creating the class httpservlet itself is useless.. thats the reason i think..
HTH!
As stated, this can be to prevent instantiation. I strongly prefer private or protected constructors over this as I feel they communicate the intent more clearly.
Also, in a class hierarchy, if class A is abstract and contains an abstract method, that method does not need to be defined in a class B which extends class A. In this case, class B is marked as abstract and has no abstract members.
To prevent instantiation of a class and use it as a base class. For example, HttpServlet class, an example of template method design pattern where each method already has a behaviour defined. The child class is free to override one or more of them instead of all of them.
One can say that reason is that we don't want to create instance of
that class. If that the reason then marking constructor of the class
private is more suitable rather than marking class abstract.
No it is not at all suitable
This below example will clear your doubts , If you use private constructor , Not only your Object creation is blocked but also you can not even create a subclass of the Parent class
class ParentClass{
private ParentClass(){
}
}
class Subclass extends ParentClass{
static{
System.out.println("Hello");
}
}
You will get compile time error saying
error: ParentClass() has private access in ParentClass
But Marking a class as abstract will block Object creation but will not block Inheritence in java
Update
As you asked in comments that you can make it protected but then your class can be easily instantiated , because protected member can be accessed from the same class as well as in SubClass in same package as well as in a sub class in another package .
i have an abstract class,this class is extended in her subclasses:
i implementend one method on this abstract class and i made the other method abstracts
the implemented method is a general method that every subclass object has to access on it.So i decided to implement it on the abstract class,avoid implementing the same method on each subclass.
little example:
public abstract class Foo{
//plus constructor and other stuff.
public abstract void differentTypeOfImplementation();
public void doSomething(Foo foo){
//do something with the generic Foo object passed
}
}
i want your opinion on this type of implementation,
regards.
This question is probably too open ended, but your solution is perfectly fine.
The alternative is that you can make an Interface with differentTypeOfImplementation(), and then a utility class with doSomething. That way, your subclasses can also extend from other classes. However, if subclasses may occasionally override doSomething, or if doSomething require accessing internal states of the object, then what you have is perfectly valid.
Implementing a method in an abstract class is very much valid and acceptable design. If this method implementation is necessary for all its subclasses then this is the way to go. In your example however - the signature of the method makes it little fishy - it looks like you are not using the super class state in any way . That means you could as well declare this method as static.
I understand WHY we need Abstract Class in Java - to create sub-classes. But the same can be achieved by concrete class. e.g. Class Child extends Parent. Here Parent can very well be abstract & concrete. So why do we have ABSTRACT??
Abstract classes cannot be instantiated directly. Declaring a class as abstract means that you do not want it to be instantiated and that the class can only be inherited. You are imposing a rule in your code.
If you extend your Parent/Child relationship example further to include a Person class then it would make good sense for Person to be abstract. Parent is a concrete idea and so is child. Person is an abstract concept in reality as well as in code.
One benefit is that you explicitly define and protect the idea of the abstract class. When you declare a class as an abstract there's no way that you or anyone else using your code uses it incorrectly by instantiating it. This reasoning is similar to why we specify functions and fields as public, private or protected. If you declare a function or member as private you are in effect protecting it from improper access from client code. Privates are meant to be used within the class and that's it. Abstract classes are meant to be inherited and that's that.
Now, do you have to use abstract classes and define functions and fields as private instead of public? No, you don't. But these concepts are provided to help keep code clean and well-organized. The abstract class is implemented in all object-oriented languages to my knowledge. If you look around you will see that C++, C#, VB.NET etc. all use this concept.
A better, specific example:
In the example above the Shape class should be abstract because it is not useful on its own.
Abstract class means it is abstract not complete. It needs another class to complete it and/or its functionalities. You need to extend the abstract class. It will be useful with Certain class eg. Fruit all fruits have the same property like color. But you can have different properties for different fruits like is it pulpy such as orange or not eg Banana etc.
I know this is an old question but it looks like the poster still had some questions about the benefit of using an abstract class.
If you're the only one who will ever use your code then there really is no benefit. However, if you're writing code for others to use there is a benefit. Let's say for example you've written a caching framework but want to allow clients to create their own caching implementation classes. You also want to keep track of some metrics, like how many caches are open, hypothetically. Your abstract class might look something like this:
public abstract class AbstractCache {
public final void open() {
... // Do something here to log your metrics
openImpl();
}
protected abstract void openImpl() { }
}
On its own the AbstractCache class is useless and you don't want clients to try to instantiate one and use it as a cache, which they would be able to do if the class was concrete. You also want to make sure they can't bypass your metric logging, which they would be able to do if you just provided them a Cache interface.
The point of abstraction is not to create sub-classes. It's more about creating Seams in your code. You want code to be test-able and decoupled which lead to the ultimate goal of maintainability. For similar reasons, abstraction also buys us the ability to replace a bit of code without rippling side effects.
An abstract class is meant to be used as the base class from which other classes are derived. The derived class is expected to provide implementations for the methods that are not implemented in the base class. A derived class that implements all the missing functionality is called a concrete class
According to my understanding
Abstract Class is a class which just describes the behavior but doesn’t implement it.
Consider this Java example for Abstract Class:
public interface DoSomething(){
public void turnOnTheLight();
}
Concrete Classes are those, which are to be implemented.
For Example:
public abstract class A(){
public void doIt();
}
public class B extends A(){
public void doIt(){
//concrete method
System.out.println(“I am a Concrete Class Test”);
}
}
In other words, A concrete class in java is any such class which has implementation of all of its inherited members either from interface or abstract class.
For those who seek only differences in pure technical approach, the clearest difference between concrete parent classes and abstract parent classes is the obligation for children to include/implement specific methods.
A concrete parent class cannot force/oblige its children to include/implement a method. An abstract parent class oblige its children to do that by declaring abstract methods.
Apart from the above, it comes to design and functional requirements to dictate the use of abstract class. Such examples can be found on javax.servlet.http.HttpServlet class
I have read somewhere that we cannot initialize an interface, for example:
interface MyInterface{};
And the following code is definitely illegal:
MyInterface m = new MyInterface();
And as I remember the text I have read said: that because the new keyword is used to allocate memory for class members; so in case of interface, we only have abstract functions, so there is nothing to be allocated in an interface; therefore, initializing an interface is prohibited.
OK, that makes sense to me.
But in case of abstract class, we are allowed to declare and define abstract functions, non-abstract function, as well as normal variables;so why we also are not allowed to initialize an abstract class? And because of that, I was wondering when and how variables in an abstract class, if any, are allocated memory?
No object is ever an instance of "just" an abstract class - it's always an instance of a concrete class. Otherwise you could call the abstract methods... and there'd be no implementation to be called.
The variables in an abstract class are allocated the same way as the variables of any other class which happens to be a superclass of the actual class being initialized - they live "with" the variables from the other classes in the hierarchy, basically.
EDIT: To clarify, this is a conceptual limitation as much as an implementation one. An abstract class usually contains abstract methods, which is the reason for making it abstract. The point of abstract methods is to allow the caller to have compile-time checking that the method will be there, even though the abstract class doesn't provide the implementation. The VM ensures that there is an implementation by preventing instantiation of "just" abstract classes.
Now abstract classes can also be used to prevent instantiation even if there aren't any abstract methods - basically the fundamental point of an abstract class is that it's one which can't be directly instantiated; only concrete subclasses can be instantiated.
When you say "initialize" you really mean two separate things: Allocation and construction. Allocation is the process of obtaining memory for the object; construction is the process of putting bringing the object itself to life.
As you observe rightly, your interface class requires no memory. But that's not the point. An abstract class cannot be constructed because it is... well, abstract. There is no object of abstract type. And interfaces are abstract.
Think of a Mercedes being an abstract Car. You can buy a Mercedes, but you cannot buy an abstract car - it doesn't make semantic sense. Any car you could conceivably have has to be of a concrete type.
Edit: It might be useful to contemplate why a class may be abstract:
Because it is declared abstract class. This makes it abstract flat-out by decree, no reason given.
Because it has abstract member functions: The member function isn't implemented, and a concrete, derived class must provide the implementation.
Because it is declared interface: This is morally equivalent to "all member functions are abstract, and there are no member objects". (Having a separate keyword for this allows interfaces to circumvent the limitations of single inheritance.)
That's the point of an abstract class: to be the base class for other classes. It is specifically designed to not be instantiated.
Most abstract classes has abstract methods, which do not have implementations. How would you call such a method if you instantiated the abstract class itself?
When you use new to create a new instance of a subclass of an abstract class, the memory required for the base abstract class will be allocated then as well.
An abstract class is a class which is not finished yet and generally has abstract members(although it is not obligatory). So you cannot instantiate an abstract class. This is defined by the language.
An abstract class is a class that is declared abstract—it may or may
not include abstract methods. Abstract classes cannot be instantiated,
but they can be subclassed.
If a class includes abstract methods, the class itself must be
declared abstract.
http://download.oracle.com/javase/tutorial/java/IandI/abstract.html
abstract classes are not full. they have abstract methods, which are not implemented.
what will happen if you try to invoke one of them?
abstract class' variables are located on memory by the concrete instantiated class.
The variables in an abstract class are allocated when the new keyword is used on a class that extends the abstract class.
So if you don't have a class extending your abstract class they never get allocated.
When you instantiate a class, you're allocating memory for several aspects of the class, including an area for methods (it's significantly more involved than this). Abstract classes do not have definitions for some methods, so we cannot put pointers to actual methods.
Abstract classes contain -- at least partially -- methods without definitions. You can't call those, because there's no code to run.
Maybe an illustration with some code could be useful.
abstract class AC{
abstract public void m();
}
class Main{
public static void main(String[] a){
AC obj = new AC();
obj.m(); /* Nothing to execute. */
}
}
So this behavior must be forbidden.
By the way, even if your interface is empty, you would have to provide an empty implementation:
Serializable x = new Serializable(){};
The empty curly braces will be needed for an abstract class too. I can't think of encountering a need for these constructs though.
Are there some practical programming situations for someone to declare a class abstract when all the methods in it are concrete?
Well you could be using a template method pattern where there are multiple override points that all have default implementations but where the combined default implementations by themselves are not legal - any functional implementation must subclass.
(And yes, I dislike the template method pattern ;))
An abstract class is a class that is declared abstract - it may or may not include abstract methods. They cannot be instantiated so if you have an abstract class with concrete methods then it can be subclassed and the subclass can then be instantiated.
Immagine an interface whose declared methods usually show the same default behavior when implemented. When writing a class that needs to support the interface you have to define said default behavior over and over.
To facilitate implementation of your concrete classes you might want to provide an abstract class providing default behavior for each method. To support the interface in a concrete class you can derive from the abstract class and override methods if they deviate from the standard behavior. That way you'll avoid the repeated implementation of the same (redundant) default behavior.
Another possible use case is a decorator which delegates all calls to the wrapped instance. A concrete decorator implementation can override only those methods where functionality is added:
public interface Foo {
public void bar();
}
public abstract class FooDecorator implements Foo {
private final Foo wrapped;
public FooDecorator(Foo wrapped) { this.wrapped = wrapped; }
public void bar() { wrapped.bar(); }
}
public class TracingFoo extends FooDecorator {
//Omitting constructor code...
public void bar() {
log("Entering bar()");
super.bar();
log("Exiting bar()");
}
}
Although I don't really see the necessarity to declare FooDecorator as abstract (non-abstract example: HttpServletRequestWrapper).
Previous answers already hit the main issues, but there's a minor detail that might be worth mentioning.
You could have a factory that returns instances of (hidden) subclasses of the abstract class. The abstract class defines the contract on the resulting object, as well as providing default implementations, but the fact that the class is abstract both keeps it from being instantiated directly and also signals the fact that the identity of the "real" implementation class is not published.
Wondering why no one has pointed to the Practical Example of MouseAdapter:
http://docs.oracle.com/javase/6/docs/api/java/awt/event/MouseAdapter.html
An abstract adapter class for receiving mouse events. The methods in
this class are empty. This class exists as convenience for creating
listener objects.
Nice question :)
One thing is for sure ... this is certainly possible. The template suggestion by krosenvold is one good reason for doing this.
I just want to say that a class must not be declared abstract just for preventing it's instantiation.
This is referred in the Java Language Specification Section 8.1.1.1
When you have an important class but the system cannot create an instance fo this class, because
this class is parent of a lot of classes of the system;
this has a lot of responsability (methods used by a lot of class) for domain's requires;
this class not represents a concrete object;
Servlet Example:
All methods are concrete,
but the base class is useless by itself:
DeleteAuthor.java
Abstract class with concrete doGet method.
doGet calls file pointed to in protected string sql_path.
sql_path is null.
DeleteAuthorKeepBook.java
extends abstract class DeleteAuthor
sets sql_path to delete_author_KEEP_BOOK.sql
DeleteAuthorBurnBook.java
extends abstract class DeleteAuthor
sets sql_path to delete_author_BURN_BOOK.sql