Interface, Abstract Class and Methods of Abstract Class - java

I am learning how to use the Factory pattern for creating objects in Java. I want to create classes to manage Cars. A car can either be small or large. I created an interface that defines the methods to be implemented by an implementing class. An abstract class implements some of the common methods of the interface shared by small and large cars. The concrete SmallCar and LargeCar classes implement the remaining methods of the abstract class.
THE CAR INTERFACE
public interface Car {
String getRegistrationNumber();
void drive();
}
THE ABSTRACT CAR CLASS IMPLEMENTS CAR INTERFACE
public abstract class AbstractCar implements Car {
private final RegistrationNumber regNumber;
private boolean tankFull = true;
public AbstractCar(RegistrationNumber regNumber) {
this.regNumber = regNumber;
}
#Override
public final String getregistrationNumber() {
return regNumber.toString();
}
/**This method is not defined in the implemented Car interface. I added it to
*the abstract class because I want subclasses of these abstract class
*to have this method*/
public boolean isTankFull() {
return tankFull;
}
}
SMALL CAR EXTENDS ABSTRACT CLASS
public final class SmallCar extends AbstractCar {
public SmallCar(RegistrationNumber regNum) {
super(regNum);
}
#Override
public void drive() {
//implemented here
}
}
FACTORY CLASS:
This class is responsible for creating instances of a particular type of car.
public final class CarFactory {
public static Car createCar(String carType, RegistrationNumber regNum) {
Car car = null;
if (carType.equals("Small") {
car = new SmallCar(regNum);
}
return car;
}
MAIN METHOD
RegistrationNumber regNum = new RegistrationNumber('a', 1234);
Car c = CarFactory.createCar("Small", regNum);
c.getRegistrationNumber(); //this works
c.isTankFull(); //this instance of Car cannot access the isTankFull method defined on the abstract class. The method is not defined on the Car interface though. I do not understand why.
The challenge is that the instance of Car can access every other method defined on the Car interface but it cannot access the isTankFull() method defined on the abstract class but not defined on the interface. I hope my explanation is clear enough.

The reason why you can't see the method there is because your c object is declared as a Car interface. Granted, when it comes out of your factory method, it is a SmallCar, but your variable there is only the interface. You could either change your declaration to AbstractCar c = CarFactory.createCar("SmallCar", regnum);.
Another way you could accomplish this while working with the interface would be to cast your c object to an AbstractCar when trying to access methods that are not on the interface, however you need to be careful as there is always the possibility that your factory could return an object that implements Car, but not AbstractCar.
if (c instanceof AbstractCar) {
((AbstarctCar)c).isTankFull();
}
Of course, the other easy solution would be to add the method to the interface, though that would remove the teaching opportunity from this question.

The good solution is to put your isTankFull() on the interface. It makes sense as any car implementing Car would need access to isTankFull().
The question is: are you creating any Car that will not be able to answer the question isTankFull? If so, then moving isTankFull to the interface will not make sense.
Another solution (if you don't want your isTankFull() to be on the interface), is to cast your Car to the appropriate type:
if (c instanceof AbstractCar) {
((AbstractCar)c).isTankFull();
}

An interface is a contract (or a protocol) that you made with the users of the classes that implement it. So you have to ask to yourself if any Car should expose the information isTankFull (i.e. should respond to message isTankFull). If the answer is 'yes', then the method isTankFull must be added to the interface.
Looking at your code, it seems that the class AbstractCar is only a utility class. Then, the method isTankFull should be lift up to interface, or it should be made at least protected.
On the other hand you have to ask yourself if your client code, i.e. main method, really needs a generic Car, or if it needs instead a specific kind of car, such as a SmallCar.
Finally, rember that the use of interface lets you minimize dependency between your components.

Related

Interfaces and Comparable

i'm beginner and just learning abstract classes and interfaces but really struggeling to get it right.
MY Class structure.
Abstract Class Vehicle
Class Car (extends Vehicle, implements ITuning)
Class Motorcycle (extending Vehicle)
Interface ITuning
I want to have an abstract method doRace() that I can use in my Car class to compare the Car Objects (car.getHp()) and prints the winner. I try to implement a doRace(object o) into the Interface ITuning and a doRace(Car o) into my Car class but get the error. How can I implement that correctly ?
The type Car must implement the inherited abstract method
ITuning.doRace(Object)
But if do chage it to Object, i can't use it in my Car class…
public interface ITuning
{
abstract void doRace(Object o1);
}
public Car extends Vehicle implements ITuning
{
public void doRace(Car o1){
if(this.getHp() > o1.getHp())
};
}
Any Idea what i'm doing wrong? I assume its a comprehension error
You can make ITuning generic.
public interface ITuning<T> {
void doRace(T other);
}
Implementation will be like this:
public class Car extends Vehicle implements ITuning<Car> {
#Override
public void doRace(Car other) {
//do comparison
}
}
Implementation in other classes will be quite similar, just change the generic parameter.
As a side note, i would rename the interface to something more fitting. Considering that tuning a vehicle is the act of modifying it to optimise its' performance, ITuning providing functionality to do the actual racing is counter intuitive.
You can change your ITuning interface to
public interface ITuning
{
void doRace(Vehicle other);
}
Since Vehicle defines the getHp() method this ensures that your actual implementation can access it.
The difference to Chaosfire's answer is that this will allow you to do a race between different types of vehicles, e.g. a Car and a Motorcycle, while the generic ITuning<T> class will be limited to races between equal types*.
Chaosfire's point regarding the interface name is still valid.
*This is a bit over-simplified to make my point clearer. Of course Car could implement ITuning<Car> and ITuning<Motorcycle> but this may not be what you want.

Could not instantiate the type (Class)? [duplicate]

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

Java - Is it possible to extend all the subclasses of a class with a single class?

Java - Is it possible to extend all the subclasses of a class with a single class?
Let's explain it with an example, the actual code is quite more complex. I have an Animal class with its own class hierarchy. Let's say that it has two subclasses: Testarrosa and Viper.
public class Car {
public abstract String getManufacturer();
}
public class Testarossa extends Car{
public String getManufacturer(){
return "Ferrari";
}
}
public class Viper extends Car{
public String getManufacturer(){
return "Dodge";
}
}
I want to extend all the Car subclasses with a RegisteredCar subclass.
public class RegisteredCar extends Car {
private String plateNumber;
public RegisteredCar (String plateNumber){
this.plateNumber=plateNumber;
}
public String getPlateNumber() {
return plateNumber;
}
}
At some point, I should be able to create a new RegisteredCar of a specific subclass. Something like
RegisteredCar c = new RegisteredCar<Viper>("B-3956-AC");
And call the c.getManufacturer() to obtain "Dodge" and c.getPlateNumber() to obtain B-3956-AC. Obviously, I should still be able to create a Car c = new Viper();
That is an example. Having an attribute in Car with null value if not registered is not enough for what I need.
In short, no that is not possible. You have to unfortunately modify your object model.
For example, what about having a Registration class this way:
public interface Registration<C extends Car> {
C getCar();
String getPlateNumber();
}
This way you can extract the information relating to registration in a single class, while maintaining your Car models.
You can then do helper methods like:
Registration<Viper> registeredViper = createRegistration(new Viper(), "B-3956-AC");
As others have said, no thats not really possible and your example could be solved by changing your model
As an alternative to inheritance you could use another class to wrap a Car instance.
I would make Car an interface (though having RegisteredCar extend Car should work too) and then attempt something like the following pseudo code:
class RegisteredCar<T extends Car> implements Car {
private final T car
RegisteredCar(T car) {
this.car = car;
}
... methods for RegisteredCar
... methods from Car delegating to `this.car`
}
Please excuse the somewhat bad code, I don't have an IDE open, and I always mess up generics without an IDE to hand.
Another possible solution is to use AOP, though I don't know how in fashion that is these days as but what you are describing could be a cross cutting concern.
A final alternative might be to use a language that allows for Extensions, Traits, Protocol or some other type of 'mix in'
In java it is prohibited to extends more than 1 class.
You could build chain from classes to extends, for example.
To solve the problem of mutiple inheritance in Java → interface is used
You should avoid inheritance as much as possible. Use abstractions (interfaces) to make your code elegant and maintainable. Just google why extends is evil.
public interface Car{
String getManufacturer();
}
public interface Registerable{
boolean isRegistered();
void register(String plateNumber);
void getPlateNumber();
}
public class Viper implements Car, Registerable
{
//all methods
}
With Generic class approach as described in other answer, you will not be able to use RegisteredCar where your require to pass Car object. e.g. suppose you need to generate some invoice.
Invoice getInvoice(Car c);
In this method you cannot use RegisteredCar as it is not of Type Car. All you API which require Car are not applicable to RegisteredCar. In some cases you may need Plate Number as well as Car, There you may need to keep mapping of Plate Number and Cars. I would suggest following approach based on Decorate Pattern and delegate all Car calls to passed car object
public class RegisteredCar extends Car{
public RegisteredCar(Car c, String plateNumber){
}
#Override
String getColor(){
c.getColor();
}
}
No, it's not like C++. Multiple inheritance is not possible in Java. However you can implement multiple interfaces.
You cannot achieve that with inheritance.
Your best option is making the RegisteredCar type generic, then having a generic instance variable that holds the intended type car:
public class RegisteredCar<T extends Car> {
private String plateNumber;
private T car;
public T getCar() {
return this.car;
}
public T setCar(T car) {
this.car = car;
}
public RegisteredCar (String plateNumber){
this.plateNumber=plateNumber;
}
public String getPlateNumber() {
return plateNumber;
}
}
With this, you will be able to pass into RegisteredCar an object of any type that's a subclass of Car.
As you can notice, I have removed the extends Car part of this class, as it doesn't need to be a subclass of car itself.
Is there a reason, in the real classes, that you couldn't simply add the new feature to the existing base class?
public abstract class Car
{
public abstract String getManufacturer() ;
protected String plate_number = null ;
public String getPlateNumber()
{ return this.plate_number ; }
public boolean isRegistered()
{ return ( this.plate_number != null ) ; }
}

How to access the members of the concrete class using the reference variable of the abstract class

My abstract class has only three methods. My concrete class which extends the abstract class has price,name,packing. how can i access those properties using the reference variable of abstract class having instance of the concrete class. Directly i can't access any of the get set methods of the concrete class using this reference variable. Is there any special pattern for this problem????
According to my design, i have to assign the instance of the concrete class to the reference variable of the abstract class. I can't create the direct object of the concrete class.
With a reference to the abstract class alone, you can't do much.
However, you can type cast it to the corresponding concrete class.
eg: if you have class A and class B extends class A, you can do something like
if(obj instanceof B){
//type cast obj to class B here and call the respective method of B
((B)obj).concreteClassMethod();
}
Here obj is the reference variable of the abstract class A. This way, you can access any method (or public property) of class B, keeping the reference, however as class A.
Example:
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 declares abstract methods for methods, such as draw or resize, that need to be implemented by all subclasses but must be implemented in different ways. The GraphicObject class can look something like this:
abstract class GraphicObject {
int x, y;
...
void moveTo(int newX, int newY) {
...
}
abstract void draw();
abstract void resize();
}
Each nonabstract subclass of GraphicObject, such as Circle and Rectangle, must provide implementations for the draw and resize methods:
class Circle extends GraphicObject {
void draw() {
...
}
void resize() {
...
}
}
class Rectangle extends GraphicObject {
void draw() {
...
}
void resize() {
...
}
}
than to acces to the father variable classes you can use: super.(variable)
only if the variable is public or protected.
If the variable is private, you will use get and set methods.
My abstract class has only three methods. My concrete class which extends the abstract class has price,name,packing.
I take it these abstract class methods are not the same as the three concrete class methods. Fine, I'll call these unnamed methods the mystery methods. If it turns out they are the same then just delete the mystery methods you'll see below.
how can i access those properties using the reference variable of abstract class having instance of the concrete class.
By injecting the dependency.
Directly i can't access any of the get set methods of the concrete class using this reference variable.
If they only exist on the concrete class this is no surprise. The only reason not to add them to the abstract class as #JBNizet suggests is if you don't want them exposed to client code. This is a reasonable concern but there is a better way to handle it.
Is there any special pattern for this problem????
Patterns are solutions not problems. What you say you're doing is structurally close to the http://en.wikipedia.org/wiki/Composite_pattern but you have the composition going in the wrong direction. I don't think the composite pattern is going to be what you want here.
According to my design, i have to assign the instance of the concrete class to the reference variable of the abstract class. I can't create the direct object of the concrete class.
There is a way to achieve this without using instanceof and more importantly without the Abstract class even knowing that the Concrete class exists.
public class Driver {
public static void main(String[] args) {
Composition compositionInstance = new Composition( new Concrete() );
System.out.println(compositionInstance);
}
}
public class Composition {
Abstract abstractInstance;
Composition(Abstract abstractInstance) {
if (abstractInstance == null) { throw new IllegalArgumentException("may not be null"); }
this.abstractInstance = abstractInstance;//concrete assigned to abstract ref var
}
public String toString() {
return String.format( "Price: %s, Name: %s, Packaging: %s",
abstractInstance.getPrice(),
abstractInstance.getName(),
abstractInstance.getPackaging() );
}
}
public abstract class Abstract {
void mysteryMethod1() {}
void mysteryMethod2() {}
void mysteryMethod3() {}
abstract String getPrice();
abstract String getName();
abstract String getPackaging();
}
public class Concrete extends Abstract {
String getPrice() {return "42";}
String getName() {return "My Concret Product";}
String getPackaging() {return "cardboard box";}
}
A lot of classes but they are very simple. These class names are terrible so don't imitate them.
Driver doesn't have to touch the getters since it can let Composition do that for it. It only knows how to build Composition and Concrete. It doesn't get chatty with them.
Composition only has to know how to talk to Abstract. It has no idea how to build one or exactly what concrete instance it might get.
Abstract only knows about it self. Doesn't know anyone else. It doesn't want to know.
Concrete only knows about abstract.
By writing the code this way it is kept flexible. It should be easy to make changes as requirements change.
This wasn't written following any set pattern. What it follows are the S.O.L.I.D. principles.

Inheritance in Java instantiating classes polymorphism

What is the advantage of writing:
Bicycle bike = new RoadBike(...);
instead of
RoadBike bike = new RoadBike(...);
Assuming RoadBike extends Bicycle of course.
I ask because even if I write
RoadBike bike = new RoadBike(...);
I can still use all the methods in Bicycle because of the extension, so what is the point of writing it the other way?
Thanks!
If Bicycle were an interface, it would allow you to just pass around that interface and make your methods more "generic" or "polymorphic".
If you had another class, StreetBike,(and it implemented the Bicycle Interface) you could use that class and RoadBike to say call method 'ride' and each class would ride differently based on the implementation.
Public Interface Bicycle {
public ride();
}
public StreetBike implements Bicycle{
public ride(){
System.out.println("I am riding on the street");
}
}
public RoadBike implements Bicycle{
public ride(){
System.out.println("I am riding on the road");
}
}
Taking it a step further we can use this SIMPLE example, but I think it gets the point across
//PERSON POJO
public Person {
//properties
public rideBike(Bicycle bike){
bike.ride(); //could be StreetBike or RoadBike, depends on what you pass in. That's the power of it.
}
}
The clearest way to express polymorphism is via an abstract base class (or interface)
public abstract class Bicycle
{
...
public abstract void ride();
}
This class is abstract because the ride() method is not defined for Bicycle. It will be defined for the subclasses RoadBike and MountainBike. Also, Bicycle is an abstract concept . It’s got to be one or the other.
So we defer the implementation by using the abstract class.
public class RoadBike extends Bicycle
{
...
#Override
public void ride()
{
System.out.println("RoadBike");
}
}
and
public class MountainBike extends Bicycle
{
...
#Override
public void ride()
{
System.out.println("MountainBike");
}
}
Now we can difference by calling Bicycle at runtime base class Bicycle but due to run time binding respective subclass methods will be invoked .
public static void main(String args)
{
ArrayList<Bicycle> group = new ArrayList<Bicycle>();
group.add(new RoadBike());
group.add(new MountainBike());
// ... add more...
// tell the class to take a pee break
for (Bicycle bicycle : group) bicycle.ride();
}
Running this would yield:
RoadBike
MountainBike
...
Hope this will clear you what the difference is !
The advantage is that Bicycle reference is more general and can refer to any object which has Bicycle in its inheritance hierarchy for example MountainBike. It offers more flexibility and does not binds you to concrete implementation. This is one of the basic principles in OOP. That said, there are some cases, like when used in short method when using Bicycle or RoadBikemakes no difference. Also there is the aspect of invoking overloaded methods which is determined by reference type at compile time (depending on the reference type, different method might be called even thought they point to the same object) but having those kinds of overlaoded methods is not advised.
You might get better explanation here.

Categories

Resources