I was going through some design pattern videos on YouTube, however I have a small doubt on some basic Java concept. I tried searching for solution, but was unable to find one. Below is my query.
I have some classes Animal.java, Dog.java, an interface Fly.java which also has a class named CantFly in same file. A main method CheckAnimal.java. Below is the code
Animal.java
package com.classification.pojo;
public class Animal {
public Fly flyingType;
public String tryToFly() {
return flyingType.fly();
}
public void setFlyingAbility(Fly newFlyType) {
flyingType = newFlyType;
}
}
Dog.java
package com.classification.pojo;
public class Dog extends Animal {
public Dog() {
super();
flyingType = new CantFly();
}
public void digHole() {
System.out.println("I am digging hole!");
}
}
Fly.java
package com.designpattern.strategy;
public interface Fly {
String fly();
}
class CantFly implements Fly {
public String fly() {
return "Can't fly";
}
}
class ItFlys implements Fly {
public String fly() {
return "I can fly";
}
}
CheckAnimal.java
package com.designpattern.main;
import com.classification.pojo.Animal;
import com.classification.pojo.Dog;
import com.classification.pojo.Fly;
public class CheckAnimals {
public static void main(String[] args) {
Animal doggy = new Dog();
System.out.println(doggy.tryToFly());
doggy.setFlyingAbility(new ItFlys());
System.out.println(doggy.tryToFly());
}
}
In CheckAnimal.java, for doggy object to invoke setFlyingAbility() method correctly, Animal.java, Dog.java and Fly.java needs to be in same package. If I keep Fly.java in different package, I cannot access CantFly() constructor. I hope I have made my point clear.
- Ishan
You've declared CantFly
without any access modifier:
class CantFly
... which means it's only accessible within the same package. Just make it public, and then you'll be able to use it within other packages. See the Java tutorial on access modifiers for more information. The same is true for the ItFlys
class.
Additionally, you haven't imported the right package in your CheckAnimal.java
file. You should be importing com.designpattern.strategy.ItFlys
. You don't need to import Fly
at all in CheckAnimal.java
, as you're never referring to that interface directly in that file.
See more on this question at Stackoverflow