How do I share methods with instance variables in a superclass? - java

I have an abstract class called Car. Then I have two subclasses, Ford and Dodge which both extend Car. Each of these subclasses have a method called move(). The code in this method is identical for Ford and Dodge, so naturally my instinct was to throw this method implementation into the Car superclass so I don't have to have the same code twice in both my subclasses, i.e. get duplicated code, and just have this method written out once in code inside the superclass, and each subclass can call it when it needs to.
Now here's my...thing: Inside the move methods in each subclass, instance variables from each subclass are being manipulated. So you see, even though the code is identical, what is happening in each move()-method is depending on the state of that specific subclass's instance variables. Like this:
abstract class Car {
// I want to put move()-method in here and erase it from subclasses
}
class Ford extends Car {
private int rpm;
public void move(){
dosomestuff + rpm // value of rpm being used here is unique to Ford
}
}
class Dodge extends Car {
private int rpm;
public void move(){
dosomestuff + rpm // value of rpm being used here is unique to Dodge
}
}
I want to have it like this, and call move() in the superclass from each subclass using the subclasses instance variables:
abstract class Car {
move(){
// do stuff that is identical to Ford and Dodge but
// dependent on different instance variables
}
}
class Ford extends Car {
private int rpm;
}
class Dodge extends Car {
private int rpm;
}
Should I create variables inside the superclass Car? But that is what I am having problem wrapping my head around, because I know an abstract class cannot be instantiated! So if I were to pass the rpm-variable in this case as a parameter in the move() method like move(rpm), while I am having the implementation for move() only inside the Car class, I would have to return the rpm-variable to get its manipulated value back. This works, for once instance variable form a subclass. The problem is, the move-methods depend on several different kinds of variables. So I would have to return several variables back to the subclass each time but I am not sure how to do that.
I am confused. How can I condense this "duplicated code" inside my subclasses into the superclass Car and still be able to manipulate instance variables from the different subclasses inheriting from the Car class? Do I pass them as parameters and return them? Do I do something with get-set methods? I am so unsure...

Use protected variables
abstract class Car {
protected int rpm;
move(){
// ACCESS RPM HERE, which would be specific to implementing class
}
}
class Ford extends Car {
}
class Dodge extends Car {
}
Since the variable rpm is now protected, it will be accessible to the sub-classes of Car and when you instantiate Ford or Dodge, it would have it's own rpm value.
Makes sense?

I do not know if this answers your questions but sub classes inherit the methods of super classes so I would put everything in the abstract class and use getter setter (or access-mutate) methods to use all the variables in the abstract class. I notice someone has stated protected variables which will work sometimes but not if you need encapsulation within your package. I would do this:
public abstract class Car{
private int rpm;
public int getRPM(){return rpm;}
public void move(){//do move using getRPM() to access the data}
}
class Ford extends Car {
}
class Dodge extends Car {
}
So then the only thing different between Ford and Doge will be the constructor which is often times good when you are subclassing

As others have written, you can pull your instance variables into your base class; and make them either protected; or provide getters for them; but honestly, I think that most likely will lead to a bad design.
The thing is: inheritance should be used to provide behavior to its subclasses, not variables.
Meaning: you consider carefully what kind of behavior you want to "share"; and then you think about the open closed principle to implement it the right way, like:
abstract class Base {
public final void doTheCommonThing() {
System.out.println("but we need subclass stuff: " + getFromSubclass());
}
protected abstract String getFromSubclass();
}
The whole point of data encapsulation is that your base class should not know about variables in child classes; and vice versa. Because those are implementation details that nobody else has a business knowing about.

Related

Abstraction and Data Hiding in java

I'm trying to understand the concept of abstraction in java. When I came through some tutorials they said that Abstraction is a process where you show only “relevant” data and “hide” unnecessary details of an object from the user.
This is a simple example of how abstract classes are working.
public class Demo {
public static void main(String[] args) {
Animal a = new Dog();
a.sound();
}
}
abstract class Animal {
abstract void sound();
}
class Dog extends Animal {
#Override
public void sound() {
System.out.println("woof");
}
}
I understand that though abstract classes we can implement common methods in sub classes like sound() method.
What I don't understand is how that help with data hiding and viewing necessary data only.
Please explain this concept to me.
If you have good example please include that too.
In your example, you create a Dog and then use it as an animal. In this case, the abstraction is not very useful, because you know that the variable a always refers to a dog.
Now let's say that in some other class you have a method soundTwice:
class OutsideWorld {
static void soundTwice(Animal a) {
a.sound();
a.sound();
}
}
Here you don't know what kind of Animal a refers to, but you can still sound twice.
UPDATE
I'm adding this class because the class Demo doesn't hide much: it needs to know about class Dog because it creates an instance of it. class OutsideWorld on the other hand doesn't: it only knows about class Animal and what class Animal exposes. It doesn't even know that class Dog exists.
we can now write a class Cat with a different implementation of method sound ("meow"), and we can still use the same soundTwice method with a Cat.
We could then rewrite the Demo class:
public class Demo {
public static void main(String[] args) {
Animal a = new Dog();
OutsideWorld.soundTwice(a);
a = new Cat();
OutsideWorld.soundTwice(a);
}
}
That would, of course, produce the output:
woof
woof
meow
meow
Abstraction in Java is not different then what we use in Software engineering terms.
Abstraction generally answers to WHAT part of your problem statement.
What all operations a system will support?
What is the system meant for?
Think about the abstract datatypes:
Example Stack
All you care about is
pop() --> return you the top element
push() --> adds the element
You simply don't care about the implementation details. So your java classes are abstracted in the same way.
Abstraction is not just about showing only “relevant” data and “hide” unnecessary details of an object from the user.
Data Abstraction is the property by virtue of which only the essential details are displayed to the user.The trivial or the non-essentials units are not displayed to the user. Ex: A car is viewed as a car rather than its individual components.
In java, abstraction is achieved by interfaces and abstract classes. We can achieve 100% abstraction using interfaces.
The one you are explaining in your example is one just form of it.
In your example of Animal class, if sound() method is not an abstract one and you have some random abstract method in that class, imagine a case someone wrote the Animal class and you are extending it in Dog class. Irrespective of the implementation in Actual Animal class, you can write the code in your current class.
Imagine the you haven't overriden the sound() method in Dog class, still if you call `
Dog d= new Dog(); d.sound();
` will get you the code of Animal sound().[Given: sound() method is not abstract]. The code of Animal class would be executed. Dog object does not even know what the sound() method has in it...but it is still able to make use of it. This process of not knowing but making use of something is what abstraction actually is
As mentioned by Yati Sawhney, pop() and push() methods are quite good examples.
Else,
you can have hascode() and equals() method from Object class,
where no one knows how the calculation is done but you end up with a
number and comparing the references respectively.
Data Hiding/Encapsulation:
Data hiding is not same as Abstraction. Not to confuse one with the other.
Abstraction is hiding the code implementation from other Object/user
whereas Data hiding is achieved by Encapsulation via POJO classes.
Data hiding has to do with the instance variables which decides the
state of the Object. Hiding its content using the setter() and
Getter() methods is Data Hiding/ Encapsulation.
You may wonder, how a getter() method is hiding the data whereas it just returns the data we requested but there is an untold story about the getter/setter methods.
Example: Refer the getName() method from the below code
public class Person {
private int age;
private String name;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
// can restrict the code without displaying data to user
if(condition)//restricted user check
return null;//returning null because the user is not supposed to view the data
return name;
}
}
Abstraction means - not providing/having the implementation details. Imagine you are the authority to decide on what parts a Car must have. You will list those functionalities as abstract methods.
Later you will share this (contract) abstract template to Hundai, Ford etc to have their own implementation to make a complete Car.
Abstraction
Ways to achieve Abstraction
There are two ways to achieve abstraction in java
Abstract class (0 to 100%)
Interface (100%)
Basic Knowledge about :
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.
public abstract class ClassName{
// declare fields
// declare nonabstract methods
abstract void methodName();
}
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.
An abstract method is a method that is declared without an implementation (without braces, and followed by a semicolon), like this:
abstract void methodName(Parameter List);
Abstraction is a process of hiding the implementation details and showing only functionality to the user.
Understanding the real scenario of abstract class:
Consider a situation of making a function to get student strength of any school.
Now we will create an abstract class and abstract function getStrength().
Then every school (Govt or private) can use this abstract method and provide implementation.
//Consider this Code
package stackoverflow;
abstract class StudentStrength {
abstract int getStrength();
}
class GovtSchool extends StudentStrength {
#Override
int getStrength() {
return 100;
}
}
class PrivateSchool extends StudentStrength {
#Override
int getStrength() {
return 200;
}
}
public class GetInfo {
public static void main(String args[]) {
StudentStrength ss;
// referring abstract class and creating object of child class
ss = new GovtSchool();
System.out.println("Student strength in Govt School : "+ ss.getStrength());
// output of above : 100
ss = new PrivateSchool();
System.out.println("Student strength in Private School : "+ ss.getStrength());
// output of above : 200
}
}
Explanation:
In this example, StudentStrength is the abstract class, its implementation is provided by the GovtSchool and PrivateSchool classes.
Mostly, we don't know about the implementation class (i.e. hidden to the end user) and object of the implementation class is provided by the factory method.
In this example, if you create the instance of GovtSchool class, getStrength() method of GovtSchool class will be invoked.
File: GetInfo.java
Student strength in Govt School : 100
Student strength in Private School : 200
ANSWER TO:
What I don't understand is how that help with data hiding and viewing necessary data only.
Like demonstrated in the above code, we are referring the abstract class and using the functionality of the child class hiding the working of child class from the end user.
I hope I was helpful :)

Implement an interface in a specific object

Im trying to implement an interface that should affect some objects of a class but not others.
For example lets say this is my code:
public interface KnowsHowToSwim{
double getHowFast();
}
public class Stable{
Horse pinky = new Horse(veryFast);
Horse lightning = new Horse(veryPretty){
#Override
public float getPrettynessFactor(){
return super.getPrettynessFactor()*10000000000
}
};
Horse wetty = new Horse(soCool); <-- This one should KnowHowToSwim
}
Now, i know I can create a new class that extends horse and implements KnowHowToSwim, but since my application will have a lot of fields from different classes that will implement that interface, I was wondering if there was a way to implement the interface in a specific object similar to how Horse lightning overrides its method.
No you can't.
You wan't something like a trait or mixin, which is not supported in Java.
Java8's default methods in interfaces won't work for you because you need a property in the instance (or access to the instance), which is not possible. Default methods have no reference to this.
Further, from a OO perspective, you have to define a separate class, extending Horse and implementing KnowsHowToSwim. All instances of this are a Horse and know-how-swim. Of course you can create only one instance of it.
However you may define a class inside a method body (i.e. a factory method), a.k.a. local class. This class hold referece to all (effectively final) variables in the method. For example:
public static Horse newSwimmingHorse() {
final Object methodScopeProperty = ...;
class SwimmingHorse extends Horse implements KnowsHowToSwim {
double speed;
double getHowFast(){
methodScopeProperty.doSomething(); //do you need this access?
return speed;
}
}
return new SwimmingHorse();
}
But as long as you don't gain any benefits from the accessible method scope I wouldn't recommend it. Use a static inner class instead, optionally with limited visibility or a package-private class. This keeps your code more cohesive.

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.

Java -- Initializing superclass variables in subclasses?

Okay, so, for example, let's say I have an abstract class called "Vehicle". The Vehicle class, has, among other things, a static variable called wheels, which is not initialized. What I want to do is have other subclasses extending from the Vehicle class, like "Motorcycle", and "Truck", and in these subclasses, have the wheels initialized.
Code:
public abstract class Vehicle {
static int wheels; //number of wheels on the vehicle
}
But the below doesn't work:
public class Motorcycle extends Vehicle {
wheels = 2;
}
Is there a way to do this effectively?
EDIT:
Thank you to all the people who replied so far. I get that making instances is probably a better way to go than to put them all in separate classes, but I don't get the "static" part of java perfectly, so I need a little help here.
What I'm trying to do for my program is have separate sprites for the Motorcycle and Truck classes, and I want them to be static so that I won't have to reload the image every time I create an instance of a Motorcycle or Truck. Other than that, though, they'll have almost identical properties to each other, which is why they'll both be extending from the Vehicle superclass.
The only other way I can see this being done is by just not declaring the sprite variable at the Vehicle class, but at the Motorcycle/Truck class, like below:
public abstract class Vehicle {
//Other coding
}
public class Motorcycle extends Vehicle {
static BufferedImage sprite = //initialize image
//Other coding
}
public class Truck extends Vehicle {
static BufferedImage sprite = //initialize image
//Other coding
}
If 'wheels' is static, there is only one and it will apply to all vehicles at the same time. So tricycle, a motorcycle, an 18-wheeler truck and a Ford will all have the same number of wheels.
That doesn't make sense to me. It would be better to have 'wheels' be an instance variable that is in the parent class but each subclass sets appropriately.
But you can try
Vehicle.wheels = 2;
NOTE: I'm adding to my answer since you added to your question.
I like your idea of having statics in each of the subclasses. But you should make them private. Then put an abstract method in the parent class (Vehicle) like
public abstract BufferedImage getSprite();
Then each direct subclass has to have the same method and it can return the private static variable.
Make the variable static so you only have to load them once. Make them private so that code outside the class itself can't fool with it and introduce bugs. You could make them 'final' if possible so the code in the class itself can't change it after the fact and introduce bugs. (A 'final' variable can't have its value changed but the contents of its value can change. So 'final' isn't a wonderful as it could be.)
What you're trying to do is fundamentally flawed. You could make Motorcycle initialize wheels once:
// Static initializer
static
{
wheels = 2;
}
... or each time an instance was created:
// Instance initializer
{
wheels = 2;
}
But there's just one variable - not one for Motorcycle, one for Truck etc. If you did the same thing for both Truck and Motorcycle, then whichever is initialized last would "win".
It's not clear how you want to use this field anyway - but if you just have a single static field, then that's just going to have a single value - not one per subclass.
Static members are only defined once and are common to every extending class. Changing the value in one of them will affect all of the others.
This is what I believe you really want to achieve:
public abstract class Vehicle {
private int _wheels; //number of wheels on the vehicle
public int getWheels(){return _wheels;}
protected Vehicle(int wheels){
_wheels = wheels;
}
}
public class Motorcycle extends Vehicle {
public Motorcycle(){
super(2);
}
}
public class Car extends Vehicle {
public Car(){
super(4);
}
}
I think there's a significantly more elegant way to do this
What I am about to propose still suffers from the limitation that you need an instance. I don't see any way around that because you want wheels to be exposed as part of the superclass, but the value of wheels is dependent on the subclass and inside of Vehicle there is no notion of a subclass type without an instance.
In my opinion, 'wheels'in this case is neither a static or non-static property. It is class metadata. And the Java way to specify class metadata is via annotations.
What you need is a user-defined annotation like this:
#Documented
#Retention(RetentionPolicy.RUNTIME)
public #interface VehicleMetadata{
int wheels();
}
You then annotate Motorcyle as follows:
#VehicleMetadata(2)
public class Motorcycle extends Vehicle {}
In the superclass you provide an accessor that gets the value of the annotation property. I would recommend you use a "lazy evaluation" approach so you don't use reflection every time you need the value.
Note the use of this to get the instance:
private String wheelsValue;
public String getWheels() {
if (this.wheelsValue== null) {
VehicleMetadatane = null;
for (Annotation annotation : this.getClass().getAnnotations()) {
if (annotation instanceof VehicleMetadata) {
ne = (VehicleMetadata) annotation;
break;
}
}
wheelsValue = ne.wheels();
}
return wheelsValue ;
}
In my opinion, this is the most elegant solution.
The original class declaration:
public abstract class Vehicle {
static int wheels; //number of wheels on the vehicle
}
public class Motorcycle extends Vehicle{...}
public class Truck extends Vehicle{...}
does not work because the static variable goes with the class it was declared in. Static class variables create memory storage for only one instance of the variable per class and not per class object. When the compiler (jvm) sees the static variable in the class Vehicle it allocates memory to that variable and that memory location is static (does not change). Each subsequent use of the Vehicle class whether it is extended or instantiated as an object will point to the same location in memory for the static variable.
In order to use the static variable in the child classes you have to use it inside a method. So, you could in essence re-write your Motorcycle class like this:
class Motorcycle extends Vehicle{
public Motorcycle(){
wheels = 2;
}
}
and it will compile; however, you will may not get the results you expect. For example if you do this in your code (assuming Truck class is declared like Motorcycle class and assigns 4 to wheels and there is a getter method to return the value of wheels).
Motorcycle cycle = new Motorcycle();
Truck pickup = new Truck();
...
System.out.println("Motorcycle has " + cycle.getWheels() + " wheels.");
will print:
Motorcycle has 4 wheels.
If you make a static variable in your objects it will be the same for every Vehicle class you will make, even when you would make another subclass for your abstract Vehicle class. This because of the "nature" of any static variable.
I think you want to use a non-static variable so that for every instance of any subclass of the abstract Vehicle class you can determine the value of the wheels and that is done as following:
public abstract class Vehicle {
public int wheels; //number of wheels on the vehicle
}
and any subclass:
public foo extends Vehicle{
public void someMethode(){
this.wheels = 2;
}
}
You could also do this for the static variable but then you will change it for every instance of any subclass of Vehicle
Hope i helped you
Maybe you'd like to think about the constructors you are using.
public Vehicle(int wheels) {
this.wheels = wheels;
}
public Motorcycle(int wheels) {
super(wheels);
}
public Motorcycle cycle = new Motorcycle(2);
The Motorcycle uses the super constructor that knows what to do with the parameter. It automatically sets wheels to 2.

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