Abstract methods in Java - java

I want to write an abstract method but the compiler persistently gives this error:
abstract methods cannot have a body
I have a method like this:
public abstract boolean isChanged() {
return smt else...
}
What is wrong here?

Abstract methods means there is no default implementation for it and an implementing class will provide the details.
Essentially, you would have
abstract class AbstractObject {
public abstract void method();
}
class ImplementingObject extends AbstractObject {
public void method() {
doSomething();
}
}
So, it's exactly as the error states: your abstract method can not have a body.
There's a full tutorial on Oracle's site at: http://download.oracle.com/javase/tutorial/java/IandI/abstract.html
The reason you would do something like this is if multiple objects can share some behavior, but not all behavior.
A very simple example would be shapes:
You can have a generic graphic object, which knows how to reposition itself, but the implementing classes will actually draw themselves.
(This is taken from the site I linked above)
abstract class GraphicObject {
int x, y;
...
void moveTo(int newX, int newY) {
...
}
abstract void draw();
abstract void resize();
}
class Circle extends GraphicObject {
void draw() {
...
}
void resize() {
...
}
}
class Rectangle extends GraphicObject {
void draw() {
...
}
void resize() {
...
}
}

If you use the java keyword abstract you cannot provide an implementation.
Sometimes this idea comes from having a background in C++ and mistaking the virtual keyword in C++ as being "almost the same" as the abstract keyword in Java.
In C++ virtual indicates that a method can be overridden and polymorphism will follow, but abstract in Java is not the same thing. In Java abstract is more like a pure virtual method, or one where the implementation must be provided by a subclass. Since Java supports polymorphism without the need to declare it, all methods are virtual from a C++ point of view. So if you want to provide a method that might be overridden, just write it as a "normal" method.
Now to protect a method from being overridden, Java uses the keyword final in coordination with the method declaration to indicate that subclasses cannot override the method.

The error message tells the exact reason: "abstract methods cannot have a body".
They can only be defined in abstract classes and interfaces (interface methods are implicitly abstract!) and the idea is, that the subclass implements the method.
Example:
public abstract class AbstractGreeter {
public abstract String getHelloMessage();
public void sayHello() {
System.out.println(getHelloMessage());
}
}
public class FrenchGreeter extends AbstractGreeter{
// we must implement the abstract method
#Override
public String getHelloMessage() {
return "bonjour";
}
}

Related

Abstract class and interfaces in java

Any body can tell me
when to use the abstract class and when to use interface?
So many websites having only differences. I am not able to get these terms
"when to use the abstract class and when to use interface"
Thanks in Advance
Interfaces
An interface is kinda* like a template. Say for example that you want to make a 'Shape' class. Not all shapes use the same formulas for calculating area, so you just establish that there has to be a "getArea" method, but you don't define it.
A simple example:
public interface Shape
{
public int getArea();
}
Then you can have a class that implements the Shape interface:
public class Rectangle implements Shape
{
//this works for rectangles but not for circles or triangles
public int getArea()
{
return this.getLength() * this.getHeight();
}
}
Abstract Classes
Abstract methods can be extended by subclasses.* They differ from interfaces in that they can also contain defined methods.
You can still leave undefined methods, but you must label them abstract.
An example:
public abstract class Vegetable
{
public String vegName;
public boolean edible = true;
public Vegetable(final String vegName, final boolean edible)
{
this.vegName = vegName;
this.edible = edible;
}
public void printName()
{
System.out.println(this.vegName);
}
//to be determined later when implemented
public abstract void drawOnScreen();
}
Then we can extend this abstract class.
public class Carrot extends Vegetable
{
//we must define the abstract methods
public void drawOnScreen()
{
//we can still use our other methods
this.printName();
//do some other thing that is specific to this class
}
}
Interfaces cannot contain implementation (at least prior to Java 8) so if you need "common" method implementation, you have to have it in a super class (be it abstract or concrete)
However, any class can have only one super class (but many interfaces). so an interface is the solution for polymorphism when you have a class that already got a super class

Same method with different return types in abstract class and interface

Just extending the question..
Same method in abstract class and interface
Suppose a class implements an interface and extends an abstract class and both have the same method (name+signature), but different return types. Now when i override the method it compiles only when i make the return type same as that of the interface declaration.
Also, what would happen if the method is declared as private or final in the abstract class or the interface?
**On a side note. Mr. Einstein stuck to this question for an abominable amount of time during an interview. Is there a popular scenario where we do this or he was just showing off?
If the method in abstract class is abstract too, you will have to provide its implementation in the first concrete class it extends. Additionally, you will have to provide implementation of interface. If both the methods differ only in return type, the concrete class will have overloaded methods which differ only in return type. And we can't have overloaded methods which differ only in return type, hence the error.
interface io {
public void show();
}
abstract class Demo {
abstract int show();
}
class Test extends Demo implements io {
void show () { //Overloaded method based on return type, Error
}
int show() { //Error
return 1;
}
public static void main (String args[]) {
}
}
No, same method names and parameters, but different return types is not possible in Java. The underlying Java type system is not able* to determine differences between calls to the methods at runtime.
(*I am sure someone will prove me wrong, but most likely the solution is considered bad style anyways.)
Regarding private/final: Since you have to implement those methods, neither the interface method nor the abstract method can be final. Interface methods are public by default. The abstract method can't be private, since it must be visible in the implementing class, otherwise you can never fulfill the method implementation, because your implementing class can't "see" the method.
With Interfaces the methods are abstract and public by default ,
so they cant have any other access specifier and they cant be final
With abstract class , abstract methods can have any access specifier other than private and because they are abstract they cant be final
While overriding , the method signature has to be same ; and covariant(subclass of the declared return type) return types are allowed
A class cannot implement two interfaces that have methods with same name but different return type. It will give compile time error.
Methods inside interface are by default public abstract they don't have any other specifier.
interface A
{
public void a();
}
interface B
{
public int a();
}
class C implements A,B
{
public void a() // error
{
//implementation
}
public int a() // error
{
//implementation
}
public static void main(String args[])
{
}
}

An abstract class in Java need not implement any methods from its implementing interface. Why?

Let's look at the following simple code snippet in Java.
interface Sum
{
abstract public void showSum();
}
interface Mul
{
abstract public void showMul();
}
abstract class Super implements Sum
{
protected int x;
protected int y;
public Super(int x, int y)
{
this.x=x;
this.y=y;
}
//No error, though the method showSum() of the implementing iterface Sum is commented. Why?
/*public void showSum()
{
System.out.println("Sum = "+(x+y));
}*/
}
final class Calculation extends Super implements Mul
{
public Calculation(int x, int y)
{
super(x,y);
}
public void showSum()
{
System.out.println("Summation = "+(x+y));
}
//If showMul() is commented , it would issue a compile-time error. Why?
public void showMul()
{
System.out.println("Multiplication = "+(x*y));
}
}
final public class Main
{
public static void main(String[] args) throws IOException
{
Scanner s=new Scanner(System.in);
System.out.print("\nEnter a number : ");
int x=s.nextInt();
System.out.print("\nEnter another number : ");
int y=s.nextInt();
Calculation c=new Calculation(x,y);
c.showSum();
c.showMul();
}
}
Since the interface Sum containing only one method showSum(); is being implemented by the abstract class Super , there should be necessary for the abstract class Super to implement that method showSum();. The compiler however doesn't complain at all and the program is working well with no problem at all. Why?
Similarly, the non-abstract final class Calculation is implementing the Mul interface and contains the actual implementation of the method showMul(); presented in it's implementing interface. In case, if this method showMul() in the class Calculation is commented, it issues a compile-time error. Why is the same thing not applicable to that abstract class Super?
The abstract class is not real implementation class. It may contain abstract methods and doesnot need to implement the methods from the interface. It is concern of the REAL implementing class to define the abstract/interface methods.
See this difference between abstract class and interface
Interface:
public interface InterfaceClass {
void interfaceMethod();
//no method definition
}
//Abstract Class implementing InterfaceClass
abstract class AbsClass implements InterfaceClass{
abstract void abstractMethod();
public void doSomethingCommon() {
System.out.println("Abstract class may contain method definition");
}
//no need to implement methods of InterfaceClass because AbsClass is abstract
}
And here is real class that extends AbsClass: Its duty of RealClass to define all abstract methods and interface methods. Additionally, it may override the defined methods in abstract class as well.
public class RealClass extends AbsClass{
#Override
public void interfaceMethod() {
//implement interface method here
}
#Override
void abstractMethod() {
}
// you may override the doSomethingCommon() of AbsClass too
#Override
public void doSomethingCommon() {
// TODO Auto-generated method stub
super.doSomethingCommon();
}
}
Why there is no compile time error on AbsClass:
We cannot create instances of abstract class. That's why there is no meaning of displaying error at compile time.
Abstract classes behavior resembles interfaces in this case.
From the Java Tutorial: ...abstract classes are similar to interfaces, except that they provide a partial implementation, leaving it to subclasses to complete the implementation. If an abstract class contains only abstract method declarations, it should be declared as an interface instead
You don't implement methods in an interface that extends another interface. And you don't HAVE to implement methods in an abstract class that implements an interface.
Because it's abstract. An abstract class is a class which is allowed to declare some methods without providing any implementation of those methods, forcing concrete subclasses doing it. You could add the method
#Override
public abstract void showSum();
to the abstract class, but it would just be redundant with the method already declared in the interface.
This ought to be comment to JB Nizet's answer, but I cant post comments yet :(
Note that you could provide the implementation for the showSum() method in your abstract class, and still have that class remain abstract without any problems. An abstract class could have all methods implemented and still be abstract!
From Oracle's Java tutorial:
a class that implements an interface must implement all of the
interface's methods. It is possible, however, to define a class that
does not implement all of the interface's methods, provided that the
class is declared to be abstract.
Reference document: https://docs.oracle.com/javase/tutorial/java/IandI/abstract.html , section When an Abstract Class Implements an Interface.

overriding, overloading and hiding in OOP

I know these 3 concepts.
But I remember there was another definition:
Say a base class has 2 virtual methods: Foo() and Foo(int a).
Is there any rule that when a derived class overrides Foo(int a) has to override all other overloads of Foo ?
Was it in Java? I believe it dosn't exist in C#.
Thanks
No, there is no such rule, at least not in Java. Such a rule would be incredibly limiting as sometimes a subclass only has a new implementation of one of those overloads, etc.
This is not a rule in Java. Were you thinking of an interface? If a class implements an interface it must have an implementation of each method declared on the interface.
C++:
What you are referring to is name hiding in C++. When you have a class with overrided methods, and you extend this class an override one of the overrided methods, you need to override all the overloaded methods. If not, calls to non-overridden overloaded in the extended class won't work.
For example:
class Base {
public:
virtual void A (int);
virtual void A (int, int);
};
void Base::A(int i) {
std::cout << “Hi\n”;
}
void Base::A (int i, int j) {
std::cout << “Bye!!\n”;
}
Suppose you only override one of the methods:
class Sub: public Base {
public:
void A(int);
};
void Sub::A(int i) {
std::cout << “Hey, La!\n”;
}
void main () {
Sub a;
a.A(1);
a.A(1, 1);//won't compile
}
The second call won’t work, as A(int, int) is not visible. This is name hiding.
If you want to circumvent this, you can use the using keyword as follows:
class Sub: public Base {
public:
void A(int);
using Base::A;
};
void Sub::A(int i) {
std::cout << “Hey, La!\n”;
}
void main () {
Sub a;
a.A(1);
a.A(1, 1);//will compile
}
Java:
Java doesn't have such a concept though. You can try this out yourself. Note that all Java methods are virtual by default as per virtual C++ methods.
public class Base {
public void A() {
System.out.println("Hi");
}
public void A(int i, int j) {
System.out.println("Bye");
}
}
public class Sub extends Base {
public void A() {
System.out.println("Hey, La!");
}
}
public class Test {
public static void main(String[] args) {
Sub a = new Sub();
a.A();
a.A(1, 1);//perfectly fine
}
}
Aside:
I hope you're not referring to extending an abstract class- if you extend an abstract class, you need to override all abstract methods else your class has to be declared abstract.
All methods of an implemented interface need to be implemented though.
No Actually that does not apply in Java. However if you implement an interface, then you need to have implementation for all methods in it. But when you are using extends i.e inheritance, then you override the methods you want, and in this case the Foo(int x) is different from the Foo() regardless if their return types are the same or not.
However if you want to create non-abstract class (extending a base class), you have to implement all abstract methods.
just to add to what others have already said, in java each method is identified distinctly using its full signature which includes its return type, name and arguments. so when you define a abstract method(virtual function) you define it as abstract only for that function with its signature.
anyhow you could have tried this in ur IDE for fun and would have got the answer in a minute. :P

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