The technique of choosing common features of objects and methods is known as abstracting. It also involves with concealing the details and highlighting only the essential features of a particular object or a concept. In an OO context, abstraction refers to the act of generalizing data and behavior to a type higher up the hierarchy than the current class. When you move variables or methods from a subclass to a superclass, you're abstracting those members.
Those are general terms, and they apply in the Java language. But the language also adds the concepts of abstract classes and abstract methods. An abstract class is a class that can't be instantiated. For example, you might create a class called Animal. It makes no sense to instantiate such a class: In practice, you'd only want to create instances of a concrete class like Dog. But all Animals have some things in common, such as the ability to make noise. Saying that an Animal makes noise doesn't tell you much. The noise it makes depends on the kind of animal it is. How do you model that? You define the common stuff on the abstract class, and you force subclasses to implement concrete behavior specific to their types. You can have both abstract and concrete classes in your hierarchies.
Using abstraction:
Our Person class contains some method behavior that we don't know we need yet. Let's remove it and force subclasses to implement that behavior polymorphically. We can do that by defining the methods on Person to be abstract. Then our subclasses will have to implement those methods.
public abstract class Person
{
...
abstract void move();
abstract void talk();
}
public class Adult extends Person
{
public Adult(){
}
public void move()
{
System.out.println("Walked.");
}
public void talk()
{
System.out.println("Spoke.");
}
}
public class Baby extends Person {
public Baby() {
}
public void move() {
System.out.println("Crawled.");
}
public void talk() {
System.out.println("Gurgled.");
}
}
What have we done in this listing?
• We changed Person to make the methods abstract, forcing subclasses to implement them.
• We made Adult subclass Person, and implemented the methods.
• We made Baby subclass Person, and implemented the methods.
When you declare a method to be abstract, you require subclasses to implement the method, or to be abstract themselves and pass along the implementation responsibility to their subclasses. You can implement some methods on an abstract class, and force subclasses to implement others. That's up to you. Simply declare the ones you don't want to implement as abstract, and don't provide a method body. If a subclass fails to implement an abstract method from a superclass, the compiler will complain. Now that both Adult and Baby subclass Person, we can refer to an instance of either class as being of type Person.
0 comments:
Post a Comment