Presentation is loading. Please wait.

Presentation is loading. Please wait.

1 Part1 FaaDoOEngineers.com. 2 Day 2 Coverage Inheritance Method Overriding Abstract Class Interface Overview of predefined packages Creating User Defined.

Similar presentations


Presentation on theme: "1 Part1 FaaDoOEngineers.com. 2 Day 2 Coverage Inheritance Method Overriding Abstract Class Interface Overview of predefined packages Creating User Defined."— Presentation transcript:

1 1 Part1 FaaDoOEngineers.com

2 2 Day 2 Coverage Inheritance Method Overriding Abstract Class Interface Overview of predefined packages Creating User Defined Packages FaaDoOEngineers.com

3 Inheritance, Interface & Abstract Class FaaDoOEngineers.com

4 4 Objectives Inheritance Method Overriding Use of super keyword Interface Abstract Class FaaDoOEngineers.com

5 5 No Multiple Inheritance In Java Inheritance The ability of a class of objects to inherit the properties and methods from another class, called its parent or base class. The class that inherits the data members and methods is known as subclass or child class. The class from which the subclass inherits is known as base / parent class. In Java, a class can only extend one parent. What is Inheritance FaaDoOEngineers.com

6 6 public class Person { private String name; public void setName(String name) { this.name = name; } public String getName() { return name; } public class Employee extends Person { private String eid; public void setEid(String eid) { this.eid=eid; } public String getEid() { return eid; } Parent Child Inheritance (Continued) Inheritance (Example) Here ‘extends’ keyword, signaling inheritance FaaDoOEngineers.com

7 7 Example Inheritance (Continued) Types of Inheritance 1. Single Level Inheritance Derives a subclass from a single superclass. Class Person Class EmployeeClass Student FaaDoOEngineers.com

8 8 Example Inheritance (Continued) Types of Inheritance (Continued) 2. Multilevel Inheritance Inherits the properties of another subclass. Class Person Class Employee Class Regular FaaDoOEngineers.com

9 9 Method overriding is defined as creating a method in the subclass that has the same return type and signature as a method defined in the superclass. Signature of a method includes namenumbersequencetype of arguments in a method Method Overriding Overriding Members FaaDoOEngineers.com

10 10 You can override (most) methods in a parent class by defining a method with the same name and parameter list in the child class. This is useful for changing the behavior of a class without changing its interface. You cannot override the static and final methods of a superclass. A subclass must override the abstract methods of a superclass. Method Overriding (Continued) Overriding Members (Continued) FaaDoOEngineers.com

11 11 public class Person { private String name; private String ssn; public void setName(String name) { this.name = name; } public String getName() { return name; } public class Employee extends Person { private String empId; public void setID(String empID) { this.empID=empID; } public String getId() { return ssn; } } public String getId() { return empID; } } getID method is overridde n Example on Method Overriding Overriding Members (Continued) FaaDoOEngineers.com

12 12 Allows you to access methods and properties of the parent class, public class Person { private String name; public Person(String name) { this.name = name; } public String getName() { return name; } public class Employee extends Person { private String empID; public Student(String name) { super(name); // Calls Person constructor } public void setID(String empID){ this.empID=empID; } public String getID(){ return empID; } Use of super keyword Example FaaDoOEngineers.com

13 13 Restricting Inheritance Parent Child Restricting Inherited capability Using modifier with a class will restrict the inheritance capability of that class final FaaDoOEngineers.com

14 14 Final Classes: A way for Preventing Classes being extended We can prevent an inheritance of classes by other classes by declaring them as final classes. This is achieved in Java by using the keyword final as follows: final class Regular { // members } final class Employee extends Person { // members } Any attempt to inherit these classes will cause an error. FaaDoOEngineers.com

15 15 Final Members: A way for Preventing Overriding of Members in Subclasses All methods and variables can be overridden by default in subclasses. This can be prevented by declaring them as final using the keyword “final” as a modifier. For example: final int marks = 100; final void display(); This ensures that functionality defined in this method cannot be altered any. Similarly, the value of a final variable cannot be altered. FaaDoOEngineers.com

16 16 A programmer’s tool for specifying certain behaviors that an object must have in order to be useful for some particular task. Interface is a conceptual entity. Can contain only constants (final variables) and abstract method (no implementation). Use when a number of classes share a common interface. Each class should implement the interface. What is an Interface Interface FaaDoOEngineers.com

17 17 For example, you might specify Driver interface as part of a Vehicle object hierarchy. A human can be a Driver, but so can a Robot. Interface Example Interface (Continued) FaaDoOEngineers.com

18 18 interface InterfaceName { // Constant/Final Variable Declaration // Methods Declaration – only method body } Interface Declaration Interface (Continued) public interface Driver { void turnWheel (double angle); void pressBrake (double amount); } Syntax for Interface Declaration Example FaaDoOEngineers.com

19 19 public class BusDriver extends Person implements Driver { // include each of the two methods from Driver } Interface Implementation Interface (Continued) class ClassName implements Interface1, Interface2,…., InterfaceN { // Body of Class } Syntax for Interface Implementation Example Interfaces are used like super-classes who properties are inherited by classes. This is achieved by creating a class that implements the given interface as follows: FaaDoOEngineers.com

20 20 speak() PoliticianPriest > Speaker speak() Lecturer speak() Interface (Continued) More Examples on Interface FaaDoOEngineers.com

21 21 Declare the Speaker Interface with one method as speak. Define three class namely, Politician Priest Lecturer that implements the Speaker interface and defines the speak method. Interface (Continued) Exercise FaaDoOEngineers.com

22 22 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 extends keyword. interface InterfaceName2 extends InterfaceName1 { // Body of InterfaceName2 } Interface (Continued) Inheriting Interfaces FaaDoOEngineers.com

23 23 An Abstract class is a conceptual class. An Abstract class cannot be instantiated – objects cannot be created. Abstract classes provides a common root for a group of classes, nicely tied together in a package. 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. Abstract Class What is an Abstract Class FaaDoOEngineers.com

24 24 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 implementing them. A subclass that does not implement all of the superclass abstract methods is itself abstract; and it cannot be instantiated. We cannot declare abstract constructors or abstract static methods. Abstract Class (Continued) Properties of an Abstract Class FaaDoOEngineers.com

25 25 Abstract Class (Continued) Abstract Class Example Shape CircleRectangle FaaDoOEngineers.com

26 26 abstract class ClassName {... … abstract DataType MethodName1(); … … DataType Method2() { // method body } } Abstract Class (Continued) Declaration of an Abstract Class Syntax abstract public class Shape { public abstract double area(); public void move() { // non-abstract method // implementation } } Example FaaDoOEngineers.com

27 27 Is the following statement valid? Question Abstract Class (Continued) Shape sh = new Shape(); FaaDoOEngineers.com

28 28 public Circle extends Shape { private double r; private static final double PI =3.1415926535; public Circle() { r = 1.0; } public double area() { return PI * r * r; } … } public Rectangle extends Shape { private double l, b; public Rectangle() { l = 0.0; b=0.0; } public double area() { return l * b; }... } Abstract Class (Continued) Implementation of an Abstract Class FaaDoOEngineers.com

29 29 Exercise Declare the Train class with the following list of methods: OrgName() TrainNo() TrainName() FromTo() Define three class namely, DreamExpress LiveExpress TimeExpress that extends from Train class and define the TrainNo(), TrainName and FromTo() method. FaaDoOEngineers.com

30 30 Inheritance is the concept of extending data members and methods of a superclass in a subclass. You can derive data members and methods from a single superclass that is a subclass of another superclass. Java does not support multiple inheritance directly. You can use the concept of method overriding to override the superclass method with the subclass method having same names. Interface is a concept of creating data members and methods that can be derived by multiple classes in Java. Interfaces also allow you to declare set of constants that can be imported into multiple classes. Summary FaaDoOEngineers.com

31 31 The methods declared in the interface are defined in the class implementing that interface. The methods in an interface are only abstract methods. Abstract classes provides a common root for a group of classes, nicely tied together in a package. Summary (Continued) FaaDoOEngineers.com

32 32 1. The class that inherits the data members and method is known as _ _ _ _ _ _. a. Abstract Class b. Sub class c. Base class d. Inner class 2. Which keyword is used to define the constants in an interface? a. super b. public c. private d. final Test Your Understanding FaaDoOEngineers.com

33 33 3. Which concept of object-oriented programming is used in method overriding? a. Polymorphism b. Abstraction c. Encapsulation d. Inheritance 4. What is the access specifier of the methods declared in an interface? a. Default b. private c. protected d. public Test Your Understanding (Continued) FaaDoOEngineers.com

34 Packages FaaDoOEngineers.com

35 35 Objectives Packages in Java Overview of java.lang package Overview of java.util package Creating User Defined Package FaaDoOEngineers.com

36 36 A package is a set of classes that are stored in a directory, which has the same name as the package name. Packages enable you to organize the class files provided by Java. Packages in Java Java packages are classified into Java defined / Built in packages User defined packages Packages in Java FaaDoOEngineers.com

37 37 Built in Java Packages Packages in Java (Continued) Java Package Name Description java.lang Includes various classes, such as Object, System, Thread etc. java.ioIncludes all Input-Output Stream related classes. java.utilProvides various classes that support Date, Collection. java.sqlProvides API for Database operation FaaDoOEngineers.com

38 38 Built in Java Packages Packages in Java (Continued) Java Package Name Description java.awt Providing Supporting classes for Graphic User Interface components. java.applet Provides the Applet class to create web based application. java.net Includes classes that support network programming such as Socket, DatagramSocket. FaaDoOEngineers.com

39 39 Packages in Java (Continued) Java java.langjava.iojava.utiljava.awtjava.appletjava.netjava.sql Hierarchy of Java Packages FaaDoOEngineers.com

40 40 The java.lang package provides various classes and interfaces that are fundamental to Java programming. The java.lang package contains various classes that represent primitive data types, such as int, char, long, and double. Classes provided by the java.lang package: Exploring java.lang package ClassDescription Object All the classes in the java.lang package are the subclasses of the Object class. System It provides a standard interface to input output and error devices, such as Keyboard & VDU. Packages in Java (Continued) FaaDoOEngineers.com

41 41 Exploring java.lang package (Continued) ClassDescription Class Supports runtime processing of the class information of an object. String Provides functionality for String manipulation. Integer Provides methods to convert an Integer object to a String object. Math Provides functions for statistical, exponential operations. Packages in Java (Continued) FaaDoOEngineers.com

42 42 Exploring java.lang.Wrapper Class Method NameDescription public int intValue() Returns the value of an object as the primitive data type int. public float floatValue() Returns the value of an object as the primitive data type float. public double doubleValue() Returns the value of an object as the primitive data type double. Packages in Java (Continued) FaaDoOEngineers.com

43 43 Exploring java.lang.Math Class Method NameDescription public static int max (int n1 int n2) public static float max (float n1, float n2) public static double max (double n1,double n2) Returns the maximum of two numbers. public static int min (int n1 int n2) public static float min (float n1, float n2) public static double min (double n1,double n2) Returns the minimum of two numbers. public static double sqrt (double x) Returns the positive square root of a number passed as an argument. Packages in Java (Continued) FaaDoOEngineers.com

44 44 Exploring java.lang.Math Class (Continued) Method NameDescription public static int round (float x) public static long round (double x) Returns the integer value closest to the parameter. public static double ceil (double x) Returns the next highest integer of the supplied parameter. public static double floor (double x) Returns the next smallest integer of the supplied parameter. Packages in Java (Continued) FaaDoOEngineers.com

45 45 Exploring java.lang.Math Class (Continued) Method NameDescription public static int abs (int n1) public static float abs (float n1) public static double abs (double n1) Returns the absolute value of that parameter. public static double random() Accepts no argument and returns a positive, double, value randomly generated, greater than or equal to 0.0 and less than 1.0. Packages in Java (Continued) FaaDoOEngineers.com

46 46 Exploring java.lang.String Class Method NameDescription public int length() Returns the length of a String object. public String toUpperCase() Converts all the characters in the string object in uppercase. public String toLowerCase() Converts all the characters in the string object in lowercase. public String toString() Returns the String representation of the object. Packages in Java (Continued) FaaDoOEngineers.com

47 47 Exploring java.lang.String Class (Continued) Method NameDescription public Boolean equals (Object ob) Returns the length of a String object. public int compareTo (String str2) Compares current String object with another String object. If the Strings are same the return value is 0 else the return value is non zero. If str1 > str2 then return value is a positive number If str1<str2 then return value is a negative number Packages in Java (Continued) FaaDoOEngineers.com

48 48 Exploring java.lang.String Class (Continued) Method NameDescription public int indexOf (String str) public int indexOf (String str, int startindex) searches for the first occurrence of a character or a substring in the invoking String and returns the position if found else return -1. public int lastIndexOf(String str) public int lastIndexOf(String str, int startindex) searches for the last occurrence of a character or a substring in the invoking String and returns the position if found else return -1. Packages in Java (Continued) FaaDoOEngineers.com

49 49 Exploring java.lang.String Class (Continued) Method NameDescription public String trim() Returns a copy of the string, with leading and trailing whitespace omitted. public char charAt( int index) Returns the char value at the specified index. public String concat(String str) Concatenates the specified String to the end of the String. public String subString(int startInd) public String subString(int startInd, int endInd) Returns a new String that is a substring of a String. Packages in Java (Continued) FaaDoOEngineers.com

50 50 Exploring java.lang.String Class (Continued) Method NameDescription public boolean startsWith(String prefix) Tests if the String starts with the specified prefix. public boolean endsWith(int suffix) Tests if the String end with the specified suffix. public char[] toCharArray() Converts this String to a new character array. public void getChars(int scrBegin,int srcEnd,char[] destination,int dstBegin) Copies characters from this string into the destination character array. Packages in Java (Continued) FaaDoOEngineers.com

51 51 The java.util package provides various utility classes and interfaces that support date and calendar operations, String manipulations and Collections manipulations. Classes provided by the java.util package: Exploring java.util package ClassDescription DateEncapsulates date and time information. CalendarProvides support for date conversion. GregorianCalendar It is a subclass of Calendar class, provides support for standard calendar used worldwide. Packages in Java (Continued) FaaDoOEngineers.com

52 52 Exploring java.util package (Continued) ClassDescription RandomGenerated a stream of random numbers. ArrayList An indexed sequence that grows and shrinks dynamically. LinkedList An ordered sequence that allows efficient insertions and deletions at any location HashSet An unordered collection that rejects duplicates. HashMap A data structure that stores key/value associations. Packages in Java (Continued) FaaDoOEngineers.com

53 53 Exploring java.util package (Continued) InterfaceDescription List An ordered list of elements that may consist of duplicate elements. SetA group of objects with no duplication. SortedSet A sorted group of objects with no duplication. Enumeration Provides an abstract mechanism for visiting elements in an arbitrary container Map Provides an object that maps keys to values. Packages in Java (Continued) FaaDoOEngineers.com

54 54 A collection is an object that contains a group of objects within it. These objects are called the elements of the collection. The elements of a collection descend from a common parent type. Collections have an advantage over arrays that collections can grow to any size unlike arrays. Collection Interface Packages in Java (Continued) FaaDoOEngineers.com

55 55 Hierarchy of Collection Interface Packages in Java (Continued) Collection SetList SortedSet ArrayListLinkedList HashSet TreeSet Map HashMap TreeMap Interface Class FaaDoOEngineers.com

56 56 The classes of the java.util package were updated to support the concept of collection framework. These classes are referred to as the legacy classes. The various legacy classes defined by the java.util package are: Vector Stack Hashtable Properties Legacy Classes & Interfaces Packages in Java (Continued) FaaDoOEngineers.com

57 57 When you write a Java program, you create many classes. You can organize these classes by creating your own packages. The packages that you create are called user-defined packages. A user-defined package contains one or more classes that can be imported in a Java program. User Defined Packages FaaDoOEngineers.com

58 58 Creating a user-defined package Syntax & Example Syntax for Creating Package package // Class definition public class { // Body of the class. } User Defined Packages (Continued) Example package land.vehicle; public class Car { String brand; String color; int wheels; } FaaDoOEngineers.com

59 59 Create a source file containing the package definition Create a folder having the same name as package name and save the source file within the folder. Compile the source file. Steps To Create User Defined Packages User Defined Packages (Continued) FaaDoOEngineers.com

60 60 You can include a user-defined package or any java API using the import statement. The following syntax shows how to implement the user-defined package, vehicle from land in a class known as MarutiCar import land.vehicle.Car; public class MarutiCar extends Car { // Body of the class. } Importing Packages User Defined Packages (Continued) FaaDoOEngineers.com

61 61 The CLASSPATH variable points to the directories in which the classes that are available to import are present. CLASSPATH enables you to put the class files in various directories and notifies the JDK tools of the region of these classes. CLASSPATH Variable FaaDoOEngineers.com

62 62 Packages enable you to organize the class files provide by Java. The various built-in packages of the Java programming language are: java.lang java.util java.io java.applet java.awt java.net The packages created by users are called user-defined packages. The import statement with the package name enables you to inform the compiler about the region of classes. The java.lang package provides a number of classes and interfaces that are fundamental to Java programming. Summary FaaDoOEngineers.com

63 63 Some of the classes defined in the java.lang package are : The various built-in packages of the Java programming language are: Object Class System Wrapper Character Integer Math String The java.util package provides various utility classes and interfaces that support date/calendar operations, String manipulation. Summary (Continued) FaaDoOEngineers.com

64 64 Some of the classes defined in the java.util package are : Date Calendar GregorianCalendar Random ArrayList LinkedList HashSet TreeSet The various interfaces defined in the java.util package are: Collection List Set SortedSet Summary (Continued) FaaDoOEngineers.com

65 65 Test Your Understanding a. Character class b. Integer class c. Math class d. String class e. StringBuffer class iii. Used for manipulating strings. iv. Wrapper class for the primitive data type char. v. Wrapper class for the primitive data type int. i. Collection of useful numeric constants. ii. Supports operations on strings of characters. Match Group A with B Group AGroup B FaaDoOEngineers.com


Download ppt "1 Part1 FaaDoOEngineers.com. 2 Day 2 Coverage Inheritance Method Overriding Abstract Class Interface Overview of predefined packages Creating User Defined."

Similar presentations


Ads by Google