26
Abstract Interface

9- Abstract classes and interfaces (1) JAVA

Embed Size (px)

Citation preview

Page 1: 9- Abstract classes and interfaces (1) JAVA

Abstract Interface

Page 2: 9- Abstract classes and interfaces (1) JAVA

Abstract Classes

• An abstract is incomplete• It has “missing” method bodies

• The class that contains an abstract method is called an abstract class

• You must declare the class with the keyword abstract:abstract class MyClass {...}

• In order to postpone the definition of a method• An abstract method has a heading, but no method body

• The body of the method is defined in the child classes

• You cannot instantiate (create a new instance of) an abstract class

• Abstract classes contain mixture of non-abstract and abstract methods.

Page 3: 9- Abstract classes and interfaces (1) JAVA

Abstract Classes

• You can extend (subclass) an abstract class• If the subclass defines all the inherited abstract methods, it is “complete” and

can be instantiated

• If the subclass does not define all the inherited abstract methods, it too must be abstract

• You can declare a class to be abstract even if it does not contain any abstract methods• This prevents the class from being instantiated

Page 4: 9- Abstract classes and interfaces (1) JAVA

Abstract Class Example

• public abstract class A {

• public A(){

• System.out.println("A class");

• }

• abstract void show();

• public void display(A a){

• a.show();

• }

• }

• public class B extends A{

• void show(){

• System.out.println(" B class Show Method");

• }

• }

• public class C extends A{

• void show(){

• System.out.println(" C class Show Method");

• }

• }

• public class CallMain {

• public static void main(String[] args) {

• A a = new B();

• a.display(a);

• a = new C();

• a.display(a);

• }

• }

Page 5: 9- Abstract classes and interfaces (1) JAVA

Abstract Class Example 1

• public abstract class A {

• public A(){

• System.out.println("A class");

• }

• abstract void show();

• public void display(A a){

• a.show();

• }

• }

• public class JavaApplication12 {

• public static void main(String[] args) {

• A a = new A(){

• void show() {

• System.out.println("this---");

• }

• };

• a.display(a);

• }

• }

Page 6: 9- Abstract classes and interfaces (1) JAVA

Interface

• An interface is a collection of abstract methods. A class implements an interface

• An interface is not a class. Writing an interface is similar to writing a class, but they are two different concepts. A class describes the attributes and behaviors of an object. An interface contains behaviors that a class implements.

• Unless the class that implements the interface is abstract, all the methods of the interface need to be defined in the class.

Page 7: 9- Abstract classes and interfaces (1) JAVA

However, an interface is different from a class in several ways, including:

1. You cannot instantiate an interface.

2. An interface does not contain any constructors.

3. All of the methods in an interface are abstract.

4. An interface cannot contain instance fields. The only fields that can appear in an interface must be declared both static and final.

5. An interface is not extended by a class; it is implemented by a class.

6. An interface can extend multiple interfaces.

Page 8: 9- Abstract classes and interfaces (1) JAVA

Declaring Interfaces:

• The interface keyword is used to declare an interface. Here is a simple example to declare an interface:

• /* File name : Animal.java */

• interface Animal {

• public void eat();

• public void travel();

• }

Page 9: 9- Abstract classes and interfaces (1) JAVA

Implementing Interfaces:• When a class implements an interface, you can think of the class as

signing a contract, agreeing to perform the specific behaviors of the interface. If a class does not perform all the behaviors of the interface, the class must declare itself as abstract.

• A class uses the implements keyword to implement an interface. The implements keyword appears in the class declaration following the extends portion of the declaration.

Page 10: 9- Abstract classes and interfaces (1) JAVA

• /* File name : MammalInt.java */

• public class MammalInt implements Animal{

• public void eat(){

• System.out.println("Mammal eats");

• }

• public void travel(){

• System.out.println("Mammal travels");

• }

• public static void main(String args[]){

• MammalInt m = new MammalInt();

• m.eat();

• m.travel();

• }

• }

• This would produce following result

• Mammal eats

• Mammal travels

Implementing Interfaces:

Page 11: 9- Abstract classes and interfaces (1) JAVA

Implementing Interfaces:

• When overriding methods defined in interfaces there are several rules to be followed:

• Checked exceptions should not be declared on implementation methods other than the ones declared by the interface method or subclasses of those declared by the interface method.

• The signature of the interface method and the same return type or subtype should be maintained when overriding the methods.

• An implementation class itself can be abstract and if so interface methods need not be implemented.

• When implementation interfaces there are several rules:

• A class can implement more than one interface at a time.

• A class can extend only one class, but implement many interface.

• An interface can extend another interface, similarly to the way that a class can extend another class

Page 12: 9- Abstract classes and interfaces (1) JAVA

• //Filename: Sports.java

• public interface Sports

• {

• public void setHomeTeam(String name);

• public void setVisitingTeam(String name);

• }

• //Filename: Football.java

• public interface Football extends Sports

• {

• public void homeTeamScored(int points);

• public void visitingTeamScored(int points);

• public void endOfQuarter(int quarter);

• }

• //Filename: Hockey.java

• public interface Hockey extends Sports

• {

• public void homeGoalScored();

• public void visitingGoalScored();

• public void endOfPeriod(int period);

• public void overtimePeriod(int ot);

• }

• The Hockey interface has four methods, but it inherits two from Sports; thus, a class that implements Hockey needs to implement all six methods. Similarly, a class that implements Football needs to define the three methods from Football and the two methods from Sports

Page 13: 9- Abstract classes and interfaces (1) JAVA

Extending Multiple Interfaces

• A Java class can only extend one parent class. Multiple inheritance is not allowed. Interfaces are not classes, however, and an interface can extend more than one parent interface.

• The extends keyword is used once, and the parent interfaces are declared in a comma-separated list.

• For example, if the Hockey interface extended both Sports and Event, it would be declared as:

• public interface Hockey extends Sports, Rules{

• }

Page 14: 9- Abstract classes and interfaces (1) JAVA

Interface Example

• public interface D {

• public void welcome();

• }

• public class CallMain {

• public static void main(String[] args) {

• new D(){

• @Override

• public void welcome() {

• System.out.println("Interface");

• }

• }.welcome();

• }

• }

Page 15: 9- Abstract classes and interfaces (1) JAVA

Generalization, Specialization

• Both use in Inheritence

• Generalization is a bottom up design process

• Specialization is a top down design process

• Realization relationship between interface and implement class

• Encapsulation

Page 16: 9- Abstract classes and interfaces (1) JAVA
Page 17: 9- Abstract classes and interfaces (1) JAVA

Introducing Nested and Inner Classes• a class within another class; such classes are known as nested classes

• The scope of a nested class is bounded by the scope of its enclosing class. Thus, if class B is defined within class A, then B is known to A, but not outside of A.

• Nested classes are divided into two categories: static and non-static. Nested classes that are declared static are simply called static nested classes. Non-static nested classes are called inner classes.

• class OuterClass {

• ...

• static class StaticNestedClass {

• ...

• }

• class InnerClass {

• ...

• }

• }

Page 18: 9- Abstract classes and interfaces (1) JAVA

Why Use Nested Classes?• There are several compelling reasons for using nested classes, among them:

• It is a way of logically grouping classes that are only used in one place.

• It increases encapsulation.

• Nested classes can lead to more readable and maintainable code.

• Logical grouping of classes—If a class is useful to only one other class, then it is logical to embed it in that class and keep the two together. Nesting such "helper classes" makes their package more streamlined.

• Increased encapsulation—Consider two top-level classes, A and B, where B needs access to members of A that would otherwise be declared private. By hiding class B within class A, A's members can be declared private and B can access them. In addition, B itself can be hidden from the outside world.

• More readable, maintainable code—Nesting small classes within top-level classes places the code closer to where it is used.

Page 19: 9- Abstract classes and interfaces (1) JAVA

• class Outer {

• int outer_x = 100;

• void test() {

• Inner inner = new Inner();

• inner.display();

• }

• // this is an inner class

• class Inner {

• void display() {

• System.out.println("display: outer_x = " + outer_x);

• }

• }

• }

• class InnerClassDemo {

• public static void main(String args[]) {

• Outer outer = new Outer();

• outer.test();

• }

• }

• OR

• class InnerClassDemo {

• public static void main(String args[]) {

• Outer outer = new Outer();

• Outer.Inner innerObject = outer.new Inner();

• outer.test();

• innerObject.display();

• }

• }

Page 20: 9- Abstract classes and interfaces (1) JAVA

• class Outer {

• int outer_x = 100;

• void test() {

• Inner inner = new Inner();

• inner.display();

• }

• // this is an inner class

• class Inner {

• int y = 10; // y is local to Inner

• void display() {

• System.out.println("display: outer_x = " + outer_x);

• }

• }

• void showy() {

• System.out.println(y); // error, y not known here!

• }

• }//end class

• class InnerClassDemo {

• public static void main(String args[]) {

• Outer outer = new Outer();

• outer.test();

• }

• }

Page 21: 9- Abstract classes and interfaces (1) JAVA

• class Outer {

• int outer_x = 100;

• void test() {

• for(int i=0; i<10; i++) {

• class Inner {

• void display() {

• System.out.println("display: outer_x = " + outer_x);

• }

• }

• Inner inner = new Inner();

• inner.display();

• }

• }

• }

• class InnerClassDemo {

• public static void main(String args[]) {

• Outer outer = new Outer();

• outer.test();

• } }

Page 22: 9- Abstract classes and interfaces (1) JAVA

Inner Class

• class EnclosingClass {

• static class Nested {

• void someMethod() { System.out.println("hello"); }

• }

• }

• class NonEnclosingClass {

• public static void main(String[] args) {

• EnclosingClass.Nested n = new EnclosingClass.Nested();

• n.someMethod(); //prints out "hello"

• }

• }

Page 23: 9- Abstract classes and interfaces (1) JAVA

Anonymous Classes

• Anonymous classes in Java are more accurately known as anonymous inner classes

• the fact that they are anonymous inner classes means that they are defined inside another class

• An anonymous inner class also has unusual syntax.

• Anonymous classes enable you to make your code more concise. They enable you to declare and instantiate a class at the same time. They are like local classes except that they do not have a name. Use them if you need to use a local class only once.

Page 24: 9- Abstract classes and interfaces (1) JAVA

Anonymous Classes

• Why use an anonymous class?

• Anonymous classes can be time-savers and reduce the number of .java files necessary to define an application.

• Rules:-

• An anonymous class must implement all the abstract methods in the super class or the interface.

Page 25: 9- Abstract classes and interfaces (1) JAVA

Anonymous Classes Example

• class ProgrammerInterview {

• public void read() {

• System.out.println("Programmer Interview!");

• }

• }

• class Website {

• public static void main(String... args) {

• ProgrammerInterview pInstance = new ProgrammerInterview() {

• public void read() {

• System.out.println("anonymous ProgrammerInterview");

• }

• };

• pInstance.read();

• }

• }

Page 26: 9- Abstract classes and interfaces (1) JAVA

• public class HelloWorldAnonymousClasses {

• interface HelloWorld {

• public void greet();

• public void greetSomeone(String someone);

• }

• public void sayHello() {

• class EnglishGreeting implements HelloWorld {

• String name = "world";

• public void greet() {

• greetSomeone("world");

• }

• public void greetSomeone(String someone) {

• name = someone;

• System.out.println("Hello " + name);

• }

• }//end inner class

• HelloWorld englishGreeting = new EnglishGreeting();

• HelloWorld frenchGreeting = new HelloWorld() {

• String name = "tout le monde";

• public void greet() {

• greetSomeone("tout le monde");

• }

• public void greetSomeone(String someone) {

• name = someone;

• System.out.println("Salut " + name);

• }

• }; //end anonymous class

• englishGreeting.greet();

• frenchGreeting.greetSomeone("Fred");

• }//end sayHello

• public static void main(String... args) {

• HelloWorldAnonymousClasses myApp =

• new HelloWorldAnonymousClasses();

• myApp.sayHello();

• }

• }