What is exact difference between Inheritance and Abstract class? - java

I know the fundamentals of OOP concepts[Inheritance, Abstraction, Encapsulation, Polymorphism]
We use Inheritance in case of Parent-Child relationship[Child can have all functionalities which Parent have and can add more functionality to itself too]
And we use Abstract class(In java) for a partial set of default implementations of methods in a class, which also can be implemented by simple Inheritance.
Look below example which makes my point clear.
Inheritance:
Parent class
public class Parent {
// This method will remain same for all child classes.No need to override
public void abc() {
System.out.println("Parent here");
}
// This methods need to be overridden from child class
public int getROI() {
return 0;
}
}
Child class
public class Child extends Parent{
#Override
public int getROI(){
return 5;
}
public static void main(String[] args) {
Child child =new Child();
child.abc();
System.out.println(child.getROI());
}
}
Abstract Class:
Parent class
abstract class Parent {
// This method will remain same for all child classes.No need to override
public void abc() {
System.out.println("Parent here");
}
// This methods need to be implemented from child class
public abstract int getROI();
}
Child class
public class Child extends Parent{
public int getROI(){
return 5;
}
public static void main(String[] args) {
Child child =new Child();
child.abc();
System.out.println(child.getROI());
}
}
For above programs o/p will be same.
O/P:
Parent here
5
So I think,
Inheritance: We need to override the method in child class
Abstract class: Put abstract keyword in method name and need to implement the method in child class
So Inheritance and abstract class is same regardless of abstract keyword
So we can implement abstract class using inheritance, here just method signature change classes(That's my belief).
Is there any significant difference?

Inheritance is for inheriting properties and having some of its own as well.
Abstract is to restrict from being instantiated.
Example:
Lets take Vehicle and VehiclePart. But Vehicle as such is very abstract and not complete. So we want Vehicle class abstract because we don't want to instantiate it directly. Car is more meaningful entity than Vehicle and car is a Vehicle. So car extends vehicle and it is not abstract.
abstract class Vehicle{
String name;
}
abstract class VehiclePart{
String name;
Date expiry;
}
class Car extends Vehicle{
List<VehicleParts> parts;
}
class RacingCar extends Vehicle{
}
class Gear extends VehiclePart{
int numOfGears;
}
Inheritance: We need to override the method in child class
Nope. in the above example you can see Car is inheriting properties like name from Vehicle. Overriding is optional. Like RacingCar can override methods of Car and make it a little bit custom. But basically it is getting(inheriting) some properties from base class. Like all the basic properties of a car will in Car and not in RacingCar. RacingCar will have properties specific to it.
Abstract class: Put abstract keyword in method name and need to
implement the method in child class
Nope. It is just to restrict its instantiation. Eg. We don't want to instantiate Vehicle object because there is no meaning to it. A vehicle has to be something like car, bus etc etc. It can't just be a vehicle. So we put abstract and restrict instantiation.

After java 8 you can have static and default methods in Interface. So it makes the interface much similar to abstract class.
But Still abstract class is class so we can have constructor, instance variable,
getter and setter to change the state of objects. These all functionalities not provided by interface .That is main difference between interface and abstract class after java 8.

With inheritance you don't need to override a method. Without overriding getROI in Child you could still call new Child().getROI() and get 0 as response.
If on the other hand a method is abstract, it will need to be implemented by the child as there is no default implementation.

An abstract class means you can't instantiate it directly.
new Parent()
is not allowed.
An abstract method will need to be implemented in an extended class.

Abstract Class:
Abstraction hides the implementation details and shows only the functionality to the user.
Abstraction helps to reduce the complexity of the code.
We can't create objects of an abstract class.
Inheritance:
Inheritance is the methodology of creating a new class using the properties and methods of an existing class.
Inheritance helps to improve code reusability.
We can create the object of the parent class.

These are two different concept and selections are based on the requirements.
Abstraction hide the implementation details and only show the functionality. It reduce the code complexity. Inheritance create a class using a properties of another class. It improve the code reusability.
So these are two different things for different purposes.
If this is about the implementation(coding), obviously there are differences than putting abstract keyword in the method name.
Can't implement method body in abstract methods in abstract class. But can implement method body in methods in parent class.
In inheritance, child class inherits is parents methods. Same as in abstraction also child class inherits non-abstracts methods of parent class as they are. But child class must implement all the abstract methods in parent class, otherwise child class need to be declared as abstract.
Can't create instance of abstract class.

Related

Can we create an object of abstract class?

I am just confused about abstract class concept. Please clear my doubt. Definition of Abstract class says we can not create object of such class, then what we called like A a = new A() { }. Example is below:
public abstract class AbstractTest {
public abstract void onClick();
public void testClick() {
}
}
public class A {
AbstractTest test = new AbstractTest() {
#Override
public void onClick() {
}
};
}
Then test is a object or what?
test is an object of an anonymous concrete sub-class of AbstractTest (note that it implements all the abstract methods of AbstractTest), which is why this sub-class can be instantiated.
On the other hand,
AbstractTest test = new AbstractTest();
wouldn't pass compilation, since that would be an attempt to instantiate an abstract class.
You are mixing up object and reference.
AbstractTest test = new AbstractTest() {
#Override
public void onClick() {
}
};
test here is a reference to a anonymous class that extends AbstractTest, the above code is like saying:
class MyClass extends AbstractTest {
#Override
public void onClick() {
}
}
AbstractTest test = new MyClass(); // test is a reference to a MyClass object
Abstract Class in my opinion needs to be explained together with Interface.
Interface allows you to specify operations that are supported/allowed on objects with that interface. More specifically Objects are instances of a Class which implements that Interface. Defining an interface allows you to describe a group of different classes of objects so that other objects can interact with them in the same manner.
Abstract Class is one step between interface and a Class (loosely speaking). Abstract Class allows you to specify operations that are supported by classes that extend it, but it also allows you to implement (some of) those operations. This way you can implement common methods for a group of classes in that abstract class. Other methods in the abstract class that are not implemented (aka abstract methods) need to be implemented by the class that extends it. The fact that you didn't implement all methods on an Abstract class naturally means you can't instantiate it (create an object of such class). There are other useful implementations for Abstract classes (i.e. callbacks).
In your example what you see there is that you are not really trying to just create an object that Abstract class you are also providing implementation of abstract method onClick();
That is the only way you can "create an instance of the abstract class" - technically speaking you are creating an instance of an Anonymous class (that is extending your abstract class) for which you provide implementation of inherited abstract methods.

Abstract class with no methods

Is there a use case where we would need an abstract class with no methods defined in it? I bumped into creating such an abstract class just for the sake of generics so that users will pass only subtypes of this class. But I want to know if either is valid or there is a better way to do it.
Having an abstract class with no methods is legal, yet entirely pointless. You use abstract classes to share implementation. If a class has no methods, it has no implementation to share.
If you need to share some common variables (I assume that your abstract class has at least some fields, otherwise it is entirely empty) you would be better off with composition and an interface, like this:
class CommonData {
// Some getters and setters for items that you wish to share
}
interface WithCommonData {
CommonData getCommonData();
}
Your classes can put the common data as a member, and implement the interface WithCommonData, giving you access to the common data, and letting the classes keep their inheritance structure.
If you need to "mark" a user class, doing it with a "marker interface" (i.e. an interface with no methods) is a lot more flexible, because the users retain an ability to build their own chain of inheritance.
Creating an abstract class just because other classes should be of that type is not neccessary. This can instead be achieved using interfaces.
Since a class only can extend one class but implement any number of interfaces, using an interface as an instance validator will not limit a solution with respect to inheritance.
Example:
public interface Vehicle {
// No methods, we just want several classes to be identified as of type Vehicle
}
public class Car implements Vehicle {
// is a vehicle
}
public class Motorcycle implements Vehicle {
// is a vehicle
}
public class Banana {
// is not a vehicle
}
public class Main {
public static void main(String[] args) {
Object o = new Car();
if(o instanceof Vehicle) {
// Ok
}
Object p = new Banana();
if(p instanceof Vehicle) {
// Will never get here
}
}
}

How to use Abstract Class/ Interface correctly?

I have a problem with my abstract class.
Here is my interface:
package dovilesUzduotis4;
import java.util.ArrayList;
public interface Interface1 {
void a(ArrayList<K> kM, String g);
}
and abstract class:
package dovilesUzduotis4;
import java.util.ArrayList;
public abstract class Service implements Interface1 {
public void iK(ArrayList<Ks> kM, String g){
K aK = new K(g);
kM.add(aK);
}
}
But when I try to use service.iK(kM,g); in main I get the error "service cannot be resolved". How can I correct that?
Please paste in the main method first.
My guess is you forgot to instantiate an object of the class:
Service service= new Service() { //create an object of the class
}; //brackets are there because the Service is abstract class and I am redefining it.
service.iK(kM, g); //invoke a method an that object
Now, I don't think that the Service class needs to be abstract. You render the class abstract if you expect a user to implement a method (or methods) of that class that is marked as abstract in a manner that suits his needs. Needless to say, I don't see any abstract method in your Service class.
So it comes to this:
if the class is NOT abstract, you instantiate it as:
Service service= new Service();
if the class is abstract, you must redefine it at place:
Service service= new Service() {
//here you could implement an abstract method or redefine an existing one
};
First of all, Java is case-sensitive meaning that service and Service are different things. The error you just got: service cannot be resolved says, that service class is expected, while you have Service class.
Remember, that class names should implement the CamelCase, while variable names should start with a small letter.
To call methods you must either:
Create an object and access its method
Or make the method static
In the first case, you have to implement a child class:
SubService extends Service {}
because service is abstract and is expected to be extended.
Then:
SubService service = new SubService();
service.method();
In the second case, you do not have to extend the class, static methods can be called.
public abstract class Service implements Interface1 {
public static void iK(ArrayList<Ks> kM, String g){ //static method
K aK = new K(g);
kM.add(aK);
}
}
Then:
Service.iK(arg0, arg1);
This topic is suitable only for deletion.
ArrayList operates on Ks type, and you guys are putting inside it an K type object...
You should extend this class, or make it not abstract (by implementing interface) if you want to instantiate it.
Your specific example seems to be related to some sort of webservice api. Without the backing code to the abstract class we can't really help you there.
I think we can start with some simple fundamentals related to interfaces and abstract classes, since that seems to be your question.
Abstract classes are classes that you cannot, by definition, create an instance of. What darijan did to "construct" and instance of the abstract class is he is creating an anonymous inner class for the Service abstract type.
Service service= new Service() { }; // notice the curly braces, this is an anonymous class definition
There are many different schools of thought and opinions related to best practices with abstract classes and interfaces. What we really are talking about here is the heart of OOP, in my opinion. Abstract classes are meant to provide APIs with or without concrete implementation, so that they may be overridden and specialized for a specific purpose.
This would be a decent example:
public class Car {
String make;
public car (String make) { this.make = make; }
}
public class Hondacar extends Car{
public Hondacar() { super("honda"); }
}
Now you have the definition of what states define a "Car" object, and then you specialize that into the definition of a "Hondacar".
Hopefully this makes sense.
Onto interfaces... Interfaces are declarations of a public API. They are a "contract" that implementing classes must abide by. A class that implements an interface must, by definition, implement all methods on that interface. YOU CAN THINK of an interface as an abstract class with only abstract methods, where classes that subclass that abstract class will need to override every method on that supertype(this draws parallels to the "#override" annotation on implemented interface methods) though many will probably discourage this way of thought. I am not sure what you are trying to do with your specific example since it does not have any names that I can even draw inference from so I can't really help you there.
So drawing on the whole car example, a similar design would be:
interface Car {
String getMake();
}
class HondaCar implements Car {
private static final make = "honda";
#override
public String getMake() { return HondaCar.make; }
}
You can see how the interface does not provide any sort of implementation at all, it merely defines the public API that an implementing class must offer.

create object using abstract classes

I am trying to understand better oop ,but I don't understand how to use abstract classes.
I have a car class, and a car can be mercedes , audi and volvo. Mercedes cars can have 5 passengers ,can open door and block windows; audi car can have 6 passengers, and just can open door. Volvo car can only have 3 passengers.
So, in order to do this, I created an interface:
public interface Car{
void openDoor();
void blockWindows();
int passengers=0;
}
then for each car I created an abstract class:
public abstract class Mercedes implements Car{
public void openDoor(){
System.out.println("Mercedes opendoor");
}
public void blockWindow(){
System.out.println("Mercedes blockwindow");
}
public Mercedes()
{
int passengers=5;
}
public abstract class Audi implements Car{
public void openDoor(){
System.out.println("Audi opendoor");
}
public Audi()
{
int passengers=6;
}
}
public abstract class Volvo implements Car{
public Volvo()
{
int passengers=6;
}
Now, I need to create an object that can transport maximum 15 cars. So I wrote:
public class TransportCars{
Car[] transport=new Car[15];}
//now I need to put in transport array differents types of cars. But I can not instantiate abstract classes. Should I use anything else? I used abstract classes because I can implement an interface and use just o part of it
Basically your design is completely wrong, as you are yet new to java, you first need to understand basic.
Design should be like this :
Car is a Vehical, so is-a relationship.
So you can create a Class Vehicle.
class Vehicle {
// properties of Vehicle like type of Vehicle, numberOfWheels etc.
String vType;
int numberOfWheels;
int passengers;
}
// Car is a Vehicle so it should extend Vehicle
class Car extends Vehicle {
String type; // sedan or hatchback
String manufacturer; // Mercedes, BMW, Audi, Volvo etc.
}
If you want to restrict Vehicle not to be instantiated, you can declare it as an abstract class
Interfaces and abstract classes have some similarities, but are not the same. For your example, you should probably make Car an abstract and have Mercedes, Audi, and Volvo extend that abstract class. Then make sure to implement any abstract methods in Car in each of your classes which extend it. Doing so will make them concrete classes, which can be instantiated.
One thing you can do with abstract classes which you cannot with interfaces, is include data. I see you're already doing that with your interface for number of passengers, but in an interface, the value will be static and final.
I see the problem why it's hard for you to understant abstraction, it's because your example is wrong. The type of car must be a concrete class which inherits from an abstract class. The specificity of an abstract class is that you can't create one of it, you can only inherit it ,that benefits polymorphism. But the real benefits comes from abstract methods.
Instead of creating a Car interface ,create a Vehicle interface.
Since you don't know how many passengers each type of car can carry make Car an abstract
class. Every vehicle have to start and stop. And you know that a car must load the passengers first in order to start. In the end you can start all your vehicles regardless what type car is it , οr what type of vehicle.
interface Vehicle {
public start();
public stop();
}
abstract class Car implements Vehicle {
protected wheels = 4;
public start() {
loadPassengers();
// do extra stuff like
//closeDoors();
}
abstract public loadPassengers();
}
public class Volvo extends Car {
int passengers = 6;
public loadPassengers() {
doSomething(this.passengers);
}
}
public static void main() {
List<Car> cars = new ArrayList<Car>();
cars.add(new Volvo());
cars.add(new Mercedes());
for(Car car : cars) {
car.start();
}
}
In terms of relationships between classes, there's notmuch differences between abstract classes and interfaces: You can't instantiate any of them and they would be used as a template for objects depending on them. You can implement partially the methods of an abstract class however, but even if all of them are implemented still you can't instantiate a class defined as abstract. To be concise:
Interfaces:
Define methods.
A class can implement several interfaces.
Public visibility (or package, by default).
Can't be instantiated.
Abstract classes:
Define methods and may implement them.
A class can inherit from only one class (abstract or not).
User defined visibility.
Can't be instantiated.
If your cars are meant to implement several interfaces, use interfaces, but their scope will have to be public or package. If you just want to have an inheritance relation with one class, use abstract.
It seems that you are going about this the wrong way. It would be better for you to seek a tutorial, but I will try to clear up as much as I can for you:
The car class should be either an interface or an abstract class (or neither).
If it's an interface, than Mercedes, Audi and Volvo should implement it.
If that is the case, any method in "car" must be implemented in the others, so all of them must have "Open door" and "Block windows". you must choose for each of the implementing classes how it will implement it.
If it's an abstract class, you can have some of the methods implemented in "car" and they will work "as is" in Mercedes, Audi and Volvo (which will "extend" car), unless you re-define them in their respective classes. if you want to enforce their implementation in each of inheriting classes, you can define those methods to be abstract in "car", and not implement them in car at all.
If you want to implement all of the methods in car, you don't need it to be abstract at all. You could still re-define them as mentioned above.

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