Is it possible and meaningful to make the superclass abstract? - java

I am told that: a class can extend a concrete superclass and override an implemented method to make it abstract.
If the method becomes abstract, then the corresponding superclass should become abstract too.
Is this correct? If so, is it meaningful to make the superclass or the method in superclass to become abstract?

To contain abstract methods the class itself must also be declared abstract.
Abstract methods can be used where behaviour is specific to each subclassing object. Although this can also be achieved through interfaces, you may prefer to use an abstract class as they can also contain already implemented methods, or you may wish to declare fields which are not static and final. Beware that when a class becomes abstract it can no longer be instantiated.
Read more about abstract classes here.

Whether or not you make your class abstract if it contains abstract methods is not a choice, it is a must. You cannot have a non-abstract class that has abstract methods.
Whether or not you should declare a method abstract or implement it in your super class comes down to your concrete use case. Is there a default behavior that makes sense for all possible concrete implementations of the super class? Then you might want to implement it. If that's not the case, declare it abstract and let the sub classes take over.

I am told that: a class can extend a concrete superclass and override an implemented method to make it abstract.
If the method becomes abstract, then the corresponding superclass should become abstract too.
Is this correct?
I think it's incorrect.
Take the following code for example.
public class Father {
public void print() {
System.out.println("Father");
}
}
public abstract class Son extends Father {
#Override
public abstract void print(); /* no need to abstract the superclass */
// and other abstract or concrete methods
}
public class Grandson extends Son {
#Override
public void print() {
System.out.println("Grandson");
}
}

Related

Is this a valid abstract class?

Is this a valid abstract class?
I know that abstract classes cannot be instantiated, so I'm suspicious of the instance variable language and constructor Programmer. It also implements a writeCode method that is not declared as default. If I recall correctly, the only methods that can be implemented in an abstract class are those with default implementations.
public abstract class Programmer {
private String language;
public Programmer (String language) {
this.language = language;
}
public void writeCode() {
System.out.println("Written in " + language);
}
}
If it is a valid abstract class, can someone explain why it contains a constructor?
Also, more broadly speaking, can abstract classes have instance variables? If so, why? Doesn't that seem counter to the idea that abstract classes cannot be instantiated?
Finally, I would love it if someone addresses the writeCode method. Why is it implemented, without a default modifier?
Thanks!
Yes, this is a valid abstract class.
Abstract classes can have constructors, instance variables and concrete methods.
The main difference with regular classes is that they can also declare abstract methods, delegating implementation to the non-abstract child classes (this is not the case here, you have no abstract methods).
Another difference is that they cannot be initialized directly, even if they do provide an accessible constructor.
The constructor(s) of an abstract class are typically used to initialize values internally, and to invoke from child classes or anonymously.
See documentation here.
Example
Given...
public abstract class Programmer {
private String language;
public Programmer(String language) {
this.language = language;
}
public void writeCode() {
System.out.println("Written in " + language);
}
}
... and...
public class JavaProgrammer extends Programmer {
public JavaProgrammer() {
super("Java");
}
}
Concrete child class
new JavaProgrammer().writeCode(); // prints "Java"
Anonymous class (note the empty class body {})
new Programmer("JavaScript"){}.writeCode(); // prints "JavaScript"
As you say, abstract classes cannot be instantiated. However, when a subclass of any abstract class is created, the first sentence in its constructor is a call to super(), which is nothing but a representation of the constructor of its parent class, the abstract class.
An abstract class can have instance variables and methods. It is even possible to have an abstract class without any abstract method. However, an abstract method can only be declared in an abstract class.
You are mixing abstract classes and interfaces concepts. An interface cannot have instance variables, and any implemented method must be prefixed with the static or default modifier.
This is correct example of abstract class. Answering your questions:
default keyword is used (as of java 8) in interfaces, where you can implement default method implementation, abstract class can have a method implementation just as any normal java class
having constructor in abstract class imposes having a constructor in extending class so that the underlying abstract class can be properly constructed (e.g. fields instantiated etc)
abstract class cannot be instantiated but as any other class can have private fields and internally make use of them, should they be protected then extending classes will also be able to directly access them.
It seems to me you're confusing abstract class with interface.
The abstract class contains a constructor because when the instantiated class based on the abstract class is created it will call super() to execute the code from the abstract class.
The instance variable is a similar thing. The class that is developed from the abstract class would then have access to the language and be able to work with it.
In terms of the default, that would be best practice but there is no absolute requirement for it to be there.
Abstract classes are partial implementations. Sometimes, as in the case above, the only thing that prevents the class from being instantiated is the abstract modifier itself!
If an abstract class has constructors then it means that subclasses must invoke one of the constructors (by calling super(...) in their constructor.
More broadly it seems that you're confusing Interfaces and Abstract Classes. Interfaces are a contract, they specify how a class should behave but provide no implementation whatsoever. Abstract Classes are a specific partial implementation of some code.
Interfaces are used (broadly) when you require someone else to provide behaviour but you don't care how it works. Abstract Classes are used when you want to assist people in providing behaviour, but you still require them to provide some details.
Since these definitions overlap, it's not unusual to see both Abstract Classes and Interfaces provided, e.g. the various Adapters in java.swing.*.

what must be implemented from an abstract class in java?

I have two questions really. I'm trying to get a handle on how inheritance works.
If I have an abstract class to inherit from, and it has a method that is not labelled abstract does this method still need to be implemented in the subclass?
If I have a subclass that is inheriting from another subclass, which is then inheriting from an abstract class, does the lowest subclass need to implement the methods in the abstract class? Or because the methods have been implemented in the middle subclass, they don't need to be implemented again?
Thank you!
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.
An abstract method is a method that is declared without an implementation (without braces, and followed by a semicolon), like this:
abstract void moveTo(double deltaX, double deltaY);
If a class includes abstract methods, the class itself must be declared abstract, as in:
public abstract class GraphicObject {
// declare fields
// declare non-abstract methods
abstract void draw();
}
When an abstract class is subclassed, the subclass usually provides implementations for all of the abstract methods in its parent class. However, if it does not, the subclass must also be declared abstract
If the method is not abstract it has been implemented already, when you subclass the abstract class you inherit the method implementation, re-implementing it would be overriding it. If the method was declared abstract you must implement or get compile-time error if the subclass is also not declared abstract.
If you are inheriting from a class A extends AbstractClass that is not abstract then A must have implemented any abstract methods or again compileerror. If it hasn't implemented any abstract classes then A must also be abstract and responsibility of implementing the abstract methods fall on subclassers of A. Any sublcassers that do not implement the method must also be declared abstract untill finally a subclass implements it.

From where Function will be inherit and why?

Suppose we have one class implements Interface extends abstract class with same abstract function in both Interface and abstract class. Then class inherit which function Interface or abstract class and why.
Like:
public class A extends B implements I
{
public void set()
{
// Some code here
}
}
Interface:
public interface I {
public void set();
}
abstract Class:
public abstract class B
{
public abstract void set();
}
Both. As long as the functions signatures match, the compiler will accept this "double"-inheritance. Keep in mind implementing interface's methods is only a "contract" your class has to verify to be compilable. Implementing the interface only means "my concrete class has to have a method set()". Extending the abstract class B means "my concrete class inherits the method set() from its superclass, and as it's defined as abstract, it needs to implement it". When both these propositions match (as per your example), all is fine.
If there is a difference in the signature of the functions between the interface and the abstract class, your concrete class must then implement both versions.
BTW, slightly off-topic, try to avoid abstract classes as much as you could. If an abstract class has only abstract methods, then it should be an interface. If it has some code in some of its method, then you should probably think about refactoring it to use composition rather than inheritance. Inheritance is evil ;)
It doesn't matter to know from which the method will be inherited because the method in both Interface and Abstract class are abstract meaning no implementation is given.
So all you have to ensure in your concrete class that you must implement all the method defined in the interface but not implemented in the abstract class . AND implement all the abstract methods defined in its superclasses (even if they are not defined in an interface) (from Guillaume)

Defining an abstract class without any abstract methods

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

What is the difference between an abstract class and a class that has all its methods abstract?

I wonder what is the difference in Java between an abstract class and a class that has all its methods abstract? I mean, is an abstract class just a class whose methods automatically get abstract?
Absolutely not. Indeed, a class can be abstract without any methods being abstract, although that's relatively rare (see Mark's comment below for an example). On the other hand, if a class has any abstract methods, then it must be declared abstract.
Generally speaking, the purpose of an abstract class is to provide a skeleton with some non-abstract behaviour, but other bits still to be filled in by subclasses. This can be used with the template method pattern, for example.
Any class that contains one or more abstract methods must also be declared abstract. To declare a class abstract, you simply use the abstract keyword in front of the class keyword at the beginning of the class declaration. There can be no objects of an abstract class. That is, an abstract class cannot be directly instantiated with the new operator. Such objects would be useless, because an abstract class is not fully defined. Also, you cannot declare abstract constructors, or abstract static methods. Any subclass of an abstract class must either implement all of the abstract methods in the superclass, or be itself declared abstract.
The Only difference between abstract class and interface is that abstract class can be inherited and whereas interfaces can't, thus interfaces don't have any constructors conversely with an abstract class.
Whenever you make a abstract method in the class then you explicitly mention the abstract keyword before the class name, just like this
public abstract class Test {
abstract void show();
}
Here are the points related Abstract class in Java
-->Abstract class is the one of class that cannot be instantiated.
-->If you want to get implementation of any method from child class(other person) then abstract method can use in this sense.
-->Abstract class are incomplete ,subclass must declare missing piece to become concrete class(Class whose object can be instantiated ) , otherwise these subclass also become abstract class.
-->You can achieve abstraction that is main pillar of OOP through by "abstract classes".
Abstraction hide the irrelevant detail of an object.
-->Abstract use for IS A Relationship (Inheritance).
-->Abstraction use for to achieve Polymorphic behavior (Another main pillar of OOP)
-->abstract class should not be private and not contained private method.
-->You extends single abstract class not multiple because Java is Single supported Inheritance
--> Abstract class must contain 1 or more than 1 abstract method
-->If any class contain abstract method then it should explicitly declare abstract class even if it contain concrete method.
--> Constructor and static method cannot be declared as abstract because constructor are not inherited.
--> If child class have not implement the abstract method of super class then it become also abstract class.
-->Attempting to instantiate the object of abstract class is an Compilation error.
-->Abstract super class variable can hold the reference of child concrete object.
A class which contains the abstract keyword in its declaration is known as abstract class.
Abstract classes may or may not contain abstract methods ie., methods with out body ( public void get(); )
But, if a class have at least one abstract method, then the class must be declared abstract.
If a class is declared abstract ,it cannot be instantiated.
To use an abstract class you have to inherit it from another class, provide implementations to the abstract methods in it.
If you inherit an abstract class you have to provide implementations to all the abstract methods in it.
If you don't want to provide implementation for all abstract methods then there is a concept of adapter class:
Example:
abstract class A{
public void m1();
public void m2();
public void m3();
}
class B extends A{
public void m1(){}
public void m2(){}
public void m3(){}
}
class C extends B{
public void m2(){
System.out.println("Hello m2");
}
public static void main(String args){
C obj=new C();
C.m2();
}
}

Categories