1 / 45

Abstract Classes

Abstract Classes. Abstract Classes. When we define a class to be “final”, it cannot be extended. In certain situation, we want properties of classes to be always extended and used. Such classes are called Abstract Classes. An Abstract class is a conceptual class.

jacobhunt
Download Presentation

Abstract Classes

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Abstract Classes

  2. Abstract Classes • When we define a class to be “final”, it cannot be extended. • In certain situation, we want properties of classes to be always extended and used. Such classes are called Abstract Classes. • AnAbstract class is a conceptual class. • An Abstractclass cannot be instantiated – objects cannot be created.

  3. Abstract Class Syntax abstract class ClassName { abstractType MethodName1( ); … Type Method2() { // method body } } • When a class contains one or more abstract methods, it should be declared as abstract class. • The abstract methods of an abstract class must be defined in its subclass. • We cannot declare abstract constructors or abstract static methods.

  4. Abstract Class -Example • Shape is a abstract class. Shape Circle Rectangle

  5. The Shape Abstract Class public abstract class Shape { public abstractdouble area(); public void move() { // non-abstract method // implementation } } • Is the following statement valid? • Shape s = new Shape(); • No. It is illegal because the Shape class is an abstract class, which cannot be instantiated to create its objects.

  6. Abstract Classes public Circle extends Shape { protected double r; protected static final double PI =3.1415926535; public Circle() { r = 1.0; ) public double area() { return PI * r * r; } … } public Rectangle extends Shape{ protected double w, h; public Rectangle() { w = 0.0; h=0.0; } public double area() { return w * h; } }

  7. Abstract Classes Properties • A class with one or more abstract methods is automatically abstract and it cannot be instantiated. • A class declared abstract, even with no abstract methods can not be instantiated. • A subclass of an abstract class can be instantiated if it overrides all abstract methods by implementation them.

  8. Design Abstraction and a way for realizing Multiple Inheritance Interfaces

  9. Interfaces • Interfaceis a conceptual entity similar to a Abstract class. • Can contain only constants (final variables) andabstract method(no implementation) - Different from Abstract classes. • Use when a number of classes share a common interface. • Each class should implement the interface.

  10. Interfaces: An informal way of realizing multiple inheritance • An interface contains abstract methods and final variables. • Therefore, it is the responsibility of the class that implements an interface to supply the code for methods. • A class can implement any number of interfaces, but cannot extend more than one class at a time. • Therefore, interfaces are considered as an informal way of realizing multiple inheritance in Java.

  11. Relationship between classes and interfaces • As shown in the figure given below, a class extends another class. • An interface extends another interface but a class implements an interface

  12. Interface -example <<Interface>> Speaker speak() Politician Lecturer speak() speak()

  13. Interfaces Definition interfaceInterfaceName { // Constant/Final Variable Declaration // Methods Declaration – no method body } • Syntax (appears like abstract class): • Example: interfaceSpeaker { public void speak( ); }

  14. The java compiler adds public and abstract keywords before the interface method and public, static and final keywords before data members.

  15. Implementing Interfaces • Interfaces are used like super-classes who's properties are inherited by classes. • This is achieved by creating a class that implements the given interface as follows: class ClassNameimplementsInterfaceName [,InterfaceName2, …] { // Body of Class }

  16. Implementing Interfaces Example class Politician implements Speaker { public void speak(){ System.out.println(“Talk politics”); } } class Lecturer implements Speaker { public void speak(){ System.out.println(“Talks Object Oriented Programming!”); } }

  17. Inheritance and Interface Implementation class ClassName extendsSuperClassimplementsInterfaceName [, InterfaceName2, …] { // Body of Class } • A general form of interface implementation: • This shows a class can extends another class while implementing one or more interfaces. • It appears like a multiple inheritance.

  18. Student Sports extends Exam implements extends Results Student Assessment Example • Consider a university where students who participate in the national games or Olympics are given some grace marks. • Therefore, the final marks awarded = Exam_Marks + Sports_Grace_Marks. A class diagram representing this scenario is as follow:

  19. Implementation class Student { // student Rno and access methods } interface Sport { // sports grace marks (say 5 marks) and abstract methods } class Exam extends Student { // example marks (test1 and test 2 marks) and access methods } class Results extends Exam implements Sport { // implementation of abstract methods of Sport interface // other methods to compute total marks // other display or final results access methods }

  20. interfacePrintable{   void print();   }   interfaceShowable{   void show();   }   classAimplementsPrintable, Showable{   publicvoid print(){System.out.println("Hello");}   publicvoid show(){System.out.println("Welcome");}   publicstaticvoid main(String args[]){   A obj = new A();   obj.print();   obj.show();    }  }  

  21. Extending Interfaces • Like classes, interfaces can also be extended. • The new sub-interface will inherit all the members of the super-interface in the manner similar to classes. • This is achieved by using the keyword extendsas follows: interfaceInterfaceName2 extendsInterfaceName1 { // Body of InterfaceName2 }

  22. interfacePrintable { void print();  } interface Showable extends Printable{   void show();  } classAimplements Showable{   publicvoid print(){System.out.println("Hello");}   publicvoid show(){System.out.println("Welcome");}   publicstaticvoid main(String args[]) { A obj = new A();   obj.print();   obj.show();    }  }

  23. Abstract class Vs Interface abstract class can extend only one class or one abstract class at a time Where as interface can extend any number of interfaces at time. abstract class can be extended from a class or from an abstract class Where as interface can be extended only from an interface. abstract class can have both abstract and concrete methods Where as interface can have only abstract methods. A class can extend only one abstract class Where as a class can implement any number of interfaces.

  24. Abstract class Vs Interface • In abstract class keyword ‘abstract’ is used to declare a method as an abstract where as In an interface keyword ‘abstract’ is optional to declare a method as an abstract • abstract class can have protected , public and public abstract methods where as Interface can have only public abstract methods i.e. by default • abstract class can have static, final or static final variable with any access specifier where as interface can have only static final (constant) variable i.e. by default

  25. DIFFERENCES BETWEEN CLASSES AND INTERFACES

  26. Nested Interfaces • An interface can be declared as a • member of a class or • another interface. • Such an interface is called a member interface or a nested interface. • A nested interface can be declared as public, private, or protected. • Note : top-level interface, must either be declaredas public or use the default access level. • Outside of the class or interface in which a nested interface is declared, its name must be fully qualified.

  27. An example that demonstrates a nested interface class A { public interface NestedIF { boolean isNotNegative(int x); } } class B implements A.NestedIF { // B implements the nested interface. public boolean isNotNegative(int x) { return x < 0 ? false : true; } } class NestedIFDemo { public static void main(String args[]) { A.NestedIFnif = new B(); // use a nested interface reference if(nif.isNotNegative(10)) System.out.println("10 is not negative"); } }

  28. Interface inside Interface Syntax: interface interface_1 { ----- ----- interface interface_2 { -------- -------- } }

  29. Example of nested Interface interface Showable { void show(); interface Messege { void msg(); } } class Test implements Showable.Messege { public void msg() { System.out.println("This is Nested Interface"); } public static void main(String args[]) { Showable.Messege message=new Test(); message.msg(); } }

  30. Accessing Interface Variable • Interface can be used to declare a set of constants that can be used in different classes. • The constant values will be available to any class that implements it. • The values can be used in any method. interface A { int m=10; int n=50; } class B implements A { int x=m; …… }

  31. Packages: Putting Classes Together • One of the main features of OOP is its ability to reuse the code already created. • One way is to inheritance – limited to reusing the classes within the program. • What if we need to use classes from other programs? • This can be accomplished in java by using “Packages” • Similar to “class libraries” in other languages.

  32. Packages in java • Packages are java’s way of grouping a variety of classes and/ or interfaces together. • The grouping is usually done according to functionality. • Packages act as containers for classes. • Examples of packages: lang, awt, util, applet, javax, swing, net, io, sql ,etc.

  33. Advantages of packages • The classes contained in the package can be easily reused. • Two classes in two different packages can have the same name. • Package provide a way to hide classes thus preventing other programs or packages from accessing classes that are for internal use only. • Provide a way of separating “design” from “coding”.

  34. Different Types of Packages: • There are two types of packages in Java: • Built-in packages • User-defined packages

  35. Built-in packages • They are also called as Java API Packages. • Java API provides a large number of classes grouped into different packages according to functionality.

  36. Java API Packages • Java.lang: lang stands for language. • This package got primary classes and interfaces essential for developing a basic Java program. • It consists of wrapper classes , String, SttringBuffer, StringBuilder classes to handle strings, thread class. • Java.util: util stands for utility. • This package contains useful classes and interfaces like Stack, LinkedList, Hashtable, Vector, Arrays, Date and Time classes. • Java.io:io stands for input and output. • This package contains streams. A stream represents flow of data from one place to another place. Streams are useful to store data in the form of files and also to perform input-output related tasks.

  37. Java API Packages • Java.awt:awt stands for abstract window toolkit. • This helps to develop GUI(Graphical user Interfaces) with colorful screens, paintings and images etc., can be developed. It consists of , classes which are useful to provide action for components like push buttons, radio buttons, menus etc. • Java.net:net stands for network. • Client-Server programming can be done by using this package. Classes related to obtaining authentication for network, client and server to establish communication between them are also available in java.net package. • Java.applet: • applets are programs which come from a server into a client and get executed on the client machine on a network. Applet class of this package is useful to create and use applets.

  38. Using System packages javajavajava java awt • The package name java contains package awt, which contains various classes required for implementing GUI. • Hierarchical representation of java.awt package. Color Graphics Fonts Images

  39. Using System Packages • Classes stored in packages can be accessed in two ways • Use the fully qualified class name of class that we want to use. This is done by using package name containing the class name using dot operator. • Example : import java.awt.Color • In many situations we might use class name in number of places in the program or we may like to use many classes of that package then- • Example: import java.awt.*

  40. Naming Conventions • Package names are written in lower case to avoid conflict with the names of classes or interfaces. • All class names begin with uppercase letters and methods with lower case letters. double y=java.lang.Math.sqrt(x); Class name Method name Package Name

  41. User-Defined packages: • Just like the built in packages shown earlier, the users of the Java language can also create their own packages. • They are called user-defined packages. • User-defined packages can also be imported into other classes and used exactly in the same way as the Built-in packages.

  42. Creating Packages • package packagename; //to create a package • package packagename.subpackagename; • //to create a sub package within a package. e.g.: package pack; • The first statement in the program must be first statement while creating a package. • While creating a package except instance variables, declare all the members and the class itself as public then only the public members are available outside the package to other programs.

  43. A program to create a package pack with Addition class. package pack; public class Addition { private double d1,d2; public Addition(double a,double b) { d1 = a; d2 = b; } public void sum() { System.out.println ("Sum of two given numbers is : " + (d1+d2) ); } }

More Related