All Collections implements interface Collection, these collection have specific abstract hierarchy e.g.
AbstractCollection -> AbstractList -> ArrayList
AbstractCollection -> AbstractSet -> HashSet
But there are also corresponding interfaces like Collection, List, Set. These interface seem to me kind of redundant.
Why are they here ? Is is just convention or is there a reason to just implement interface and not extend the abstract class.
The interfaces are there because it's good to be able to assign a type to a variable or parameter without imposing an implementation.
For instance if I create a persistent entity to use in Hibernate, and it has a collection of things, I want to assign a type of List or Set to that. Hibernate will swap out whatever list I initialize it to with its own, with some Hibernate-specific implementation that does lazy-loading or whatever else it needs to. The Hibernate developers may not want to be constrained by having to extend the abstract class.
The abstract class exists as a convenience for implementers. The interface is a contract used by clients.
Implementing an interface is much different from extending an abstract class.
Let's suppose that class Animal is an abstract class, and that Dog, Cat, Snake and Shark extend Animal.
The default Animal.move() implementation simply moves them.
But, interfaces allow us to further group-out similar animals, such as RunningAnimal, SwimmingAnimal.
So, if Dog extends Animal implements RunningAnimal, along the inherited move() he will also have to implement his own run(), which might find it's way in the overridden move() inherited from Animal. Does this make sense to you yet or do I need to clarify better / with some code? :)
Interfaces let you group similar functionality of different classes. "Clickable", "Sortable", "Serializable" ... They all encompass the members thru a shared functionality (so a list of clickables is more than a list of buttons) rather than a same purpose.
So, think about it like this
Cat extends Animal implements RunningAnimal, ClimbingAnimal -- inherits move() has to implement run() and climbTree()
Dog extends Animal implements RunningAnimal -- inherits move(), has to implement run()
Snake extends Animal -- likely overrides inherited move()
Shark extends Animal implements SwimmingAnimal -- likely overrides move(), has to implement swim()
Why not ? Abstract classes are made to simplify inheritance process. When you want to create your collection you don't have to do everything from scratch.
But of course no one tells you that you SHOULD inherit from AbstractCollection. You can write your implementation from scratch.
This is a common good practice for API's to have interfaces. And have distinction between implementations and interfaces.
An Interface is a contract made between users and implementers. An abstract base class is intended to be used as a common base to access a number of similarly-behaving objects.
Related
Basically the question in the title but here a little more detail:
I have a set of classes you can create similar objects of (e.g. animals and I have the classes Tiger, Crocodile, Wolf etc. whatever you like). And the types of those objects are specified by the Supertype they are derived from. Now some objects might derive from multiple Supertypes, which obviously need to be implemented as Interfaces. But lets say I have a specific Supertype which I want each animal to only derive EXACTLY ONCE from (e.g. the animal family they belong to). Does this automatically mean that this Supertype should be an abstract class to ensure it can only be extended once in a Subtype?
Edit since Michael pointed out that my question is unclear.
This question is not about a specific piece of code it is more a theoretical question about types, maybe I should ask like this: Can and should an abstract class be used as a tool to ensure a Subtype of this Supertype can only derive it once. Lets say for my example with animals I have the Supertypes "Omnivore", "Herbivore" and "Carnivore" and I know an animal can only be exactly one of those, is this a valid reason to make those abstract classes and not interfaces?
If you have different exclusive categories then different base classes (abstract or not) is a sensible solution.
class HerbivoreBase implements Animal, EatsVegetables { ... }
class CarnivoreBase implements Animal, EatsAnimals { ... }
class OmnivoreBase implements Animal, EatsVegetables, EatsAnimals { ... }
It only makes sense when the classes have (differing) methods.
To look at other languages. Scala has case classes (the name says it all) with pattern matching.
Java also has (will have?) pattern matching based on classes, and instanceof as follows:
Animal animal = ...
if (animal instanceof Herbivore herbi) { ... herbi.eatVegy(...); ... }
else if (animal instanceof Carnivore carni) { ... carni.hunts(...); ... }
Java has also introduced a restricting mechanism to list which classes may be child of a given class, say abstract class Animal.
I would still like to mention, that modeling with inheritance can easily over-architect things, especially if later a change is needed, or the code becomes bloated.
Your question is more about "should I use an interface, or a class (and extend it)?"
Remember that a subclass has a relationship of is-a with its base class. A class has a relationship of has-a with an interface.
An interface define a behaviour that one class has (a car has 4 wheels) (remember also that an interface should define only one behaviour, related to the interface segregation principle, which says that it's better to have more smaller and specific interfaces than one general and bigger, so that classes can implements only needed behaviours), a superclass define a "more general" type (dog is an animal).
See for example:
If you have a MountainBike class, it will implement an interface Bike, or extend a class Bike? It will extend the Bike class, since mountain bike is a "sub-type" of bike.
If you have an Elephant class, it will implement an interface Trunk or extend a class Trunk? It will implement the Trunk interface, since trunk is a part (behaviour) of the elephant, not a "container".
An interface is a way to define signature of a method, but normally it does not define the implementation of a given method. If you want to implement a method in an interface, use the default keyword
interface inter{
public default void myMethod(){/*your code here*/
}
A class can implement multiple interfaces but cannot extend more than one class.
If you are using an abstract class you are can use the following two benefits
The abstract class cannot be initialized
The abstract class can implement abstract methods.
A subclass can still only extend one class, abstract or not.
Your question was: "If I want a superclass to only be derivable from a single subclass, which should I use? Interface or abstract class?"
By derivable, do you mean inheritance? Because if that's the case, then I think you got the question backwards. Subclasses inherit from the superclasses.
The child (subclass) inherits from its parent (superclass)
I have a super-class, Animal, with two subclasses, Cat and Dog. Dog and Cat both need to have specific methods for speaking and moving. Here are two alternatives for achieving this:
Animal will have two abstract methods, move() and speak(); Dog, Cat and Dog each override the two methods so they are specific to them.
I could have an interface that has generic animal methods move() and speak(), with the two subclasses implementing the methods so they are again specific to them.
Is one of these approaches more appropriate than the nother? I realize if I had an ArrayList of animals, I would write:
ArrayList Animal<allAnimals> = new ArrayList <Animal>():
allAnimals.add(new Dog());
allAnimals.add(new Cat());
//If I override the methods, I can simply go:
for (Animal a: allAnimals) a.move();
//Where as if I implemented the methods, I would not need be able to do this. I would need to cast the animal as its specific animal. e.g. If I knew the animal was a dog.
Dog aDog= (Dog) a;
a.move();
So overriding and implementing could have certain advantages and disadvantages depending on the situation they are used in. Can anyone else elaborate on this ?
First, from the subclass point of view, there is no difference between overriding or implementing a method. So, the code that you wrote would work exactly the same in all cases (in Java, all methods act like C++ virtual functions; the method invoked is the one of the actual class being referenced).
So, the decission is to define a superclass that is an interface, an abstract class, or a instantiable class.
The instantiable class should be used if there makes sense to create objects of the superclass (new Animal()).
The abstract class, when there are no objects of the superclass but the implementation of some methods will be shared by all (or nearly all) the subclases.
The interface, when you only define the contract and the implementation is left to each subclass.
It depends of the scope of the problem to decide which use. For example, if move() just means "change x,y coordinates of animal", probably it should be an implemented method in an abstract class. But if you have to define how the animal moves, then Animal would be better an interface so each subclass defines it.
As a general rule of thumb, use extension (abstract classes), if and only if your extending classes will share a good amount of behavior. In that case, extension can be used eliminate the need for duplicate code, which is A Good Thing (TM).
On the other hand, if your classes simply need to have the same signatures, then go with an Interface, which is much more flexible (you can, for instance, implement several interfaces, but you can only extend from one class).
This is just somewhat generic advice, since every use case is different.
To avoid the limitations of extension, there are other techniques that can be used, for instance, composition: (http://en.wikipedia.org/wiki/Composition_over_inheritance).
Last but not least, I think you're slightly mistaken in your code.
You can call the methods on the base classes in exactly the same way, no matter if they're inheriting them from an Abstract Class or an Interface.
In this case it probably depends on whether or not you'd like to have a default implementation of move() so Dog and Cat don't HAVE to provide their own implementations. Presumably the move() method shares a lot of commonality between cats and dogs so you'd have better reusability with a common implementation in the superclass.
//Where as if I implemented the methods, I would not need be able to do this. I would need to cast the animal as its specific animal. e.g. If I knew the animal was a dog.
Dog aDog= (Dog) a;
a.move();
No, you wouldn't have to do this at all. If Animal is an interface instead of an abstract class, the process you show for abstract classes would work just fine.
Conceptually, an abstract class describes what the thing IS, an interface describes what it DOES. In this case it's appropriate to have Animal as an abstract class because a Cat or a Dog IS an Animal. Functionally, choose whichever option results in the least amount of coding / the cleanest class hierarchy.
In general, the rule of thumb is to use an interface if you can cause a Java class can implement many interfaces but extend only one class.
Extending (inheritance) should be used only if there is a lot in common to a few classes and you want to be able to reuse the same code.
By the way, in the code that you provided as an example, you can use:
for (Animal a: allAnimals) a.move();
both in the case when you use interface as well as inheritance.
First of all, you have a third option, which is: Have an interface (say, MoverAndSpeaker; although that's kind of a lame name), and have the abstract base class Animal 'implmenent' it:
static public abstract class Animal implements MoverAndSpeaker {
#Override
public abstract void move();
public abstract void speak();
}
Why would you even want something like that?
Unlike some of the answers here, I believe semantic consistency is the paramount consideration, and issues such as avoiding code duplication are either resolved on their own or take the minority in importance.
If I were in your position, the key criterion I would apply is:
"Are there objects which move and speak, which are not Animals?"
If the answer is "no", then moving and speaking is something Animals do. Thus, use the abstract methods only
If the answer is "yes", then I ask myself
"Do all animals move and speak?"
If the secondary answer is "yes", then use the above code (assuming you don't want some default implementation for all animals).
If the secondary answer is "no", consider just the interface. Although you might want an intermediary class between Dog, Cat and Animal - if you have some shared code or fields between all Animals which also move and speak.
Finally, if there's nothing in common to all animals, then as suggested in other answers, you might not need the Animal base class at all.
What is use of an abstract class implementing an interface? In which
scenario would we implement.
Why would you choose Abstract class over interface? If an class
extends an Abstract class, should we implement all the methods in
the Abstract Class. If an class implements an Interface should we
implement all the methods too.
Why was abstract class or interface pattern introduced? What is the
use of them? Does it deal anything in the way object is getting
instantiated or the way it behaves?
If an abstract class has a static method declared, then can we
instantiate that class?
I was asked these questions, though my answers were not clear... i would like to know from people here?
1&2) You can use interfaces and abstract classes together -- the interface can provide a definition of behavior, and the abstract class provides partial implementation, the subclasses provide full implementation.
3) Interfaces and abstract classes are concepts. The java language designers decided to provide language features to realize the concepts.
4) An instance of an abstract class can never be instantiated. A static method on an abstract class can be invoked normally, remember static methods are invoked by referencing the class, not an instance of the class.
some psuedocode
abstract class Base {
abstract void doSomething(); // subclass provides implementation
protected helper() {
// doSomething implementation in subclass can use helper
}
}
On Abstract classes and Interfaces
Abstract classes defines a partial representation of some entity, that is common to every extending class but that must be completed by inheritance. So, every inheriting class comprehends all the properties defined in every parent classes.
Interfaces provide a behavior to a given class, and allow to simulate something similar to multiple inheritance. Since you can implement multiple interfaces in a class, you can make that class adopt the behavior of every implementing interface, and all together.
Classical example:
Abstract class: Animal Represents an animal in an abstract way. Each animal should extend this class to adopt all the implications of "being" an animal.
Abstract class: Mammal extends Animal The mammal is an Animal and inherits all the properties that are common to every mammal.
Some mammals are carnivorous and some herbivorous. These are different behaviors for the same type of animal, so here they come the interfaces.
Interface: Carnivorous Defines the properties a carnivore animal should have.
Interface: Herbivorous Defines the properties a herbivore animal should have.
Every mammal should breath air. This is another behavior, that is common to every mammal.
Interface AirBreathing Defines the properties for air-breathing animal
So. You have these two mammals: Wolves and Manatees. Both have to breath air, but wolves are carnivorous and manatees herbivorous.
Class Wolf extends Mammals implements AirBreathing, Carnivorous
Class Wolf extends Mammals implements AirBreathing, Herbivorous
Implementation details
1) Every abstract method defined in an abstract class, must be implemented somewhere "in the road" of inheritance until a final class is reached. This means that when a final class is implemented it must implement or inherit implementations of every abstract method inherited from parent classes.
2) Yes, you can define static methods in abstract classes. You can call static method from the abstract class as AbstractClass.staticMethod(), but you can't ever instantiate an abstract class.
3) Classes implementing interfaces, must implement every method defined by the interface.
Hope this helps.
What is use of an abstract class implementing an interface? In which scenario would we implement?.
One important use is to provide a skeletal implementation reducing the effort needed to implement the interface. An example of this is AbstractCollection<E> which implements the Collection<E> interface in the Java Collections Framework.
Why would you choose Abstract class over interface?
When I want to provide an implementation for some parts of the class's behaviour.
If a class extends an abstract class, should we implement all the methods in the abstract
Class. If an class implements an interface should we implement all the methods too.
Concrete classes must completely implement the abstract interface. You have no choice but to implement all methods. This is because whenever you implement an interface or extend an abstract class with a concrete implementation, you're declaring that the concrete class fully describes the interface's behavior.
Of course abstract extensions don't have to implement the interface completely i.e. abstract extensions of interfaces / abstract classes aren't forced to implement the interface in entirety.
Why was abstract class or interface pattern introduced? What is the use of them? Does it deal anything in the way object is getting instantiated or the way it behaves?
Interfaces describe the behavior of types. Since all implementations must completely describe the behavior enforced by the interface, they allow for polymorphism.
Canonical Collections Framework example:
The List<E> interface describes how a list of objects may behave. It describes the add, remove, get and set operations to name a few.
2.ArrayList<E> and LinkedList<E> are two concrete implementations of the List<E> interface.
3.Thus it's guaranteed that both of them behave like a List<E> and more specifically have concrete implementations of the add, remove, get and set operations to name a few.
4.Also since both of them implement the same interface, more specifically, both of them behave like a List<E>, I can use them, wherever I need to use a List<E>.
5.This allows for statements like these :
List<String> names = new ArrayList<String>();
List<String> queue = new LinkedList<String>();
showList(names);
showList(queue);
void showList(List<String> list) {
for(String s : list)
System.out.println(s);
}
This is a very simple example of polymorphism in action. The showList(List<String> list) methods accepts and happily iterates over names and queues because both of them implement the same interface and it can be sure of it's behaviour.
I have just completed my studies and joined a firm. So might be possible i may not be able to give you good example but yes in broad sense they gonna work and they are effective...
the most important reason for using interface is to create a common behavior in related classes. Wonderfull example is collection framework. Collection is a interface that ensure whatever the classes that represents collection of some objects then it should compulsory implement all the methods of collection(else they wont be a collection, also note that collection is a behavior) and now this interface is further implemented by other interface list so all the collection which are of type list implement this(here we have specialize the behavior of collection(by adding some method), note that list is also a behavior). Now we want a class which represents nothing but a collection of array as linked list so we implemented all the methods of list(which ultimately have collection method).
Now come to abstract class, consider the example of Number class in java its a abstract class which implements serializable interface since it has to show serialized behavior. Also note that Number represents some physical entity, so it should be a abstract class. Abstract because from it we cant conclude to exact object. While serializable is a behavior hence interface.
Thats what i could deliver to you and thats what i learned from my basic knowledge. But always remember oops differ people to people. See your encapsulation implement abstraction example as well. So everything depends on you.
I am a beginner in interface concept.
when I surfing for the information about "Achieving multiple inheritance via interface", I came across this link.. Multiple inheritance
I have a same doubt as the programstudent had.
hi, Good Explanation very much helpful In the uml diagram for java
there is no connection to Animal from Bird and horse why? Is it
necessary to use the implement the same method in the derived class
and why
void birdNoise();
void horseNoise();
why in the Peagus class
public void horseNoise()
{
System.out.println("Horse Noise!");
}
public void birdNoise()
{
System.out.println("Bird Noise!");
}
why this must be there? Why "Remember, we must write each class's own implementation for each method in the interface. reason? Thank for this good explanation Thank you
In that post, they have used multiple inheritance in c++ and converted to interfaces in java.
1.what I thought about inheritance is having some methods in parent class, and whenever the same methods are needed in other class(es) too, then those class(es) will inherit the parent class and use it.
But in interface concept if each derived class(es) has to define its own implementation then what is the use of inheriting it?
2.If we have to provide own implementation then why not we define that method in the derived class(es) itself. What is the use of inheriting it?
Someone please explain.
Thanks in advance.
When I switched from c++ to java I had this same feeling but now that I been working with java for a while it all kinda makes sense.
1.what I thought about inheritance is having some methods in parent
class, and whenever the same methods are needed in other class(es)
too, then those class(es) will inherit the parent class and use it.
Like the original author did, you can still do multiple inheritance in java you just must use interfaces. Interfaces are like pure virtual classes in c++.
But in interface concept if each derived class(es) has to define its
own implementation then what is the use of inheriting it?
The reason you implement an interface in java is so that you guarantee that class has those methods. That way you can have a specific class implement a generic interface and then treat every specific class that implements that generic interface the same.
Java Design is a bit different then c++ design but after doing several java program's you will become just as good at using multiple interfaces as you are at using multiple inheritance.
Each subclass has to define it's own implementation because each subclass may perform the operation slightly differently. Consider the following example:
public interface animal {
//All implementers must define this method
void speak();
}
This interface states that any Animal MUST have a way to speak. Basically, any type of animal is going to be able to make a noise. We then have 2 subclass, or 2 different types of animals that we create.
public class Dog implements animal {
//Define how a Dog speaks
public void speak() {
System.out.println( "woof" );
}
}
We then define another animal, cat
public class Cat implements animal {
//Define how a Cat speaks
public void speak() {
System.out.println( "meow" );
}
}
In this example, both Cat and Dog are animals, and therefore must be able to speak due to our interface. However, everybody knows that cats and dogs make different sounds. By allowing each subclass to define how it 'speaks', we can give Dog and Cat their own respective sound when the speak() method is called, while ensuring they are both Animals.
In answer to your question more specifically, inheritance forces it's subclasses to have a specific method. In other words, an interface states that "all my subclasses will define each of these methods". What this allows us to do is to write code that deals with the methods in an interface without knowing the specific subclass. We can safely do that because we know that each subclass MUST have defined the method in the interface class. If only the subclasses that use the method defined it, then we would have no way of knowing for sure whether it is safe to call the method on all subclasses.
Just a note: If you do not want a subclass to define the method, you can simply define an empty method like this:
public class MuteAnimal implements animal {
//A MuteAnimal can't speak!
public void speak() { }
}
Inheritance is often useless without polymorphism. It is really not easy to explain it all just in few sentences. My advices would be to look at interfaces for defining behavior (something like can-do relationship), and concrete inheritence for is-a relationships.
In the center of everything as you may learn is something called Single Responsibility Principle. This means that one class has one responsibility, if you are having more of them, you separate the class.
If you take your example, even the Pegasus isn't both horse and bird at the same time 100% percent. It would inherit the horse, but implement specific characteristics of the birds, which would be defined in interfaces, like Flyable for instance. You can say that birds have one way of flying common to them all, so inherit them from Bird. Pegasus is a little different, so that custom logic can be defined after you implement the Flyable interface with method Fly.
Also, the example with horseNoise and birdNoise is little unrealistic, you want one method speak() which will due to internal class alhorithm perform certain action. What if that pegasus could talk? Would you have a method for each word?
Back to Flyable example, say you now have a video-game. Now you can have polimorphism for this: Lets say that in game earthquake happens. You want for each animal that can fly to go and fly. You have a collection of animals currently in game, so you write this:
foreach(Flyable flyableAnimal in animals)
flyableAnimal.Fly();
You just rely on polimorphism ...
These were just some random thoughts, you can find far better examples online, hope this helps ...
If class A inherits from class B, that effectively means two things:
Class A can implicitly use all methods and properties of class B, and need only define that functionality which is in fact unique to class A.
Code which expects an object of type B will accept an object of type A.
Those two features of inheritance are in some sense orthogonal; one can imagine places where either could be useful without the other. Although derived classes can only have one parent class from which they gain implicit access to methods and properties, they may define an arbitrary number of interfaces for which they are substitutable.
Note that while some people insist that interfaces form a "has-a" rather than "is-a" relationship, I think it's better to think of them as saying something "is __able" or "is a __er", the point being that interfaces don't just define abilities, but define substitutability (i.e. "is a") in terms of ability.
In Java, abstract classes give the ability to define both concrete and abstract methods whereas interfaces only give the ability to implement abstract methods.
I believe overriding methods in subclasses/implementations is possible in both cases, therefore, what is the real advantage of one over the other (interfaces vs abstract classes in Java)?
Interfaces are for when you want to say "I don't care how you do it, but here's what you need to get done."
Abstract classes are for when you want to say "I know what you should do, and I know how you should do it in some/many of the cases."
Abstract classes have some serious drawbacks. For example:
class House {
}
class Boat {
}
class HouseBoat extends /* Uh oh!! */ {
// don't get me started on Farmer's Insurance "Autoboathome" which is also a helicopter
}
You can get through via an interface:
interface Liveable {
}
interface Floatable {
}
class HouseBoat implements Liveable, Floatable {
}
Now, abstract classes are also very useful. For example, consider the AbstractCollection class. It defines the default behavior for very common methods to all Collections, like isEmpty() and contains(Object). You can override these behaviors if you want to, but... is the behavior for determining if a collection is empty really likely to change? Typically it's going to be size == 0. (But it can make a big difference! Sometimes size is expensive to calculate, but determining whether something is empty or not is as easy as looking at the first element.)
And since it won't change often, is it really worth the developer's time to implement that method every... single... time... for every method in that "solved" category? Not to mention when you need to make a change to it, you're going to have code duplication and missed bugs if you had to re-implement it everywhere.
Interfaces are useful because Java doesn't have multiple inheritance (but you can implement as many interfaces as you like).
Abstract classes are useful when you need concrete behaviour from the base class.
The facts are-
Java doesn't support multiple inheritance
Multiple interfaces can be implemented
Few methods in an abstract class may be implemented
These facts can be used to tilt the advantage in favor of interfaces or abstract classes.
If there are more than one behavior that a class must share with other classes, interfaces win.
If a method definition has to be shared/ overridden with other classes, abstract classes win.
An class may implement several interfaces, whereas it may only extend one class (abstract or concrete), because Java does not support multiple inheritance.
In OOP (mostly independent of a concrete language) abstract classes are a re-use mechanism for the class hierarchy for behaviour and structure which isn't complete on its own.
Interfaces are mechanism for specification of requirements on a module (e.g. class) independently of the concrete implementation.
All other differences are technical details, important is different usage.
You dont override an interface. You implement it.
Writing an interface gives implementors the ability to implement your interface and also other interfaces in addition to inheriting from a base class.
Abstract classes can be partially or fully implemented.Marking a class abstract just prevents you from instantiating an object of that type.
-Method without any implementation is abstract method,whenever a class contains one or more abstract method,then it must be declared as a abstract class
-Interface is fully abstract which cannot have constructor,instance and static blocks,and it contains only two types of members
1.public abstract method
2.public-static-final variable
*Both cannot be instantiated but reference can be created.
*Which one suits better depends on the application
-Interfaces are useful because Java classes will not support multiple inheritance but interfaces do.
-Abstract classes are useful when you need concrete behavior from the base class.
The main advantages of interface over abstract class is to overcome the occurrence of diamond
problem and achieve multiple inheritance.
In java there is no solution provided for diamond problem using classes.For this reason multiple inheritance is block using classes in java.
So to achieve multiple inheritance we use interface .
class Animal
{ void move(){} }
class Bird
{ void move(){fly} }
class Fish
{ void move(){swim} }
Now, if class Animal is abstract class like
Animal a;
a= new Bird(); or a = new Fish()
Here, abstraction works well, but if there are 100 objects like Animal a[100];
You can not write new Bird().move or new Fish().move 100 times
Use interface and write a[i].move. It will differentiate as bird or fish and that move() will be invoked
Second it supports multiple inheritance as class A can implements as many interfaces.
Amazing answers!!
I too want to put my opinion on Interface.
As the name says it is interface which means it will provide interface between two classes.
It help a class or interface hold multiple behavior at the same time.
Who ever having the interface can access the behavior of the class agreed with the interface.
interface teacher
{
//methods related to teacher
}
interface student
{
//methods related to student
}
interface employee
{
//methods related to employee
}
class Person:teacher,student,employee
{
//definition of all the methods in teacher,student, employee interface
//and method for person
}
Now here which ever class is having teacher interface will have access to only teacher behavior of Person.
Similarly the class or module having student interface will have access to only student behavior of person.
Using abstract class, it is not at all possible.
Hope this will add some additional points. :)
Happy coding!!.