I wrote an easy interface-inheritance example to illustrate what I'm trying to do.
interface Fruit{
public void taste();
}
class Banana implements Fruit {
public String name = "Banana";
public void taste(){
System.out.println("yummy banana!");
}
class Strawberry implements Fruit {
public String name = "Strawberry";
public void taste(){
System.out.println("yummy strawberry!");
}
}
class Lunch<Fruittype implements Fruit> {
public Fruittype fruit;
public void tasteit() {
System.out.println("I'm going to eat a"+ fruit.name + "!" );
// error: name cannot be resolved or is not a field
fruit.taste();
}
}
class exec {
public static void main(String[] args) {
Lunch<Banana> bananalunch = new Lunch<>;
bananalunch.fruit = new Banana();
bananalunch.tasteit();
}
}
So Banana and Strawberry are implementing Fruit. In the class Lunch I'm trying to call the fruit name and its function taste();
While calling the Function taste works just fine, i can't call the name (see: error in the comment)
Wanted Output:
I'm going to eat a Banana!
yummy banana!
Like I said, yummy banana works but the name can't be resolved. I tried to declare "public String name = "default""; in the Fruit interface. Then you can call it, but it will always say "default" and not the name in the actual class.
Is there a way to get a member of a generic Type that implements an interface?
P.S. I need to do it like this, of course this code was only for representation but I have a much larger more complicated code in which i encountered this problem- And I don't want to restructure it if not necessary.
Thank you in advance!
Your problem is caused by trying to access an instance member directly - fruit.name - instead of via a method - fruit.getName().
If you use a getter method, the correct method will be executed and return the required output.
That said, in this particular example it would make more sense to have a single getName() method in a base class, and a single _name variable in that base class, which is initialized to a different value based on the actual type of fruit class.
On the other hand, seeing that your Fruit is an interface rather than a base class, you can have each of the classes which implement that interface have a getName() method returning a different value.
For example:
class Strawberry implements Fruit {
public String name = "Strawberry";
public void taste(){
System.out.println("yummy strawberry!");
}
}
would become:
class Strawberry implements Fruit {
public String getName () {
return "Strawberry";
}
public void taste() {
System.out.println("yummy strawberry!");
}
}
You would have to add getName() to the interface:
interface Fruit {
public String getName();
public void taste();
}
Finally, your Lunch class becomes:
class Lunch<Fruittype implements Fruit> {
public Fruittype fruit;
public void tasteit() {
System.out.println("I'm going to eat a "+ fruit.getName() + "!" );
fruit.taste();
}
}
Case, when class implements interface, means that object of this class can do something that described in interface.
For example, every plane shape has area. So we can determine interface:
interface PlaneShape {
int getArea();
}
Area of square is product of edges. And area of circle is product of
squared radius by pi number divided by 2. So:
class Square implements PlaneShape {
public int edge = 5;
public int getArea() {
return edge*edge;
}
}
class Circle implements PlaneShape {
public int radius = 5;
public int pi = 3.14;
public int getArea() {
return radius*radius*pi/2;
}
}
Interfaces use for abstraction. AreaCalculator operates with plane shapes, so it abstracts from any specific kind of plane shapes. AreaCalculator just knows that any shape can give him area value by executing method getArea(). AreaCalculator don't know anything about special shape fields, like edge or radius.
class AreaCalculator<S implemets PlaneShape> {
public S shape;
public int calculateArea() {
shape.getArea();
}
}
By this way, in your example,Lunch<Fruittype implements Fruit> class don't know anything about fruits inner names, it doesn't "see" this fields, it only can invocate method taste(). You need to add method getName() to interface, and implement it.
On the subject of name="default" in interface. It declared in context of interface and hasn't any relation to implementations.
Related
import java.lang.Math;
public class FiguraProba
{
public abstract class Figura {
public abstract double pole();
public abstract double obwod();
}
public abstract class Czworokat extends Figura {
public double obwod(double bok1, double bok2, double bok3, double bok4)
{
return (bok1+bok2+bok3+bok4);
}
public abstract double pole();
}
public class Kwadrat extends Czworokat {
double bok1;
public Kwadrat(double bokPodany)
{
bok1=bokPodany;
}
public double pole(double bok1) {
return bok1*bok1;
}
}
public class Prostokat extends Czworokat {
double bok1, bok2;
public Prostokat(double bokPodany1, double bokPodany2)
{
bok1=bokPodany1;
bok2=bokPodany2;
}
public double pole(double bok1, double bok2) {
return bok1*bok2;
}
}
public static void main(String args[] )
{
//System.out.println(Math.sin(90*(Math.PI/180)));
}
}
I apologize for my English and using English variable names. My goal is: I have object f.e squareExample with side 5. I want to call function to compute area from class square and call function perimeter from class quadrange to compute perimeter. Is it possible?
Compilator says: "FiguraProba.Prostokat is not abstract and does not ovveride abstract method pole() in FiguraProba.Czworokat." I understand the error but I dont know how to work out the error to achieve the goal.
Sorry for using code variables and classes in a foreign language. Here is the explanation what all the words mean:
figura - figure
kwadrat - square
czworokat - quadrangle
prostokat - rectangle
pole - area
obwod - perimeter
bok - side
The solution would be the following:
import java.lang.Math;
public class FiguraProba
{
public abstract class Figura {
public abstract double pole();
public abstract double obwod();
}
public abstract class Czworokat extends Figura {
public double obwod(double bok1, double bok2, double bok3, double bok4)
{
return (bok1+bok2+bok3+bok4);
}
public abstract double pole();
}
public class Kwadrat extends Czworokat {
double bok1;
public Kwadrat(double bokPodany)
{
bok1=bokPodany;
}
// Method without any arguments like the Figura class
// When you extend an abstract class, you have to
// implement the exact method with the exact number of arguments
// Of course you are obligated only if you can create an instance
// of that object. The perfect example when you are not obligated to
// implement a method is class Czworokat. Czworokat is not
// obligated, because you can not create an instance out of it.
public double pole() {
return bok1*bok1;
}
}
public class Prostokat extends Czworokat {
double bok1, bok2;
public Prostokat(double bokPodany1, double bokPodany2)
{
bok1=bokPodany1;
bok2=bokPodany2;
}
// Same logic applies here.
// When you extend an abstract class, you have to
// implement the exact method with the exact number of arguments
// Of course you are obligated only if you can create an instance
// of that object. The perfect example when you are not obligated to
// implement a method is class Czworokat. Czworokat is not
// obligated, because you can not create an instance out of it.
public double pole() {
return bok1*bok2;
}
}
public static void main(String args[] )
{
//System.out.println(Math.sin(90*(Math.PI/180)));
}
}
This would be what you want in case you would only use the classes properties and return the value on behalf of that. If you do want the pole methods with one and two arguments (like you have it in the code), then you would still need to remove the abstract pole method OR you would need to implement that exact method with ZERO arguments.
You can not breach the contract by NOT implementing pole with no arguments. If you need a deeper understanding about abstract classes, then I would suggest you to take a look at the official Java documentation.
If you are overriding a method from abstract class you have to write it exacly what it looks like in interface. So your method should have the same name and the same arguments.
In other worlds, you have a method with signature double pole(double bok1), but you still have to override method dobule pole();
Well, this is kind of embarrassing, but I've forgotten how to do the following in plain old Java:
abstract class Animal {
protected String name;
public Animal(String name) {
this.name = name;
}
}
class Flea extends Animal {
private double jumpHeight;
public Flea(String name, double jumpHeight) {
super(name);
this.jumpHeight = jumpHeight;
}
public double jump() {
return jumpHeight();
}
}
class Giraffe extends Animal {
private int strideLength;
public Giraffe(int strideLength) {
super("Berta");
this.strideLength = strideLength;
}
public int stride() { return strideLength; }
}
class Gorilla extends Animal {
private String call;
public Gorilla(String call) {
super("Boris");
this.call = call;
}
public String call() { return "Gorilla says " + call; }
}
Now I would like to decide the appropriate method at runtime, without having to add all the methods to each Animal (no abstract methods) and without meaningless placeholders (like imagine a Flea has no call).
I would like to do this without casting. So no:
if(Animal instanceof Gorilla) ((Gorilla) animal).call();
I could come up with a solution incorporating interfaces like jumpable and could use that, but I'm sure there was a certain pattern that was exactly for this kind of task.
Any ideas?
You should consider the visitor pattern:
abstract class Animal {
public abstract void acceptAnimalVisitor(AnimalVisitor visitor);
}
class Flea extends Animal {
public void acceptAnimalVisitor(AnimalVisitor visitor){
visitor.visit(this);
}
}
// other animals also implementing acceptAnimalVisitor
public class AnimalVisitor{
public void visit(Flea flea){
// ...
}
// other visit methods for the other animals
}
However, this requires at least one method (the accept method itself). Also note that you can convert the AnimalVisitor into an interface, and that way you can easily achieve the so called double dispatch.
So, I am trying to learn how the interface classes in Java Work, and i'm really confused about it.
I wan't to make it like a method in a normal class file like this:
public class APIClass {
private int davs;
public int setInt(int dav) {
this.davs = dav;
return davs;
}
public int getInt() {
return davs;
}
}
Two methods. One that set's the int "davs", and one getting the int "davs".
What i wan't to do in the interface is something like that. I have seen in others interface files, that they have something like this:
public interface MyInterface {
public MyInterface setInt(int davs);
public MyInterface getInt();
}
EDIT:
My question is that i can't see what i can use the interface for? All i have seen use it, declare the same method in a new class file, and then they really don't need the interface file. So what is it for?
Interfaces in Java are meant as an abstraction. You're expected to use it strictly for deriving other classes. You don't declare any methods in it all.
So if you have an interface like this:
public interface MyInterface {
int setInt(int davs); // this should probably return void
int getInt();
}
And you implement it in a class like this:
public class APIClass implements MyInterface {
private int da;
public int setInt(int davs) {
// return da; <- this doesn't make a whole lot of sense
da = davs; // I assume you meant this
return da; // usually you don't return anything from a setter
}
public int getInt() {
return dada;
}
}
And another class like this:
public class SecondAPIClass implements MyInterface {
private int dada = 0;
public int setInt(int davs) { // note that you have to keep the same method signiture in all derived classes
dada = davs + 5;
return dada;
}
public int getInt() {
return da;
}
}
You can use the interface to group them both. This is an important part of object oriented design. It's usefulness is probably too long to explain in a simple StackOverflow question, but here's a simple example of its usefullness:
import java.util.ArrayList;
public static void main(String[] args)
{
APIClass first = new APIClass();
SecondAPIClass second = new SecondAPIClass();
first.setInt(20);
second.setInt(20);
ArrayList<MyInterface> list = new ArrayList<MyInterface>();
list.add(first);
list.add(second);
for(MyInterface item : list) {
System.out.println(item.getInt());
}
}
The output should be this:
20
25
This example might be more helpful:
Consider you have several vehicles. All vehicles can drive, but driving a boat is different from driving a car, or a helicopter. This is where interfaces are useful. You can declare what a Vehicle should do, without dictating how it should do it.
public interface Vehicle {
void drive();
}
So when you derive it in a class Car, you can state how you want this vehicle to drive.
public class Car implements Vehicle {
void drive() {
// drive like a car
}
}
Now boats are vehicles, and they can drive too, but driving a boat is much different than driving a car.
public class Boat implements Vehicle {
public void drive() {
// drive like a boat
}
}
In summary, interfaces are useful when you have an abstract concept in mind, where you know what derived objects should do but can't dictate how they do it.
I have this abstract base class and each of it's childs should have a specific mandatory function but slightly different. Is this possible using the abstract class or should I be using an interface for this?
I will be using the structure like this
public abstract class Animal
{
//Mandatory method
Public void sound()
{
}
}
public class Cat extends Animal
{
public void sound()
{
System.out.println("Miauw");
}
}
public class Dog extends Animal
{
public void sound()
{
System.out.println("Woof");
}
}
//I will put all these child objects in a List<Animal> and need to call these methods.
for (Animal a : animalList)
{
a.sound();
}
How would one go about this structure? I have to add that I am using an abstract class because there are plenty of identical methods that need to be shared among the child classes. Just some of the methods need to be different from each other but mandatory and accessible from the base class.
You are looking for:
public abstract class Animal
{
//Mandatory method
abstract public void sound();
}
But also look at other users advices:
use lowercase for method names
the keyword publicalways goes in lowercase
use interfaces if your Animal class hasn't common code for all children classes
Both an abstract class and an interface would work in this case. The times when you'd want to use an abstract class is when there are common methods and data that you want shared among all subclasses. Such as, if Animal had a weight variable, and each subclass sets that variable.
NOTE: In an abstract class, any methods that you don't want to implement, you must declare as abstract. See how I modified Sound() below. Also, a bonus tip is that the standards say that method names should start with a lowercase letter, so I changed Sound to sound.
public abstract class Animal
{
private int weight;
public void setWeight(int weight) {
this.weight = weight;
}
public int getWeight() {
return weight;
}
//Mandatory method
abstract public void sound();
}
public class Cat extends Animal
{
public Cat(int weight) {
this.setWeight(weight);
}
public void sound()
{
System.out.println("Miauw");
}
}
public class Dog extends Animal
{
public Dog(int weight) {
this.setWeight(weight);
}
public void sound()
{
System.out.println("Woof");
}
}
You are looking for Java's abstract modifier. The official Java Documentation contains more specific information about abstract and final here.
public abstract class Animal
{
// Mandatory method with no "default" implementation.
public abstract void Sound();
// Optional method with a default implementation.
public void Move() {
// some actions here
}
// Optional method with a fixed implementation (it can't be changed in a child class).
public final void Eat(Food food) {
// some actions here
}
}
you should use interface in this case because you are not defining any method, if you only want to provide declaration interface is ok for that
if you use abstract class you overhead by overriding the method and define it again
I'm studying a chapter in java related to Inheritance, and i have a few questions.
I' have basic understanding how inheritance works ( overriding methods, information hiding, how to use private fields from superclass in a subclass etc ), but i have just one problem and i hope you might help me.
When superclass have non default constructor(s) - without parameters, that means that in a subclass i have to create new constructor (it can be default - without parameters ), but in a first statement must be superclass constructor call.
Ok, so far so good. I understand so far. In subclass you must call superclass constructor, matching any of constructors parameters.
But lets check following code: (Superclass)
public class Vehicle {
private int numOfWheels;
private double avgGallonsPerMile;
public Vehicle(int numOfWheels, double avgGallonsPerMile) {
this.numOfWheels = numOfWheels;
this.avgGallonsPerMile = avgGallonsPerMile;
}
}
And another Subclass code:
public class Car extends Vehicle{
public Car(double avgGallonsPerMile) {
super(What should i write here?, avgGallonsPerMile);
//force numOfWheels to 4;
}
}
Here is the exercise for subclass:
Each subclass
contains a constructor that accepts the miles-per-gallon value as an argument and
forces the number of wheels to the appropriate value—2 for a MotorCycle and 4 for
a Car.
In subclass constructor i don't need numOfWheels field, because i will force it to 4 ( for car ) and 2(for motorbike) anyway.
But stil i need that data for superclass anyway. Where to get that data? What should as first parameter in call to superclass constructor.
But still this isn't the lonely case. I got lots of exercises that i don't need certain data in subclass constructor as parameters, BUT still i need them in superclass constructor call.
What should i do in such cases ?
I really hope you understood me, what i want to tell. It's kinda difficult.
If its anyway the same 4 for cars and 2 for motorcycles than make if fix!
super(4, avgGallonsPerMile);
or the better way - declare a constant:
private static final int NUM_OF_WHEELS = 4;
..
super(Car.NUM_OF_WHEELS, avgGallonsPerMile);
If you don't need a field in a super class then chances are it shouldn't be there. Instead you can do the following.
public abstract class Vehicle {
private final double avgGallonsPerMile;
public Vehicle(double avgGallonsPerMile) {
this.avgGallonsPerMile = avgGallonsPerMile;
}
public double getAvgGallonsPerMile() { return avgGallonsPerMile; }
public abstract int getNumOfWheels();
}
public class Car extends Vehicle{
public Car(double avgGallonsPerMile) {
super(avgGallonsPerMile);
}
public int getNumOfWheels() { return 4; }
}
public class Bicycle extends Vehicle{
public Bicycle (double avgGallonsPerMile) {
super(avgGallonsPerMile);
}
public int getNumOfWheels() { return 2; }
}
public class Tricycle extends Vehicle{
public Tricycle (double avgGallonsPerMile) {
super(avgGallonsPerMile);
}
public int getNumOfWheels() { return 3; }
}
BTW: Your car must be really inefficient if it uses gallons per mile of fuel.
Very simple: if the number of wheels on a Car is always 4, them simply pass the value 4:
public Car(double avgGallonsPerMile) {
super(4, avgGallonsPerMile);
// ...
}