Can any body provide me a practical example/scenario where we make use of abstract class and abstract method in Java? An explanation with sample code would be of help in understanding it conceptually. Thanks
abstract class Car{
public int drivenKm;
//....
public abstract void checkCar();
}
public class Volvo extends Car {
public void checkCar() {
checkWithVolvoTestSpecs1();
}
//you have some Volvo-specific tests implemented here
public void checkWithVolvoTestSpecs1(){
//....
}
}
public class BMW extends Car {
public void checkCar() {
checkWithBMWTest();
}
//you have some BMW-specific tests implemented here
public void checkWithBmWTest(){
//....
}
}
Now you can have a list of Cars containing BMW's or Volvo's.
It sometimes makes no sense to implement a general checkCar()-method, because they need to be checked according to some producer-specific checks. So you should mark the class abstract as well as the method.
Marking the class abstract prevents you from generating a non specific car which can not be checked.
Marking the method abstract is used to not being forced to implement a general car check as well as forcing any derived classes to implement a specific car check.
This grantees that you can call the checkCar()-method for every object in your list of Cars because it is guaranteed that there is no general car object which has no implementation of checkCar() as well as that every specific object (like BMW) in the list has an implementation of that method.
public static void main() {
List<Car> cars = new ArrayList<Car>();
cars.add(new Volvo());
cars.add(new BMW());
foreach(Car c:cars)
c.checkCar();
}
Related
Is there a way we can hide the non mutual methods for types which are not qualified for the specific methods?
Lets say we have an abstract superclass with methods we don't want to expose to the objects themselves. We create a facade with the methods we want to allow for the objects. (We dont want to be able to set a cats age to 32 out of the blue.)
I end up in a scenario where i expose methods for a specific subclass that was actually meant for another subclass. (Even if we in the method can controll that the type is correct)
Scenario:
public abstract class Animal {
//setters and code we want to protect
}
public class Cat extends Animal{
private boolean giveBirth;
public void giveBirth(){giveBirth = true;}
//setters etc
}
public class Bird extends Animal{
private boolean layEgg;
public void layEgg(){layEgg = true;}
//setters etc
}
public class FacadeAnimal {
Animal animal;
public FacadeAnimal(Animal a){
animal = a;
}
public void layEgg(){
if(animal instanceof Bird){
((Bird) animal).layEgg();
}
}
public void giveBirth(){
if(animal instanceof Cat){
((Cat) animal).giveBirth();
}
}
}
So in this case we can control inside the method that the type needs to be Bird if we want to layEgg. But it would also be okay for us to let a Cat layEgg. Even though the logic is taken care of, it's still not very intuitional to give Cat the option to lay eggs.
I was thinking it's possible to create an "facade inheritance structure", where we for every subclass also create a facade for that specific subclass. But in the terms of extensibility, that means we will force future developers to not only create a subclass, but also an implementation of it's facade.
Is this the way to go or can we change the way we wrap this around?
Cheers!
EDIT: Maybe the animalscenario was not very clear.
It could in the same manner be two different cars, where one has turbo and one has not, if the "activateTurbo" method exists in the facade, i would be able to call the activateTurbo method on a car that does not actually have a turbo.
Method names such as giveBirth() and layEgg() are too specific - consider something more common such as:
public abstract class Animal {
public void reproduce();
}
Then each subclass can implement as needed. For examle:
public class Cat extends Animal {
public void reproduce() {
liveBirth();
}
private void liveBirth() {
// ...
}
}
and
public class Bird extends Animal {
public void reproduce() {
layEgg();
}
private void layEgg() {
// ...
}
}
This approach will likely lead to at least some duplicate code in the private methods. As #Lini said, combine with the strategy pattern. A little refactoring, and it changes from inheritance to composition.
I would unify giveBirth() and layEgg() into one single method in Animal, the subclass decides itself what to do.
You can also encapsulate this behavior into a new class something like NextGenerationStrategy with subclasses LayEggStrategy or GiveBirthStrategy.
The subclass of Animal (Bird or Cat) selects itself the strategy. So when you work with Animal you dont care it lays egg or gives birth.
For instance, I have an abstract class implemented like this:
public abstract class Animal
{
public abstract void makeNoise();
}
and I have a child class which is representing an animal that does not make any noise. Which is better?
public class Turtle extends Animal
{
// properties and methods
public void makeNoise()
{
//leave it empty
}
}
or should i simply make it : public abstract void makeNoise(); inside Turtle?
It is better to move the makeNoise() method out of Animal as all the animals doesnot make noise. So create another interface NoiseMaker and add the the makeNoise method inside that.
public abstract class Animal {
// animals methods
}
public interface NoiseMaker {
void makeNoise();
}
public class Turtle extends Animal {
// properties and methods which are applicable for turtle
}
And when you want an animal which makes noise like Lion you can extend Animal class and implement NoiseMaker, so that it has the behaviour of Animal as well as it makes noise.
public class Lion extends Animal implements NoiseMaker {
public void makeNoise() {
// implementation
}
// other properties and methods which are applicable for turtle
}
What people often do: throw some sort of exception, like UnsupportedOperationException or something alike.
But: in the end your are fixing a symptom here.
The point is: extending a base class means that an object of the derived class IS-A object of the base class as well. And you are asking: how to violate the public contract of the base class.
And the answer is: you should not do that. Plain and simple.
Because if you start throwing exceptions here, all of a sudden, a caller that maybe has List<Animal> animals can't simply invoke makeNoise() on each object. The caller has instead to use instanceof (so that he can avoid calling makeNoise() on specific classes) - or try/catch is required.
So the real answer is: step back and improve your model. Make sure that all methods on the base class make sense for derived classes. If not - maybe introduce another layer, like abstract class NoisyAnimal extends Animal.
This is the best use case to use UnsupportedOperationException
You have to implement because of the abstract design. So just implement the method and throw UnsupportedOperationException exception.
Keep it Animal, cause most of the Animal's make sound :) If you move it to Turtle, all the subclasses again have to have their own voice method.
or should i simply make it : public abstract void makeNoise(); inside Turtle?
If you do, Turtle is abstract. So the question isn't which is better, the question is, do you want to be able to instantiate Turtle or not?
If you do, you have to implement the method.
If you are okay with it being abstract, then declare it abstract and don't list the method at all:
public abstract class Turtle extends Animal {
}
You might want to distinguish between Animals making noises or not. Something a long the lines of
public abstract class Animals {}
public abstract class AnimalsNoisy extends Animals { abstract void makeNoise(); }
You would then use Turtle extends Animals. The advantage of this structure is if you have a List of Animals you don't need to worry if they implemented the makeNoise method or not e.g.
for(AnimalsNoisy animal: ListAnimalsNoisy) { animal.makeNoise();}
It is a good example to learn how to make your code loosely coupled.
By loosely coupled I mean, if you decide to change or modify your code you will not touch your previous code. Sometimes it is referred as OPEN-CLOSE principle.
For this first you have to identify what part of your code is frequently changing.
Here the method makingNoise() will have different implementation based on your class.
This design can be achieved in following steps.
1) Make an interface which will have implementation for makeNoise()
method.
public interface NoiseInterface {
public void speak();
}
2) Create concrete implementation for NoiseInterface
eg: For Fox
public class FoxSound implements NoiseInterface {
#Override
public void speak()
{
//What does the fox say ?
Sysout("chin chin chin tin tin tin");
}
}
3: Provide the Noise Interface in Animal Class
public abstract class Animal
{
public NoiseInterface noiseMaker;
public abstract void makeNoise();
}
4: Just provide the Type of NoiseInterface of your choice in Fox Class
public class Fox extends Animal
{
public Fox()
{
noiseMaker = new FoxSound();
}
public void makeNoise()
{
noiseMaker.speak();
}
}
Now Amazing thing about this design is you will never have to worry about the implemetation. I will explain you how.
You will just call
Animal me = new Fox();
fox.makeNoise();
Now in future you want to mute the Fox.
You will create a new Interface Mute
public class Mute implements NoiseInterface {
#Override
public void speak()
{
Sysout("No sound");
}
}
Just change the NoiseBehavior in Fox class constructor
noiseMaker = new Mute();
You can find more on OPEN-CLOSE Principle Here
You may write like this,is this what you want?
public interface NoiseInterface {
void makingNoise();
void makingNoNoise();
}
public class Animal implements NoiseInterface{
#Override
public void makingNoise() {
System.out.println("noising");
}
#Override
public void makingNoNoise() {
System.out.println("slient");
}
}
public class Turtle extends Animal{
#Override
public void makingNoNoise() {
System.out.println("turtle");
super.makingNoNoise();
}
}
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
I have a class called Car, and an extention of Car, called Mazdamx5. Can I create a class that extends Mazdamx5 that contains the properties of Car, but also contains the modified or overridden properties of Mazdamx5, or will this only cause complications? Oh, yeah, forgot the important part. How do I do all this with Car and Mazdamx5 in a different package than my new extention? By import?
You can certainly have class hierarchies like this, but you should consider your design implications a bit closer. Having deeply nested inheritance like that isn't necessary in a lot of cases.
If you want each class to have shared fields, then use protected instead of private for their declaration.
This is entirely legal:
public class Car {
}
public class Mazdamx5 extends Car {
}
public class SomeOtherCar extends Mazdamx5 {
}
Try it out. Perfectly valid to create another class that extends Mazdamx5.
I provide the code example
class Car{
void carDrive() {
S.O.P("car drive");
}
}
class Mazdamx5 extends Car{
void drive() {
S.O.P("drive 2");
}
}
class Car2 extends Mazdamx5 {
void drive() {
S.O.P("Car 2 drive");
}
}
In this case, this class Car2 extends Mazdamx5, overrides method properties of Mazdamx5(drive method), and contins method properties of car(carDrive)
I'm having a bunch of classes that I can not change; all these classes have a common ancestor (other than Object) that declares and implements the majority of their properties and methods.
Let's say, we have an inheritance tree like this (for illustration only):
class Vehicle
class Bicycle extends Vehicle
class Skateboard extends Vehicle
class Boat extends Vehicle
class Car extends Vehicle
class Aircraft extends Vehicle
class Jetplane extends Aircraft
class Helicopter extends Aircraft
...
class Truck extends Vehicle
...
While class Vehicle is actually more like an abstract class (it is not really, but it is never instantiated on its own behalf), objects of class Aircraft are created occasionally.
Now the point: the objects can have interrelationships that are not reflected by the classes. Since it is quite a bouquet of classes and the collection is subject to change every once in a while, it is not practical to maintain a subclass for each of the classes that implement the missing behavior.
My approach is therefore to have one class that serves as a wrapper for the above classes.
The constructor takes as a parameter the class of the respective object, which is then instantiated using reflection.
class VehicleW
{
// fields
public boolean isInitialized=false;
private Vehicle fVehicle;
...
// constructors
public VehicleW(Class aClass, ...)
{
Class VehicleClass = Vehicle.class;
if (!VehicleClass.isAssignableFrom(aClass))
return;
// <the reflection magic here>
...
// and on success mark this object as usable
isInitialized=true;
}
}
A constructor without arguments doesn't really make sense here. But now class Aircraft and its subclasses want some extra properties, so I thought I could establish a class AircraftW extends VehicleW that takes care of them.
The modification then looks like this:
// fields
private Aircraft fAircraft;
// constructors
public AircraftW(Class aClass, ...)
{
Class AircraftClass = AirCraft.class;
if (!AircraftClass.isAssignableFrom(aClass))
return;
// <the reflection magic here>
...
// and on success mark this object as usable
isInitialized=true;
}
But this fails, because Java intelligently inserts a call to the parameterless constructor of the ancestor, which is not present (and doesn't make sense, as already said).
It also doesn't make sense to call the parameterized super(), because I initialize a field of class Vehicle then. Okay, I can later in my AircraftW() just set that field to null, but that doesn't seem right.
Is there a way around this? Or am I taking an absolutely wrong approach? I thought about generics, but I can't seem to find a point using it. Interfaces? I'm not that much of a Java expert, so any recommendations are welcome.
Edit (not unsolved (to avoid the term solved)) Well, below you find a working program. I can't put it down as an answer, because Thomas led me to this code... with his answer... which I accepted as the solution... I can't see what's wrong with that.
Thanks, Thomas, for pointing me in the right direction.
For the sceptical, here the complete source code of a test program:
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
class Vehicle { public Vehicle(){} }
class Bicycle extends Vehicle { public Bicycle(){} }
class Skateboard extends Vehicle { public Skateboard(){} }
class Boat extends Vehicle { public Boat(){} }
class Car extends Vehicle { public Car(){} }
class Aircraft extends Vehicle { public Aircraft(){} }
class Jetplane extends Aircraft { public Jetplane(){} }
class Helicopter extends Aircraft { public Helicopter(){} }
class Truck extends Vehicle { public Truck(){} }
class VehicleW
{
protected Vehicle fVehicle=null;
public boolean isInitialized=false;
public VehicleW(Class aClass)
{
if (checkVehicle(aClass))
if ((fVehicle=makeVehicle(aClass))!=null)
isInitialized=true;
}
protected boolean checkVehicle(Class aClass)
{
Class tClass = Vehicle.class;
return (tClass.isAssignableFrom(aClass));
}
protected Vehicle makeVehicle(Class aClass)
{
Vehicle tVehicle = null;
System.out.format("trying to create %s\n",aClass.toString());
Constructor c;
try
{
c=aClass.getConstructor();
}
catch(NoSuchMethodException e)
{
System.out.format(" no constructor found\n");
return null;
}
try
{
tVehicle=(Vehicle)c.newInstance();
}
catch(InvocationTargetException e)
{
System.out.println(e.toString());
}
catch(InstantiationException e)
{
System.out.println(e.toString());
}
catch(IllegalAccessException e)
{
System.out.println(e.toString());
}
return tVehicle;
}
public Vehicle getVehicle()
{
if (!isInitialized)
return null;
return fVehicle;
}
public Class getWClass()
{
if (!isInitialized)
return null;
return fVehicle.getClass();
}
}
class AircraftW extends VehicleW
{
public AircraftW(Class aClass)
{
super(aClass);
/*
Class tClass=Aircraft.class;
if (!tClass.isAssignableFrom(aClass))
return;
isInitialized=true;
*/
}
#Override
protected boolean checkVehicle(Class aClass)
{
Class tClass = Aircraft.class;
return (tClass.isAssignableFrom(aClass));
}
}
class program
{
public static void tellme(VehicleW vx)
{
String s = "failed";
if (vx.getVehicle()!=null)
s="succeeded";
System.out.format(" making %s for %s %s\n",
vx.getWClass(),vx.getClass(),s);
}
public static void main(String[] args)
{
VehicleW v1, v2, v3;
AircraftW a1, a2, a3;
v1=new VehicleW(Bicycle.class);
tellme(v1);
v2=new VehicleW(Boat.class);
tellme(v2);
v3=new VehicleW(Helicopter.class);
tellme(v3);
a1=new AircraftW(Helicopter.class);
tellme(a1);
a2=new AircraftW(Aircraft.class);
tellme(a2);
a3=new AircraftW(Truck.class);
tellme(a3);
return;
}
}
and the output:
trying to create class Bicycle
making class Bicycle for class VehicleW succeeded
trying to create class Boat
making class Boat for class VehicleW succeeded
trying to create class Helicopter
making class Helicopter for class VehicleW succeeded
trying to create class Helicopter
making class Helicopter for class AircraftW succeeded
trying to create class Aircraft
making class Aircraft for class AircraftW succeeded
making null for class AircraftW failed
This sounds a lot like the factory pattern so you might want to look into that.
What you basically would do is something like this:
class VehicleFactory {
public static Vehicle createAircraft( /*Aircraft specific parameters*/) {
//build and return Aircraft, you can call your reflection magic here
}
public static Vehicle createBoat( /*Boatspecific parameters*/) {
//build and return Boat, you can call your reflection magic here
}
}
Additionally, you might want to look into the builder pattern.
In your approach there are several issues:
Prematurely returning from a constructor would still kept the created object, it might just not be properly initialized (you're using an attribute to signal full initialization but what do you do with uninitialized objects besides removing them? In that case initialized should not be a property of the objects or wrappers themselves).
If you have such a high number of subclasses you might want to check what the differences are. It might be a more flexible approach to use composition instead of inheritance.
Example of the last point:
class Vehicle {
VehicleType type; //e.g. Aircraft, Boat, Car
Set<Features> features; //e.g. 2 wheels, 4 wheels, wings etc.
Behavior behavior; //Class to implement specific behavior, depending on your needs
}
class AircraftBehavior extends Behavior {
void fly() {
//implements flying mechanic
}
//method overridden/implemented from Behavior
#Override
void move() {
fly();
}
}
//create an aircraft
Vehicle aircraft = new Vehicle( VehicleType.AIRCRAFT, new HashSet<Feature>(new WingsFeature()), new AircraftBehavior());
The last part would also be predestined for using the factor or builder pattern.
When child class can not full fill the contract of constructor with parent class. Then at same place exists a design defect.
The issue/reason can be that the child class is not valid as a child class or the parent class has to many functionalities.
For your example is really hard to tell what is breaking the contract. But the best and most flexible thing to work with are interfaces.
You claim that you are not an expert in Java. Interfaces are just a concept in Object Oriented programming in case you look for any carrier in this area you should be familiar with them. SO this might the time for you to learn more about interfaces and software design.