Should I implement all the methods present in an abstract class? - java

Below is the code snippet:
public abstract class MyAbstractClass {
public abstract void a();
public abstract void b();
}
public class Foo extends MyAbstractClass {
public void a() {
System.out.println("hello");
}
public void b(){
System.out.println("bye");
}
}
public class Bar extends MyAbstractClass {
public void a() {
System.out.println("hello");
}
public void delta() {
System.out.println("gamma");
}
}
There are couple of questions that I have:
Q-1 :- Should I implement ALL the methods in abstract class?
Q-2 :- Can the implementing class have its own methods?

When you extend an Interface or an Abstract class you are creating a contract of sorts with that superclass. In the contract you are saying:
"I will implement all unimplemented methods in my superclass"
If you do not, implement all the unimplemented methods, then you are breaking your contract. A way to not break your contract is make your subclass Abstract as well as a way of saying
"I have not implemented all the classes in my contract, I am going to
have my subclasses implement them".
For your class bar right now, you must implement b() or make bar an Abstract class or you are not fulfilling your contract with MyAbstractClass
The basic idea is:
Interface: None of my methods are implemented. A subclass must implement all my methods in order to implement me. (Note: I believe default interfaces have been added to Java 8 which may change this a bit)
Example:
public interface myInterface
{
//My subclasses must implement this to fulfill their contract with me
public void methodA();
//My subclasses must implement this to fulfill their contract with me
public void methodB();
}
Abstract: I may implement some of my methods, but I will also leave methods as abstract so that my subclasses must implement because they can implement those classes to suit their needs better than I can.
Example:
public abstract class myAbstractClass
{
//My subclasses must implement this to fulfill their contract with me
public abstract void methodC();
public void helloWorld()
{
System.out.println("Hello World");
}
}
Abstract classes can also extend interfaces so they can implement some of their methods. But they can also leave some of the methods unimplemented so the subclass can implement them. If you leave an interface method unimplemented, there is not need to declare it abstract, it is already in the contract.
Example:
public abstract class myAbstractClass2 implement myInterface
{
#Override
public void methodA()
{
// this fulfills part of the contract with myInterface.
// my subclasses will not need to implement this unless they want to override
// my implementation.
}
//My subclasses must implement this to fulfill their contract with me
public abstract void methodD();
}
So in essence, an abstract class doesn't have as strict a contract with it's superclass because it can delegate its methods to its subclasses.
Regular Class: (I use regular to mean non-interface, and non-abstract). I must implement all unimplemented methods from all of my superclasses. These classes have a binding contract.
Example:
public class mySubClass extends myAbstractClass2
{
#Override
public void methodB()
{
//must be implemented to fulfill contract with myInterface
}
#Override
public void methodD()
{
//must be implemented to fulfill contract with myAbstractClass2
}
public void myMethod()
{
//This is a method specifically for mySubClass.
}
}

Q-1:- Should I implement all methods in abstract class?
Yes, you must implement all abstract methods.
Q-2 :- Can the implementing class have its own methods?
Yes, you can declare own (more specfic) methods.

You not only should, but have to implement all abstract methods (if the subclass is non-abstract). Otherwise an object of that subclass wouldn't know what to do if that method was called!
The only way to prevent this is if the subclass is also declared abstract, so that it cannot be instantiated in the first place.

You don't have to implement all methods of an abstract class. But you must implement all abstract methods of it.
In fact extending an abstract class has no difference then extending a normal class. It's not like implementing interfaces. Since you're extending you are creating a subclass thus you can add as many methods and attributes as you need.

Ya definately implementing class can define its own method as well and if are not implementing all the methods of your abstract class in the derived class then mark this derived class also as Abstract
but at the end of chain you have to make one concrete class which implements all the method that was not implement in abstract sub-parent

public interface I{
public void m();
}
public abstract class A1 implements I{
//No need to implement m() here - since this is abstract
}
public class B1 extends A1{
public void m(){
//This is required, since A1 did not implement m().
}
}
public abstract class A11 extends A1{
//Again No need to implement m() here - since this is abstract
public abstract void newA11Method()
}
public class B11 extends A11{
//This class needs to implement m() and newA11Method()
}

Yes, the implementing class need only implement the methods labeled as abstract in the abstract class.

Yes you must implement all the methods present in an abstract class. As the purpose of abstract class is purely to create a template for the functions whose implementation is decided by the class implementing them. So if you don't implement them, then you are breaking the concept of abstract class.
To answer your second question, yes you can create any number of your own methods irrespective of the abstract class you are extending.

Yes, When you are implementing an Interface you will have to implement all its methods. That is the purpose of defining an Interface. And yes, you can have your own methods in the class where you implement an Interface.

Yes, when you extends abstract you should give implementation for all abstract methods which are presents in abstract class. Othrewise you should make it implementation class as abtract class.

You must implement all the abstract methods you have in the abstract class. But you can directly use the concrete methods that are implemented.
For more information please refer to the :
https://www.javatpoint.com/abstract-class-in-java

Related

OOP interface inheritance

My question is that can one interface extend another interface or it implements another interface.
interface A {
}
interface B extends A {
}
OR
interface B implements A {
}
Barring Java 8 extensions, an interface doesn't implement anything.
So therefore extends is the correct term.
An interface can only extend another interface, since an interface cannot contain any implementation.
interface ParentInterface{
void myMethod();
}
interface SubInterface extends ParentInterface{
void anotherMethod();
}
Yes, they can via the extends keyword, as interfaces can't implement any methods, only declare their signatures.
interface A {
public void foo();
}
interface B extends A {
// You don't implement the methods from A here
public void bar();
}
class C implements B {
public void foo(){
}
public void bar(){
}
}
Any class that then implements B must then implement the methods from A as well.
Yes, an interface can extend another interface in Java.
// this interface extends from the Body interface:
public interface FourLegs extends Body
{
public void walkWithFourLegs( );
}
Well but we must think,
When would we want an interface to extend another interface
We know that any class that implements an interface must implement the method headings that are declared in that interface. And, if that interface extends from other interfaces, then the implementing class must also implement the methods in the interfaces that are being extended or derived from.
So, in the example above, if we have a class that implements the FourLegs interface, then that class must have definitions for any method headings in both the FourLegs interface and the Body interface.
Question part 2:Interface do not Implement another interface,Because
Implements denotes defining an implementation for the methods of an interface. However interfaces have no implementation so that's not possible.
In terms of Inheritance in case of "INTERFACE" they always extends they never implement anything.

Abstract class with all methods abstract - Practical Example

I am asking a very basic question and it may be marked duplicate (I could not find the answer though):
Is there any practical example of an Abstract Class with all the
methods declared as Abstract?
In most cases and as mentioned in Java Tutorial also, class with all methods abstract shall be an interface.
But since abstract class and interface are two different concepts, I am looking for an example compelling to have "complete abstract class"
The only practical approach i think is that Abstract class can hold state. So you can have inside properties with access level protected, and you can make protected abstract methods that in interface you can't cause all are public.
A practical example could be for example this, the protected method in java has 'inheritance access' and 'package access'.
public interface Operation{
void operate();
}
public abstract class AbstractClase implements Operation{
protected Operation delegate;
public AbstractClase(Operation delegate){
this.delegate=delegate;
}
//delegate implementation responsability to children
protected abstract doSomething();
}
The downside of using abstract class is that you loss the possibility to extends of something else too.
As well as for holding state, it's worth remembering that all interface members are implicitly public. So restricting visibility of abstract methods may itself be a compelling enough reason to use an abstract class instead of an interface.
Adding to the two answers given above, Interfaces can only have constants(Variables which are public,static and final) while there is no such restrictions for abstract classes.
Abstract classes can have constructors which will be implicitly called when a child class is instantiated (if it is non-parameterised). But this is not possible with interfaces.
Here is an example for the usage of an abstract class
abstract class Animal{
public int noOfLegs;
public boolean isAlive;
Animal(){
isAlive = true;
}
public abstract void walk();
}
class Cow extends Animal{
Cow(){
noOfLegs = 4;
}
public void walk(){
if(isAlive){
//Code for walking
}
}
}
One other general purpose of an abstract class is to prevent an instance of the class., for example
abstract class Mammal{
int i=0;
}
public class Man extends Mammal{
public setMeValue(int i){
this.i=i;
}
public static void main(String args[]){
Mammal m= new Man();
man.setMeValue(10);
}
}
In the above code, I effectively make sure that there will never be an object of instance Mammal.
An interface can be applied to wildly different classes. Classes that have no relation to each other are Serializable or Cloneable. However, subclasses of an abstract class are all related. This may not mean anything when implementing the interface or extending the abstract class, but it means something semantically.
There is a style of programming where all the methods of a base class are either public final, protected abstract, protected and empty, or private. But even that isn't what the OP was interested in.
Adding more to the below answers:
Interface provide you with a contract to implement where abstract Class may provide you with a template as well. For a simple scenario you can use an Interface or an abstract Class without thinking much. But having an abstract class just for maintaining a state might give you lot of problems in a complex implementation. In such cases you have to carefully consider what you really want to achieve in your code and make the decision. If you consider the case of maintaining the state in your code, you can always use the State pattern in your implementation, so you will be able to use an interface in your code. You should always consider the extend-ability and maintainability of your code before deciding to use an abstract class over interface.
The simplest practical example I can think of is a class that has a protected variable:
public abstract class RoadVehicle {
protected int numberOfTires;
protected String vinNumber;
protected VehicleRegistration registration;
public abstract void drive();
public abstract double calculateToll();
public abstract void changeTires();
// so on and so forth...
}
You can't do this with an interface.
public abstract class animal{
public abstract void speak(){
System.out.println("animal voice");
}
}
public class dog extends animal{
public void speak(){
System.out.println("dog voice");
}
}
The biggest motive behind having Pure Abstract classes is to allow future extension. Assume you have an Abstract class (with all abstract members), then you inherit that abstract class in 20 derived classes. Sometime in future you wish to add a public method to 5 of your derived classes, what do you do ?
Since you already inherit the abstract class, an easier solution is to add the method (with implementation) to the abstract class. This way you don't have to touch any of the derived classes. Interfaces are very rigid in this context, once created there is very little chance to change an Interface, as it would require changing all the classes that implement that Interface.

not implementing all of the methods of interface. is it possible?

Is there any way to NOT implement all of the methods of an interface in an inheriting class?
The only way around this is to declare your class as abstract and leave it to a subclass to implement the missing methods. But ultimately, someone in the chain has to implement it to meet the interface contract. If you truly do not need a particular method, you can implement it and then either return or throw some variety of NotImplementedException, whichever is more appropriate in your case.
The Interface could also specify some methods as 'default' and provide the corresponding method implementation within the Interface definition (https://docs.oracle.com/javase/tutorial/java/IandI/defaultmethods.html). These 'default' methods need not be mentioned while implementing the Interface.
The point of an interface is to guarantee that an object will outwardly behave as the interface specifies that it will
If you don't implement all methods of your interface, than you destroy the entire purpose of an interface.
We can override all the interface methods in abstract parent class and in child class override those methods only which is required by that particular child class.
Interface
public interface MyInterface{
void method1();
void method2();
void method3();
}
Abstract Parent class
public abstract class Parent implements MyInterface{
#Override
public void method1(){
}
#Override
public void method2(){
}
#Override
public void method3(){
}
}
In your Child classes
public class Child1 extends Parent{
#Override
public void method1(){
}
}
public class Child2 extends Parent{
#Override
public void method2(){
}
}
I asked myself the same question, and then learned about Adapters. It solved my problem, maybe it can solve yours. This explains it very well : https://blogs.oracle.com/CoreJavaTechTips/entry/listeners_vs_adapters
You can do that in Java8. Java 8 introduces “Default Method” or (Defender methods) new feature, which allows a developer to add new methods to the Interfaces without breaking the existing implementation of these interfaces.
It provides flexibility to allow Interface define implementation which will use as default in the situation where a concrete Class fails to provide an implementation for that method.
interface OldInterface {
public void existingMethod();
default public void DefaultMethod() {
System.out.println("New default method" + " is added in interface");
}
}
//following class compiles successfully in JDK 8
public class ClassImpl implements OldInterface {
#Override
public void existingMethod() {
System.out.println("normal method");
}
public static void main(String[] args) {
ClassImpl obj = new ClassImpl ();
// print “New default method add in interface”
obj.DefaultMethod();
}
}
Define that class as an abstract class. However, you must implement those unimplemented methods when you want to create an instance of it (either by using a subclass or an anonymous class).
It is possible and it is easy. I coded an example.
All you have to do is inherit from a class that does implement the method. If you don't mind a class that is not instantiable, then you can also define an abstract class.
If you want an instantiable class, it is not possible. You may try to define an abstract class, though.
If you try to implement an interface and you find yourself in a situation where there is no need to implement all of them then, this is a code smell. It indicates a bad design and it violates Liskov substitution principle. Often this happens because of using fat interface.
Also sometimes this happens because you are trying to implement an interface from an external dependency. In this case, I always look inside the source code to see if there is any implementation of that interface which I can either use it directly or subclass it and override methods to my needs.
We can use Adapter classes ,which reduces complexcity by not making mandatory to implement all the methods present in the interface
Adapter class is a simple java class that implements an interface with only EMPTY implementation .
Instead of implementing interface if we extends Adapter class ,we provide implementation only for require method
ex--- instead of implementing Servlet(I) if we extends GenericServlet(AC) then we provide implementation for Service()method we are not require to provide implementation for remaining meyhod..
Generic class Acts as ADAPTER class for Servlet(I).
yes possible below shown is the way
interface Test {
void m() throws NullPointerException;
}
class Parent {
// Parent class doesn't implements Test interface
public void m() {
System.out.println("Inside Parent m()");
}
}
class Child extends Parent implements Test {
}
public class Program {
public static void main(String args[]) {
Child s = new Child();
s.m();
}
}

implementing abstract methods/classes in java

Can I implement abstract methods in an abstract base class A in java?
If the answer is yes and there is an implemented abstract method in a base class A and there is a derived class B from A (B is not abstract). Does B still has to implement that base abstract method?
If I understand your question correctly, Yes.
public abstract class TopClass {
public abstract void methodA();
public abstract void methodB();
}
public abstract class ClassA extends TopClass {
#Override
public void methodA() {
// Implementation
}
}
public class ClassB extends ClassA {
#Override
public void methodB() {
// Implementation
}
}
In this example, ClassB will compile. It will use it's own implementation of methodB(), and ClassA's implementation of methodA(). You could also override methodA() in ClassB if desired.
You could have two abstract classes, X and Y, where Y extends X. In that case it could make sense for Y to implement an abstract method of X, while still being abstract. Another non-abstract class Z could extend Y. However, in your example, for A to implement its own abstract methods is a contradiction, the point of making them abstract is so it doesn't provide implementations, it just specifies what the method signatures should look like.
If you implement an abstract method it's not really abstract any more, so no.
Abstract classes can have regular methods. If you want to implement some of the methods of class A and leave rest of the methods abstract, you can do this. However, abstract methods cannot have a body, therefore if you mark a method as abstract, then it has to be implemented by a subclass, you can't implement them in the abstract class. However, you can have an abstract class without abstract methods, then subclass only needs to extend it.
Yes, you can implement abstract methods in a class which is declared as abstract. If a class is declared abstract that does not mean all its method must be abstract.
For a concrete sub class, it is not mandatory to implement the abstract methods that are already implemented by one of their super class.
No. Abstract methods are meant to be defined by the subclass(es). For more information, see Abstract Methods and Classes. However, you can define a method in the base class and have the subclass(es) override it, if required.
Yes, but it can't be abstract any more. Abstract means there is no implementation.
What you can do is:
interface I {
void meth();
}
//and
abstract class A implements I {
public void meth() {
//implementation
}
}
Or:
abstract class A {
public abstract void meth();
}
//and
abstract class B extends A {
public void meth() {
}
}
If A already has an implementation, you can override it in B (if B is concrete), because B inherits that default implementation from A.

Abstract class in Java

What is an "abstract class" in Java?
An abstract class is a class which cannot be instantiated. An abstract class is used by creating an inheriting subclass that can be instantiated. An abstract class does a few things for the inheriting subclass:
Define methods which can be used by the inheriting subclass.
Define abstract methods which the inheriting subclass must implement.
Provide a common interface which allows the subclass to be interchanged with all other subclasses.
Here's an example:
abstract public class AbstractClass
{
abstract public void abstractMethod();
public void implementedMethod() { System.out.print("implementedMethod()"); }
final public void finalMethod() { System.out.print("finalMethod()"); }
}
Notice that "abstractMethod()" doesn't have any method body. Because of this, you can't do the following:
public class ImplementingClass extends AbstractClass
{
// ERROR!
}
There's no method that implements abstractMethod()! So there's no way for the JVM to know what it's supposed to do when it gets something like new ImplementingClass().abstractMethod().
Here's a correct ImplementingClass.
public class ImplementingClass extends AbstractClass
{
public void abstractMethod() { System.out.print("abstractMethod()"); }
}
Notice that you don't have to define implementedMethod() or finalMethod(). They were already defined by AbstractClass.
Here's another correct ImplementingClass.
public class ImplementingClass extends AbstractClass
{
public void abstractMethod() { System.out.print("abstractMethod()"); }
public void implementedMethod() { System.out.print("Overridden!"); }
}
In this case, you have overridden implementedMethod().
However, because of the final keyword, the following is not possible.
public class ImplementingClass extends AbstractClass
{
public void abstractMethod() { System.out.print("abstractMethod()"); }
public void implementedMethod() { System.out.print("Overridden!"); }
public void finalMethod() { System.out.print("ERROR!"); }
}
You can't do this because the implementation of finalMethod() in AbstractClass is marked as the final implementation of finalMethod(): no other implementations will be allowed, ever.
Now you can also implement an abstract class twice:
public class ImplementingClass extends AbstractClass
{
public void abstractMethod() { System.out.print("abstractMethod()"); }
public void implementedMethod() { System.out.print("Overridden!"); }
}
// In a separate file.
public class SecondImplementingClass extends AbstractClass
{
public void abstractMethod() { System.out.print("second abstractMethod()"); }
}
Now somewhere you could write another method.
public tryItOut()
{
ImplementingClass a = new ImplementingClass();
AbstractClass b = new ImplementingClass();
a.abstractMethod(); // prints "abstractMethod()"
a.implementedMethod(); // prints "Overridden!" <-- same
a.finalMethod(); // prints "finalMethod()"
b.abstractMethod(); // prints "abstractMethod()"
b.implementedMethod(); // prints "Overridden!" <-- same
b.finalMethod(); // prints "finalMethod()"
SecondImplementingClass c = new SecondImplementingClass();
AbstractClass d = new SecondImplementingClass();
c.abstractMethod(); // prints "second abstractMethod()"
c.implementedMethod(); // prints "implementedMethod()"
c.finalMethod(); // prints "finalMethod()"
d.abstractMethod(); // prints "second abstractMethod()"
d.implementedMethod(); // prints "implementedMethod()"
d.finalMethod(); // prints "finalMethod()"
}
Notice that even though we declared b an AbstractClass type, it displays "Overriden!". This is because the object we instantiated was actually an ImplementingClass, whose implementedMethod() is of course overridden. (You may have seen this referred to as polymorphism.)
If we wish to access a member specific to a particular subclass, we must cast down to that subclass first:
// Say ImplementingClass also contains uniqueMethod()
// To access it, we use a cast to tell the runtime which type the object is
AbstractClass b = new ImplementingClass();
((ImplementingClass)b).uniqueMethod();
Lastly, you cannot do the following:
public class ImplementingClass extends AbstractClass, SomeOtherAbstractClass
{
... // implementation
}
Only one class can be extended at a time. If you need to extend multiple classes, they have to be interfaces. You can do this:
public class ImplementingClass extends AbstractClass implements InterfaceA, InterfaceB
{
... // implementation
}
Here's an example interface:
interface InterfaceA
{
void interfaceMethod();
}
This is basically the same as:
abstract public class InterfaceA
{
abstract public void interfaceMethod();
}
The only difference is that the second way doesn't let the compiler know that it's actually an interface. This can be useful if you want people to only implement your interface and no others. However, as a general beginner rule of thumb, if your abstract class only has abstract methods, you should probably make it an interface.
The following is illegal:
interface InterfaceB
{
void interfaceMethod() { System.out.print("ERROR!"); }
}
You cannot implement methods in an interface. This means that if you implement two different interfaces, the different methods in those interfaces can't collide. Since all the methods in an interface are abstract, you have to implement the method, and since your method is the only implementation in the inheritance tree, the compiler knows that it has to use your method.
A Java class becomes abstract under the following conditions:
1. At least one of the methods is marked as abstract:
public abstract void myMethod()
In that case the compiler forces you to mark the whole class as abstract.
2. The class is marked as abstract:
abstract class MyClass
As already said: If you have an abstract method the compiler forces you to mark the whole class as abstract. But even if you don't have any abstract method you can still mark the class as abstract.
Common use:
A common use of abstract classes is to provide an outline of a class similar like an interface does. But unlike an interface it can already provide functionality, i.e. some parts of the class are implemented and some parts are just outlined with a method declaration. ("abstract")
An abstract class cannot be instantiated, but you can create a concrete class based on an abstract class, which then can be instantiated. To do so you have to inherit from the abstract class and override the abstract methods, i.e. implement them.
A class that is declared using the abstract keyword is known as abstract class.
Abstraction is a process of hiding the data implementation details, and showing only functionality to the user. Abstraction lets you focus on what the object does instead of how it does it.
Main things of abstract class
An abstract class may or may not contain abstract methods.There can be non abstract methods.
An abstract method is a method that is declared without an
implementation (without braces, and followed by a semicolon), like this:
ex : abstract void moveTo(double deltaX, double deltaY);
If a class has at least one abstract method then that class must be abstract
Abstract classes may not be instantiated (You are not allowed to create object of Abstract class)
To use an abstract class, you have to inherit it from another class. Provide implementations to all the abstract methods in it.
If you inherit an abstract class, you have to provide implementations to all the abstract methods in it.
Declare abstract class
Specifying abstract keyword before the class during declaration makes it abstract. Have a look at the code below:
abstract class AbstractDemo{ }
Declare abstract method
Specifying abstract keyword before the method during declaration makes it abstract. Have a look at the code below,
abstract void moveTo();//no body
Why we need to abstract classes
In an object-oriented drawing application, you can draw circles, rectangles, lines, Bezier curves, and many other graphic objects. These objects all have certain states (for ex -: position, orientation, line color, fill color) and behaviors (for ex -: moveTo, rotate, resize, draw) in common. Some of these states and behaviors are the same for all graphic objects (for ex : fill color, position, and moveTo). Others require different implementation(for ex: resize or draw). All graphic objects must be able to draw or resize themselves, they just differ in how they do it.
This is a perfect situation for an abstract superclass. You can take advantage of the similarities, and declare all the graphic objects to inherit from the same abstract parent object (for ex : GraphicObject) as shown in the following figure.
First, you declare an abstract class, GraphicObject, to provide member variables and methods that are wholly shared by all subclasses, such as the current position and the moveTo method. GraphicObject also declared abstract methods, such as draw or resize, that need to be a implemented by all subclasses but must be implemented in different ways. The GraphicObject class can look something like this:
abstract class GraphicObject {
void moveTo(int x, int y) {
// Inside this method we have to change the position of the graphic
// object according to x,y
// This is the same in every GraphicObject. Then we can implement here.
}
abstract void draw(); // But every GraphicObject drawing case is
// unique, not common. Then we have to create that
// case inside each class. Then create these
// methods as abstract
abstract void resize();
}
Usage of abstract method in sub classes
Each non abstract subclasses of GraphicObject, such as Circle and Rectangle, must provide implementations for the draw and resize methods.
class Circle extends GraphicObject {
void draw() {
//Add to some implementation here
}
void resize() {
//Add to some implementation here
}
}
class Rectangle extends GraphicObject {
void draw() {
//Add to some implementation here
}
void resize() {
//Add to some implementation here
}
}
Inside the main method you can call all methods like this:
public static void main(String args[]){
GraphicObject c = new Circle();
c.draw();
c.resize();
c.moveTo(4,5);
}
Ways to achieve abstraction in Java
There are two ways to achieve abstraction in java
Abstract class (0 to 100%)
Interface (100%)
Abstract class with constructors, data members, methods, etc
abstract class GraphicObject {
GraphicObject (){
System.out.println("GraphicObject is created");
}
void moveTo(int y, int x) {
System.out.println("Change position according to "+ x+ " and " + y);
}
abstract void draw();
}
class Circle extends GraphicObject {
void draw() {
System.out.println("Draw the Circle");
}
}
class TestAbstract {
public static void main(String args[]){
GraphicObject grObj = new Circle ();
grObj.draw();
grObj.moveTo(4,6);
}
}
Output:
GraphicObject is created
Draw the Circle
Change position according to 6 and 4
Remember two rules:
If the class has few abstract methods and few concrete methods,
declare it as an abstract class.
If the class has only abstract methods, declare it as an interface.
References:
TutorialsPoint - Java Abstraction
BeginnersBook - Java Abstract Class Method
Java Docs - Abstract Methods and Classes
JavaPoint - Abstract Class in Java
It's a class that cannot be instantiated, and forces implementing classes to, possibly, implement abstract methods that it outlines.
Simply speaking, you can think of an abstract class as like an Interface with a bit more capabilities.
You cannot instantiate an Interface, which also holds for an abstract class.
On your interface you can just define the method headers and ALL of the implementers are forced to implement all of them. On an abstract class you can also define your method headers but here - to the difference of the interface - you can also define the body (usually a default implementation) of the method. Moreover when other classes extend (note, not implement and therefore you can also have just one abstract class per child class) your abstract class, they are not forced to implement all of your methods of your abstract class, unless you specified an abstract method (in such case it works like for interfaces, you cannot define the method body).
public abstract class MyAbstractClass{
public abstract void DoSomething();
}
Otherwise for normal methods of an abstract class, the "inheriters" can either just use the default behavior or override it, as usual.
Example:
public abstract class MyAbstractClass{
public int CalculateCost(int amount){
//do some default calculations
//this can be overriden by subclasses if needed
}
//this MUST be implemented by subclasses
public abstract void DoSomething();
}
From oracle documentation
Abstract Methods and Classes:
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, then the class itself must be declared abstract, as in:
public abstract class GraphicObject {
// declare fields
// declare nonabstract 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, then the subclass must also be declared abstract.
Since abstract classes and interfaces are related, have a look at below SE questions:
What is the difference between an interface and abstract class?
How should I have explained the difference between an Interface and an Abstract class?
Get your answers here:
Abstract class vs Interface in Java
Can an abstract class have a final method?
BTW - those are question you asked recently. Think about a new question to build up reputation...
Edit:
Just realized, that the posters of this and the referenced questions have the same or at least similiar name but the user-id is always different. So either, there's a technical problem, that keyur has problems logging in again and finding the answers to his questions or this is a sort of game to entertain the SO community ;)
Little addition to all these posts.
Sometimes you may want to declare a
class and yet not know how to define
all of the methods that belong to that
class. For example, you may want to
declare a class called Writer and
include in it a member method called
write(). However, you don't know how to code write() because it is
different for each type of Writer
devices. Of course, you plan to handle
this by deriving subclass of Writer,
such as Printer, Disk, Network and
Console.
An abstract class can not be directly instantiated, but must be derived from to be usable. A class MUST be abstract if it contains abstract methods: either directly
abstract class Foo {
abstract void someMethod();
}
or indirectly
interface IFoo {
void someMethod();
}
abstract class Foo2 implements IFoo {
}
However, a class can be abstract without containing abstract methods. Its a way to prevent direct instantation, e.g.
abstract class Foo3 {
}
class Bar extends Foo3 {
}
Foo3 myVar = new Foo3(); // illegal! class is abstract
Foo3 myVar = new Bar(); // allowed!
The latter style of abstract classes may be used to create "interface-like" classes. Unlike interfaces an abstract class is allowed to contain non-abstract methods and instance variables. You can use this to provide some base functionality to extending classes.
Another frequent pattern is to implement the main functionality in the abstract class and define part of the algorithm in an abstract method to be implemented by an extending class. Stupid example:
abstract class Processor {
protected abstract int[] filterInput(int[] unfiltered);
public int process(int[] values) {
int[] filtered = filterInput(values);
// do something with filtered input
}
}
class EvenValues extends Processor {
protected int[] filterInput(int[] unfiltered) {
// remove odd numbers
}
}
class OddValues extends Processor {
protected int[] filterInput(int[] unfiltered) {
// remove even numbers
}
}
Solution - base class (abstract)
public abstract class Place {
String Name;
String Postcode;
String County;
String Area;
Place () {
}
public static Place make(String Incoming) {
if (Incoming.length() < 61) return (null);
String Name = (Incoming.substring(4,26)).trim();
String County = (Incoming.substring(27,48)).trim();
String Postcode = (Incoming.substring(48,61)).trim();
String Area = (Incoming.substring(61)).trim();
Place created;
if (Name.equalsIgnoreCase(Area)) {
created = new Area(Area,County,Postcode);
} else {
created = new District(Name,County,Postcode,Area);
}
return (created);
}
public String getName() {
return (Name);
}
public String getPostcode() {
return (Postcode);
}
public String getCounty() {
return (County);
}
public abstract String getArea();
}
What is Abstract class?
Ok! lets take an example you known little bit about chemistry we have an element carbon(symbol C).Carbon has some basic atomic structure which you can't change but using carbon you can make so many compounds like (CO2),Methane(CH4),Butane(C4H10).
So Here carbon is abstract class and you do not want to change its basic structure however you want their childrens(CO2,CH4 etc) to use it.But in their own way
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.
In other words, a class that is declared with abstract keyword, is known as abstract class in java. It can have abstract(method without body) and non-abstract methods (method with body).
Important Note:-
Abstract classes cannot be used to instantiate objects, they can be used to create object references, because Java's approach to run-time Polymorphism is implemented through the use of superclass references. Thus, it must be possible to create a reference to an abstract class so that it can be used to point to a subclass object. You will see this feature in the below example
abstract class Bike{
abstract void run();
}
class Honda4 extends Bike{
void run(){
System.out.println("running safely..");
}
public static void main(String args[]){
Bike obj = new Honda4();
obj.run();
}
}
An abstract class is one that isn't fully implemented but provides something of a blueprint for subclasses. It may be partially implemented in that it contains fully-defined concrete methods, but it can also hold abstract methods. These are methods with a signature but no method body. Any subclass must define a body for each abstract method, otherwise it too must be declared abstract.
Because abstract classes cannot be instantiated, they must be extended by at least one subclass in order to be utilized. Think of the abstract class as the generic class, and the subclasses are there to fill in the missing information.
Class which can have both concrete and non-concrete methods i.e. with and without body.
Methods without implementation must contain 'abstract' keyword.
Abstract class can't be instantiated.
It do nothing, just provide a common template that will be shared for it's subclass

Categories