Why cannot use new keyword to initialize abstract class in Java? - java

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.

Related

Why we are declaring the class as abstract class it has only concrete methods in it?

Abstract class means, it has both abtract methods and concrete methods but even if it has only concrete methods, it is just look like a normal methods only right.
And why we are declaring the class as the abstract without any abtract methods?
On some cases, you do want to have some shared logic/fields/methods between several classes, but you do not want the base class to be instanciated by itself, only the extending classeses.
For such use-cases, abstract class, even without any abstract methods, can do the trick
It could be a base class for implementing some interfaces: all methods are concrete, but not all methods of interfaces are implemented.

Class without java.lang.Object as a superclass

We know that by default, every class inherits ultimately from the java.lang.Object class, which is why methods such as toString are readily available to every class. Therefore, a generic class is effectively as follows:
public class Foo extends java.lang.Object {
public Foo() {super(); }
}
However, is it at all possible to create a class which does NOT automatically inherit from the Object class, and thus, has no superclass? And if so, what would be the effect?
We can't write class without having java.lang.object as superclass. Compiler will automatically extend the object class.Only the object class itself and interfaces are the ones which do not extend object class.
No, that is not possible. From the documentation:
Class Object is the root of the class hierarchy. Every class has
Object as a superclass. All objects, including arrays, implement the
methods of this class.
I do not believe that you can have a class that does not inherit Object. Quoting from Object as a Superclass..
The Object class, in the java.lang package, sits at the top of the
class hierarchy tree. Every class is a descendant, direct or indirect,
of the Object class. Every class you use or write inherits the
instance methods of Object. You need not use any of these methods,
but, if you choose to do so, you may need to override them with code
that is specific to your class.
In cases where the inheritance is not explicitly stated, it is implicitly stated. Now, inheritance will obviously not form a cycle. The Object class is the only one which inherits from nobody, it's the top of hierarchy.

Why mark class abstract when there is no abstract method

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 .

abstract method in class

A class automatically becomes abstract class when any of its method declared as abstract.
I take this point in some blog. Can someone explain me Why entire class becomes abstract when we use only one abstract method.?
Because it can't be instantiated directly anymore. Also, it's then a compiler error if you don't mark the class itself as abstract.
First of all, I'm going to guess that the blog you mentioned was actually discussing C++. In Java, it's a compiler error to declare an abstract method within a class that is declared with the abstract keyword. With that said, Consider this (erroneous) code:
class A
{
abstract void foo();
}
A a = new A();
a.foo(); //Whoa! what are we supposed to do??!
If A had been declared as abstract (as would be required in real code), it would have been impossible to instantiate it.
If any part of a class is missing (that is, it is declared abstract), the class must be abstract because parts of it cannot be used.
In C++, there is no abstract keyword-- a class is automatically abstract if it has any abstract methods (referred to as pure virtual functions in C++).
In Java on the other hand, a class is only abstract if it is declared with the abstract keyword. However, this keyword is required if there are any abstract methods, so the only difference between the two systems in practice is that Java allows abstract classes to not have any abstract methods. In both languages, a class must be abstract if it has any abstract methods: in C++, this is simply how abstract classes are defined, and in Java it is required via the mechanics of the abstract keyword.
Once a method is abstract, it is declared to have no implementation. How would you suggest the VM instantiate an instance of that class?
An abstract method is one that defines a contract for a method but does not implement the functionality.
To instantiate a class with methods that cannot meet the contract defined as there is no implementation wouldn't work. Thus an abstract method means that you should not be able to instantiate the class.
A class automatically becomes abstract class when any of its method declared as abstract.
Can someone explain me Why entire class becomes abstract when we use
only one abstract method.?
The class has to be declared Abstract because the compiler expects a body for a normal class's method otherwise it will throw error. So either you write the method's body or declare the class Abstract
Example:
class SomeClass{
// Method without body
public void SomeMethod();
public static void main(String[] args) {
}
}
When you try to compile it, you will get:
SomeClass.java:4: missing method body, or declare abstract
public void SomeMethod();

What is the purpose of abstract class which doesn't have any abstract methods in it?

Java allows you to designate a class as being abstract even if it has no abstract methods in it. What is the purpose of this kind of abstract class?
An abstract class can be used to force derivation and to disallow instance creation, even when it doesn't have any abstract methods. It might be an abstract representation of some concept that has default implementations for its methods.
As Jordão noted, abstract classes can be used to prevent instance creation for abstract concepts; imagine a Window class that creates a system-level window in its constructor, but only allows for instances of ModalWindow, ModelessWindow, or DialogWindow.
Abstract classes can require constructor variables and expose protected methods and fields for subclasses. The methods may even refer to private instance variables on the abstract class.
While it is a debated recommendation to "favor composition over inheritance", my view is to ensure that an abstract class devoid of abstract methods is not simply a convenient container for methods convenient to subclasses, but instead that each subclass could stand in for its superclass.

Categories

Resources