create object using abstract classes - java

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.

Related

What is exact difference between Inheritance and Abstract class?

I know the fundamentals of OOP concepts[Inheritance, Abstraction, Encapsulation, Polymorphism]
We use Inheritance in case of Parent-Child relationship[Child can have all functionalities which Parent have and can add more functionality to itself too]
And we use Abstract class(In java) for a partial set of default implementations of methods in a class, which also can be implemented by simple Inheritance.
Look below example which makes my point clear.
Inheritance:
Parent class
public class Parent {
// This method will remain same for all child classes.No need to override
public void abc() {
System.out.println("Parent here");
}
// This methods need to be overridden from child class
public int getROI() {
return 0;
}
}
Child class
public class Child extends Parent{
#Override
public int getROI(){
return 5;
}
public static void main(String[] args) {
Child child =new Child();
child.abc();
System.out.println(child.getROI());
}
}
Abstract Class:
Parent class
abstract class Parent {
// This method will remain same for all child classes.No need to override
public void abc() {
System.out.println("Parent here");
}
// This methods need to be implemented from child class
public abstract int getROI();
}
Child class
public class Child extends Parent{
public int getROI(){
return 5;
}
public static void main(String[] args) {
Child child =new Child();
child.abc();
System.out.println(child.getROI());
}
}
For above programs o/p will be same.
O/P:
Parent here
5
So I think,
Inheritance: We need to override the method in child class
Abstract class: Put abstract keyword in method name and need to implement the method in child class
So Inheritance and abstract class is same regardless of abstract keyword
So we can implement abstract class using inheritance, here just method signature change classes(That's my belief).
Is there any significant difference?
Inheritance is for inheriting properties and having some of its own as well.
Abstract is to restrict from being instantiated.
Example:
Lets take Vehicle and VehiclePart. But Vehicle as such is very abstract and not complete. So we want Vehicle class abstract because we don't want to instantiate it directly. Car is more meaningful entity than Vehicle and car is a Vehicle. So car extends vehicle and it is not abstract.
abstract class Vehicle{
String name;
}
abstract class VehiclePart{
String name;
Date expiry;
}
class Car extends Vehicle{
List<VehicleParts> parts;
}
class RacingCar extends Vehicle{
}
class Gear extends VehiclePart{
int numOfGears;
}
Inheritance: We need to override the method in child class
Nope. in the above example you can see Car is inheriting properties like name from Vehicle. Overriding is optional. Like RacingCar can override methods of Car and make it a little bit custom. But basically it is getting(inheriting) some properties from base class. Like all the basic properties of a car will in Car and not in RacingCar. RacingCar will have properties specific to it.
Abstract class: Put abstract keyword in method name and need to
implement the method in child class
Nope. It is just to restrict its instantiation. Eg. We don't want to instantiate Vehicle object because there is no meaning to it. A vehicle has to be something like car, bus etc etc. It can't just be a vehicle. So we put abstract and restrict instantiation.
After java 8 you can have static and default methods in Interface. So it makes the interface much similar to abstract class.
But Still abstract class is class so we can have constructor, instance variable,
getter and setter to change the state of objects. These all functionalities not provided by interface .That is main difference between interface and abstract class after java 8.
With inheritance you don't need to override a method. Without overriding getROI in Child you could still call new Child().getROI() and get 0 as response.
If on the other hand a method is abstract, it will need to be implemented by the child as there is no default implementation.
An abstract class means you can't instantiate it directly.
new Parent()
is not allowed.
An abstract method will need to be implemented in an extended class.
Abstract Class:
Abstraction hides the implementation details and shows only the functionality to the user.
Abstraction helps to reduce the complexity of the code.
We can't create objects of an abstract class.
Inheritance:
Inheritance is the methodology of creating a new class using the properties and methods of an existing class.
Inheritance helps to improve code reusability.
We can create the object of the parent class.
These are two different concept and selections are based on the requirements.
Abstraction hide the implementation details and only show the functionality. It reduce the code complexity. Inheritance create a class using a properties of another class. It improve the code reusability.
So these are two different things for different purposes.
If this is about the implementation(coding), obviously there are differences than putting abstract keyword in the method name.
Can't implement method body in abstract methods in abstract class. But can implement method body in methods in parent class.
In inheritance, child class inherits is parents methods. Same as in abstraction also child class inherits non-abstracts methods of parent class as they are. But child class must implement all the abstract methods in parent class, otherwise child class need to be declared as abstract.
Can't create instance of abstract class.

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

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.

Abstract class with no methods

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

Is there a way to guarantee an interface extends a class in Java?

Suppose I have the following situation:
public abstract class Vehicle {
public void turnOn() { ... }
}
public interface Flier {
public void fly();
}
Is there a way that I can guarantee that any class that implements Flier must also extend Vehicle? I don't want to make Flier an abstract class because I want to be able to mix a few other interfaces in a similar manner.
For instance:
// I also want to guarantee any class that implements Car must also implement Vehicle
public interface Car {
public void honk();
}
// I want the compiler to either give me an error saying
// MySpecialMachine must extend Vehicle, or implicitly make
// it a subclass of Vehicle. Either way, I want it to be
// impossible to implement Car or Flier without also being
// a subclass of Vehicle.
public class MySpecialMachine implements Car, Flier {
public void honk() { ... }
public void fly() { ... }
}
Java interfaces cannot extend classes, which makes sense since classes contain implementation details that cannot be specified within an interface..
The proper way to deal with this problem is to separate interface from implementation completely by turning Vehicle into an interface as well. The Car e.t.c. can extend the Vehicle interface to force the programmer to implement the corresponding methods. If you want to share code among all Vehicle instances, then you can use a (possibly abstract) class as a parent for any classes that need to implement that interface.
You could rearrange your classes and interfaces like this:
public interface IVehicle {
public void turnOn();
}
public abstract class Vehicle implements IVehicle {
public void turnOn() { ... }
}
public interface Flier extends IVehicle {
public void fly();
}
This way all implementations of Flier are guaranteed to implement the protocol of a vehicle, namely IVehicle.
If you have control on the Vehicle classes just extract Vehicle as an interface and then provide a base implementation.
If you have no control over Vehicle class, for example because it is part of a framework you are using or a third party library, it's not possible to do in Java.
The closest thing you can do is using Generics multiple wildcards notation.
<T extends Vehicle & Car>
But you can't really apply it directly to Car unless you do something like this:
public interface Car<T extends Vehicle & Car>() {
T self();
}
Which is bot weird and do not enforce the self method to actually return self, it's just a strong hint/suggestion.
You would implement a Car like this:
public class CitroenC3 extends Vehicle implements Car<CitroenC3> {
#Override
public CitroenC3 self() {
return this;
}
}
one can use a Car<?> like this:
Car<?> car = obtainCarInSomeWay();
Vehicle v = car.self();
Car c = car.self();
they should be both valid syntax.
What the compiler enforce here is that what you specify in Car<WHICH> as WHICH must both extend Vehicle and implement Car. And by adding self() you are saying to the programmer that the T object is supposed to be the object itself, thus forcing the wildcard instance to match the class if he want to be compliant with the specification.
in Java 8 you can even define a default implementation for the self method.
I also wish there was a better way to handle something like this.
It's a strange requirement, but you can accomplish something of the sort with Generics:
<T extends MyInterface & MyAbstractClass>
This question shows that you haven't grasped the essence of interface and class. Forgetting the concrete Java syntax right now, all you need to understand first is that: interface is a set of protocol, which should be implementation-agnostic. It makes no sense to let an interface extend a class(which is implementation-oriented).
Back to your concrete question, if you want to guarantee that a Flier is always a kind of Vehicle, just change the latter to an interface and let former extends it(It does make sense to extend one protocol from the other protocol). After that, you may create any class(abstract or concrete) that implements Vehicle or Flier.
Define a new Package
Create a new interface (ie. HiddenOne) with scope "default" with a method "implementMe(HiddenOne)"
Move Vehicle and Flier to the new Package.
Inherit Vehicle and Flier from HiddenOne
Implement the method implementMe in Vehicle.
Now: Whenever you like to implement from "Flier" you must extends from Vehicle !
(because only Vehicle can implement implementMe).
This is tricky but works great.

confused about JAVA interface [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What does it mean to “program to an interface”?
Interface vs Abstract Class (general OO)
I'm new to learn JAVA and now I'm confused about interface. I have searched and read many materials but still not clear.
When I try to find some information about interface, I see many people talked about the relationship between interface and abstract class. But I even don't know why they contrast these two. Because I think abstract class is used to tell other people you can not create an object of this abstract class and if you want, you must modify the abstract class. This is something about inheritance, right?
But I don't know the meaning of interface. There is a interface a, and if a class B is going to implement the interface a, it must use the reserved word class B implements a, and then complete all the methods that the interface requires. But my question is, if class B have to complete all the methods by itself, what's the meaning of interface? I think we don't need it.
I don't understand it very much. I read many sentences like: "interface can reflect the core thought of object-oriented language", "interface can help make the program easier" and so on. But I can not really understand the meaning.
So, does anyone can show me some examples to let understand interface? Or you can tell me some useful links or the books that describe the interface clearly. I really hope to figure it out. THANK YOU!
Suppose you have a Car class and Vegetable class which is unrelated in real life and there is a common behaviour called wash(). Because we can wash a car and wash a vegetable too. But washing a car and washing a vegetable is totally different process/behaviour.
For ex: Car should be washed with a power pump, Vegetables under your kitchen sink. So the way of washing is different. So you make the washing process as a method wash() in the interface say Washable and you implement them in both Car and Vegetable class.
interface Washable {
public void wash();
}
public class Car implements Washable {
public void wash() {
// wash the car with a power pump
}
}
public class Vegetable implements Washable {
public void wash() {
// wash the vegetable under a kitchen sink
}
}
As a person, you would want to wash a car as well as vegetable.
public class Person {
Washable washableObject = new Car();
washableObject.wash();
washableObject = new Vegetable();
washableObject.wash();
}
So interface is a way to connect unrelated classes which has a common behavior.But the behavior will be differently implemented or can be changed in future.
One day you decide to change the way you wash a Car.Suppose you have purchased a "car washing machine". So the implementation changes inside the method wash() in the Car class.
public class Car implements Washable {
public void wash() {
// wash the car with my new car washing machine !!
}
}
But as a Person , you still call the wash() method. The way the wash() method is being implemented changed ( washing the car with your new car washing machine ), this implementation change did not affect your Person class.
Hope you are clear why we use interfaces now.
Basically, interface is a way to accomplish multiple inheritance without actually having to do it. (Which is not to say that the Java folks "wimped out" -- multiple inheritance is exceedingly messy and inefficient to implement.)
What this means is that you can have two totally separate classes A and B, with no common ancestor other than Object, and, if they implement the same interface, you can substitute one for the other (so long as you reference only methods in the interface).
A simple code to understand the interface and class.
import java.util.List;
import java.util.ArrayList;
public class Q01 {
List<Shape> shapes= new ArrayList();
public void add() {
shapes.add(new Square(3.0));
shapes.add(new Circle(2.0));
}
public void print() {
for (int i = 0; i < shapes.size(); i++) {
Shape shape = shapes.get(i);
System.out.println(shape.getClass().getSimpleName() + " --->" + shape.getArea());
}
}
public static void main(String[] args) {
Q01 q01= new Q01();
q01.add();
q01.print();
}
public interface Shape {
double getArea();
}
public class Square implements Shape{
private double edge;
public Square(double edge) {
this.edge = edge;
}
public double getArea() {
return edge*edge;
}
}
public class Circle implements Shape{
private double radius;
public Circle(double radius) {
this.radius = radius;
}
public double getArea() {
return 3.14 * radius * radius;
}
}
}
Think in interfaces like contracts between a class and the user. When a class implements an interface is telling that it promise to offer all the methods defined by the interface.
Assuming you understand class inheritance, I think of an Interface like a skeleton class, where the structure of a class is described but not actually written/implemented.
Another class can then work with any class that implements a particular Interface even if it hasn't been implemented yet.
For example, someone may create an Interface called Animal. Its methods maybe: Talk(), Walk() and Eat(). You could write a Dog class that implements Animal that prints "woof" when the Talk() method is called. Therefore another class will know how to work with all classes that implements the Animal interface.
UPD
A good real world example is the JDBC Database Statement Interface. This sets out a number of required properties that a database manufacturer will have to implement, such as execute(String sql). Oracle will implement this differently from Postgresql. This allow the database to be swapped for another one but the user code remains the same.

Categories