hi really very sorry to ask the same questions..still i am not getting clear idea ...genarally learn new things easily..now i cont understand abt abstract and interafces..plz explain with clear coding example...i am worrying like anything

Ezzaral commented: Spamming the question doesn't improve your understanding of a concept. -4

Recommended Answers

All 2 Replies

Abstract Classes

Sometimes you may want to declare a class and yet not know how to define all of the methods that belong to that class. For example, you may want to declare a class called Writer and include in it a member method called Write. However, you don't know how to code Write() because it is different for each type of Writer Device. Of course, you plan to handle this by deriving subclasses of Writer, such as Printer, Disk, Network and Console. But what code do you put in the Write() function of Writer class itself?

In Java you can declare the Write() function of Writer as an abstract method. Doing so allows you to declare the method without writing any code for it in that class. However, you can write code for the method in the subclass. If a method is declared abstract, then the class must also be declared as abstract. For Writer and its subclasses, this means they would appear as follows:

abstract class Writer {
    abstract void Write();
}

public class Printer extends Writer{
    public void Write() {
        // Printer code
    }
}

public class Disk extends Writer{
    public void Write() {
        // File I-O
    }
}

public class Network extends Writer{
    public void Write() {
        // Network I/O
    }
}

Note
A method that is private or static cannot also be declared abstract. Because a private method cannot be overridden in a subclass, a private abstract method would not be usable. Similarly, because all static methods are implicitly final, static methods cannot be overridden.

Abstract Method: This is a method that is incomplete; it has only a declaration and no method body. Here is the syntax for an abstract method declaration:

[B]abstract void f();[/B]

A class containing abstract methods is called an abstract class. If a class contains one or more abstract methods, the class itself must be qualified as abstract. (Otherwise, the compiler gives you an error message.)

If an abstract class is incomplete, what is the compiler supposed to do when someone tries to make an object of that class? It cannot safely create an object of an abstract class, so you get an error message from the compiler. This way the compiler ensures the purity of the abstract class, and you don’t need to worry about misusing it.

If you inherit from an abstract class and you want to make objects of the new type, you must provide method definitions for all the abstract methods in the base class. If you don’t (and you may choose not to), then the derived class is also abstract and the compiler will force you to qualify that class with the abstract keyword.

It’s possible to create a class as abstract without including any abstract methods. This is useful when you’ve got a class in which it doesn’t make sense to have any abstract methods, and yet you want to prevent any instances of that class.


Sample - 1

abstract class Shape {
	abstract void draw();
	abstract void erase();
}
class Circle extends Shape {
	void draw() {
		System.out.println("Circle.draw()");
	}
	void erase() {
		System.out.println("Circle.erase()");
	}
}
class Square extends Shape {
	void draw() {
		System.out.println("Square.draw()");
	}
	void erase() {
		System.out.println("Square.erase()");
	}
}
class Triangle extends Shape {
	void draw() {
		System.out.println("Triangle.draw()");
	}
	void erase() {
		System.out.println("Triangle.erase()");
	}
}
//A "factory" that randomly creates shapes:
class RandomShapeGenerator {
	private Random rand = new Random();
	public Shape next() {
		switch(rand.nextInt(3)) {
		default:
		case 0: return new Circle();
		case 1: return new Square();
		case 2: return new Triangle();
		}
	}
}
public class TestMain {
	private static RandomShapeGenerator gen =
		new RandomShapeGenerator();
	public static void main(String[] args) {
		Shape[] s = new Shape[9];
//		Fill up the array with shapes:
		for(int i = 0; i < s.length; i++)
			s[i] = gen.next();
//		Make polymorphic method calls:
		for(int i = 0; i < s.length; i++)
			s[i].draw();
	}
}

Sample - 2

abstract class Actor {
	abstract void act();
}
class HappyActor extends Actor {
	void act() { System.out.println("HappyActor");}
}
class SadActor extends Actor {
	void act() {System.out.println("SadActor");}
}
class Stage {
	private Actor actor = new HappyActor();
	void change() { actor = new SadActor(); }
	void performPlay() { actor.act(); }
}
public class TestMain {
	public static void main(String[] args) {
		Stage stage = new Stage();
		stage.performPlay();
		stage.change();
		stage.performPlay();
	}
}

Interfaces
In previous session, we learned about the abstract keyword, which allows you to create one or more methods in a class that have no definitions—you provide part of the interface without providing a corresponding implementation, which is created by inheritors. The interface keyword produces a completely abstract class, one that provides no implementation at all. You’ll learn that the interface is more than just an abstract class taken to the extreme, since it allows you to perform a variation on C++’s “multiple inheritance,” by creating a class that can be upcast to more than one base type.

Characteristics of Interfaces

  1. It allows the creator to establish the form for a class: method names, argument lists, and return types, but no method bodies. An interface can also contain fields, but these are implicitly static and final. An interface provides only a form, but no implementation.
  2. An interface says: “This is what all classes that implement this particular interface will look like.” Thus, any code that uses a particular interface knows what methods might be called for that interface, and that’s all. So the interface is used to establish a “protocol” between classes.

A review of methods is in order before continuing. Methods are similar to functions in other languages. A method is a unit of code that is called and returns a value. Methods perform work on the variables and contain executable code. They are always internal to a class and are associated with an object.

The concept of interfaces is one of the main differences in project design between traditional C and Java application development. The C and other procedural programming language systems' development life cycle often begins with the definition of the application function names and their arguments as empty "black boxes." In other words, the programmers know the necessary argument parameters when programming code that calls these functions without knowing how they are implemented in the function.

Thus they can develop code without first fully fleshing out all the functions. In C, this could be done by defining a function prototype for all the functions and then implementing them as resources and schedules permit. How is this accomplished in Java? Through interfaces.

An interface only defines a method's name, return type, and arguments. It does not include executable code or point to a particular method. Think of an interface as a template of structure, not usage.

Interfaces are used to define the structure of a set of methods that will be implemented by classes yet to be designed and coded. In other words, the calling arguments and the return value must conform to the definition in the interface. The compiler checks this conformity. However, the code internal to one method defined by the interface may achieve the intended result in a wildly different way than a method in another class.

The concept of using interfaces is a variation on inheritance used heavily in Java. The chief benefit of interfaces is that many different classes can all implement the same interface. This guarantees that all such classes will implement a few common methods. It also ensures that all the classes will implement these common methods using the same return type, name, and arguments.

Declaring an Interface
An interface is declared in much the same manner as a class, but instead uses the interface keyword instead of the class keyword:

interface name {
   ... body of interface
}

The interface body is declared between the curly braces. The body of an interface consists of declarations for variables and methods.

Modifiers
The same modifiers public and default available to classes can be applied to an interface's declaration. The default is nonpublic, which means accessible by any member of a given package. Most interfaces are public because interfaces are the only means to share variable and method definitions between different packages.

Here is an example of a public interface declaration: 

public interface AnInterface {
  ... //body of interface
}

Variables and methods declared inside an interface also have modifiers associated with them. However, the modifiers are limited to particular combinations for variables and methods.

Modifiers for variables are limited to one specific set: public static final. In other words, variables declared in interfaces can only function as constants. public static final are the default modifiers. It is not necessary to declare the modifiers explicitly, but it makes the code more self-documenting. Trying to assign other modifiers such as protected results in a compile-time error. Here are examples of variable declarations:

public static final int smtpSocket = 25;
public static final float pie = 3.14159;
public static final String = "A DATAPOST COMPUTER CENTER";

Modifiers for methods are limited to one specific set as well: public abstract, meaning that methods declared inside an interface can only be abstract. These are the default modifiers for methods. It is not necessary to declare them explicitly, but once again, it makes the code easier to read.

Trying to assign other modifiers, such as protected, results in a compile-time error. Here are example interface method declarations:

public abstract boolean isBlack(Color); 
public abstract boolean isBlack(String);
public abstract StringBuffer promptForName(String);

As you can see in this example, overloaded methods can be declared in an interface just as in a class. An entire interface based on these examples follows:

public interface MyInterface {
   public static final int smtpSocket = 25;
   public static final float pie = 3.14159;
   public static final String = "A DATAPOST COMPUTER CENTER";
   public abstract boolean isBlack(Color);
   public abstract boolean isBlack(String);
   public abstract StringBuffer promptForName(String); 
}

Interfaces also can extend other interfaces, just as classes can extend other classes, using the extends keyword. In the following code, the interface AnInterface declares a variable named theAnswer:

public interface AnInterface {
   public static final int theAnswer = 42;
}
public interface MyInterface extends AnInterface {
   public static final int smtpSocket = 25;
   public static final float pie = 3.14159;
   public static final String = "The quick brown fox";
   public abstract boolean isBlack(Color);
   public abstract boolean isBlack(String);
   public abstract StringBuffer promptForName(String); 
}

The interface MyInterface specifies that it extends AnInterface. This means that any classes that use MyInterface will have access to not only the variables and methods declared in MyInterface, but also those in AnInterface.

You can also list multiple interfaces after the extends keyword. Multiple, possibly disparate, interfaces can be combined into a logical whole if desired, as in the following:

public interface YourInterface extends HerInterface, HisInterface { 
  // body of interface 
} 

Using an Interface
class name [extends classname ] implements interfacename [, interfacename] {
   ... body of class
}

The implements keyword follows the name of the class (or extends declaration) and in turn is followed by one or more comma-separated interface names. The capability to specify a list of interfaces enables a class to have access to a variety of predefined interfaces.

Sample-1
class Note {
	private String noteName;
	private Note(String noteName) {this.noteName = noteName;}
	public String toString() { return noteName; }
	public static final Note
	MIDDLE_C = new Note("Middle C"),
	C_SHARP = new Note("C Sharp"),
	B_FLAT = new Note("B Flat");
}
interface Instrument {
//	Compile-time constant:
	int i = 5; // static & final
//	Cannot have method definitions:
	void play(Note n); // Automatically public
	String what();
	void adjust();
}
class Wind implements Instrument {
	public void play(Note n) {
		System.out.println("Wind.play() " + n);
	}
	public String what() { return "Wind"; }
	public void adjust() {}
}
class Percussion implements Instrument {
	public void play(Note n) {
		System.out.println("Percussion.play() " + n);
	}
	public String what() { return "Percussion"; }
	public void adjust() {}
}
class Stringed implements Instrument {
	public void play(Note n) {
		System.out.println("Stringed.play() " + n);
	}
	public String what() { return "Stringed"; }
	public void adjust() {}
}
class Brass extends Wind {
	public void play(Note n) {
		System.out.println("Brass.play() " + n);
	}
	public void adjust() {System.out.println("Brass.adjust()");
	}
}
class Woodwind extends Wind {
	public void play(Note n) {
		System.out.println("Woodwind.play() " + n);
	}
	public String what() { return "Woodwind"; }
}
public class TestMain{
//	Doesn't care about type, so new types
//	added to the system still work right:
	static void tune(Instrument i) {
//		...
		i.play(Note.MIDDLE_C);
	}
	static void tuneAll(Instrument[] e) {
		for(int i = 0; i < e.length; i++)
			tune(e[i]);
	}
	public static void main(String[] args) {
//		Upcasting during addition to the array:
		Instrument[] orchestra = {
				new Wind(),
				new Percussion(),
				new Stringed(),
				new Brass(),
				new Woodwind()
		};
		tuneAll(orchestra);
	}
}
Sample-2
interface CanFight {
	void fight();
}
interface CanSwim {
	void swim();
}
interface CanFly {
	void fly();
}
class ActionCharacter {
	public void fight() {}
}
class Hero extends ActionCharacter implements CanFight, CanSwim, CanFly {
	public void swim() {}
	public void fly() {}
}
public class TestMain {
	public static void t(CanFight x) { x.fight(); }
	public static void u(CanSwim x) { x.swim(); }
	public static void v(CanFly x) { x.fly(); }
	public static void w(ActionCharacter x) { x.fight(); }
	public static void main(String[] args) {
		Hero h = new Hero();
		t(h); // Treat it as a CanFight
		u(h); // Treat it as a CanSwim
		v(h); // Treat it as a CanFly
		w(h); // Treat it as an ActionCharacter
	}
}
Sample-3
Extending an interface with inheritance - You can easily add new method declarations to an interface using
inheritance, and you can also combine several interfaces into a new interface with inheritance.

interface Monster {
	void menace();
}
interface DangerousMonster extends Monster {
	void destroy();
}
interface Lethal {
	void kill();
}
class DragonZilla implements DangerousMonster {
	public void menace() {}
	public void destroy() {}
}
interface Vampire extends DangerousMonster, Lethal {
	void drinkBlood();
}
class VeryBadVampire implements Vampire {
	public void menace() {}
	public void destroy() {}
	public void kill() {}
	public void drinkBlood() {}
}
public class TestMain {
	static void u(Monster b) { b.menace(); }
	static void v(DangerousMonster d) {
		d.menace();}
	static void w(Lethal l) { l.kill(); }
	public static void main(String[] args) {
		DangerousMonster barney = new DragonZilla();
		u(barney);
		v(barney);
		Vampire vlad = new VeryBadVampire();
		u(vlad);
		v(vlad);
		w(vlad);
	}
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.