Abstract class and methods | Ambiguity in opinions - java

I just came across two distinct opinions regarding abstract class :
1) One says , abstract method cannot be used in concrete(general) class ; while the abstract classes can have both abstract/non-abstract methods
2) While , a tutorial that has been highly watched on youtube says , " Any class that has an abstract method , will let its class be automatically defined as abstract "
2nd point is totally in contrast to the 1st point ; While implementing it , I did succeed only in the 1st concept and not 2nd though . But , still I want to have a detailed clarity in this regard , if anyone can help me with patience .

As described in the official Java tutorial, "If a class includes abstract methods, then the class itself must be declared abstract". It does not automatically become abstract; it needs to be marked as abstract explicitly.

Any class that contains abstract methods cannot be instantiated because it contains methods that are undefined. Any time an object of a class is created, it must contain all contents of the class and they must all be defined.
So you need to declare the class as abstract which means that the class cannot be instantiated. But just because a class is abstract, doesn't mean it must implement only abstract methods. For example, you can have a static method in an abstract class because calling a static method belongs to the class rather than an object or instance of the class.

An abstract class can have methods abstracts and non abstract. For exemple,
public abstract class Employee {
...
//this method would be implemented in those classes that extends from Employee.
public abstract void calculateSalary();
public Employee addEmployee() {
//Method body
}
But if you declare an abstract method in a non abstract class this has to be converted itself into am abstract one.
On the other hand abstract methods will be implemented in the inherited classes of an abstract parent class. So you would be doing this implementation in a generic class.
I hope this would helps.

Related

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();

Trouble with implementing abstract super class Java

I'm working on an assignment where I'm trying to implement a class that extends an abstract super class, but by using
public class B extends A{}
However, that gives me the error that type B must implement the abstract method A.act, is there another way in which I can do this without using extends?
Using:
public abstract class B extends A{}
Gives me a different error on another part of the assignment that should be correct.
What should I do? Thanks for the help.
In order for B to instantiated by the JVM, it must not be abstract. A abstract class is an idea or suggest of how a class might work, with some (or all) of the functionality needing to implemented by those classes that extended it.
For B to be instantiated, it must implement all the abstract methods of A.
To solve your problem, you must provide an implementation of the methods that A has marked as abstract...
public abstract class A {
public abstract void implementMe();
}
public class B extends A {
public void implementMe() {
// Your implementation
}
}
The reason for much of this is it allows you to pass B to methods and classes that use A and also change the way in which A works. This is part of polymorphism, where one instance of object can act as its parent (B acting like it's A)
I don't know if it will help, but you could have a read of Abstract classes
and methods
don't declare method act in abstract class A as abstract method if you do not want to provide implemenation of act in B. But that may not be a right choice depending upon what you are trying to achieve. In second case, when abstract class extends another abstract class, use "implement" instead of "extends". hope it helps

Why cannot use new keyword to initialize abstract class in 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.

Regarding Object class function access from a user defined class

We can use base class functions by extending from subclass.Generally we use equals() method which is defined in Object class.I read in the book that every class will extend Object class and so that we are able to use functions like equals() in our user defined class with subclass reference.
One doubt i am having is with out extending Object class (Even any other class that extends Object class) we are able to use equals method.
can any one explain how it happens?
Every class in Java extends Object by default(unexplicitly) no matter what you do.
If you do:
Class Foo { }
the compiler will treat it as if it were
Class Foo extends Object { }
Even when classes can only have at most 1 super class, if you do
Class Foo extends Bar { }
Class Bar extends Biz{ }
at certain moment up in the hierarchy one of those classes will have the class Object as it's parent, so even when only the topmost class would directly extend from Object, all of the other classes down the hierarchy would indirectly extend Object too, hence giving you access to Object class defined methods such as: clone, equals, finalize, etc...
Regards.
It's an implicit rule, JVM may implement the mechanism.

Categories

Resources