Sie sind auf Seite 1von 65

Part1

FaaDoOEngineers.com
1 FaaDoOEngineers.com

Day 2 Coverage

Inheritance
Method Overriding Abstract Class Interface Overview of predefined packages Creating User Defined Packages

FaaDoOEngineers.com

Inheritance, Interface & Abstract Class

FaaDoOEngineers.com

FaaDoOEngineers.com

Objectives
Inheritance
Method Overriding Use of super keyword Interface Abstract Class

FaaDoOEngineers.com

Inheritance What is 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.

No Multiple Inheritance In Java


5 FaaDoOEngineers.com

Inheritance (Continued) Inheritance (Example)


Parent Child

Here extends keyword, signaling inheritance

public class Person { private String name; public void setName(String name) { this.name = name; } public String getName() { return name; } }
6 FaaDoOEngineers.com

public class Employee extends Person { private String eid; public void setEid(String eid) { this.eid=eid; } public String getEid() { return eid; } }

Inheritance (Continued) Types of Inheritance


1. Single Level Inheritance Derives a subclass from a single superclass.

Example
Class Person

Class Employee
7 FaaDoOEngineers.com

Class Student

Inheritance (Continued) Types of Inheritance (Continued)


2. Multilevel Inheritance Inherits the properties of another subclass.

Example
Class Person

Class Employee

Class Regular
8 FaaDoOEngineers.com

Overriding Members Method Overriding


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

name

number

sequence

type

of arguments in a method
9 FaaDoOEngineers.com

Overriding Members (Continued) Method Overriding (Continued)


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.

10

FaaDoOEngineers.com

Overriding Members (Continued) Example on Method Overriding


public class Person { private String name; private String ssn; public void setName(String name) { this.name = name; } public String getName() { return name; } public String getId() { return ssn; } }
11 FaaDoOEngineers.com

public class Employee extends Person { private String empId;

public void setID(String empID) { this.empID=empID; } public String getId() { return empID; } }

getID method is overridde n

Use of super keyword

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;

Example public Student(String name) {


super(name); // Calls Person constructor } public void setID(String empID){ this.empID=empID; } public String getID(){ return empID; } }

12

FaaDoOEngineers.com

Restricting Inheritance

Parent
Using final modifier with a class will restrict the inheritance capability of that class
Restricting Inherited capability

Child

13

FaaDoOEngineers.com

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.

14

FaaDoOEngineers.com

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.

15

FaaDoOEngineers.com

Interface What is an Interface


A programmers 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.

16

FaaDoOEngineers.com

Interface (Continued) Interface Example

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.

17

FaaDoOEngineers.com

Interface (Continued) Interface Declaration


interface InterfaceName public interface Driver {{ Constant/Final Variable Declaration void // turnWheel (double angle); Methods Declaration only method body void // pressBrake (double amount); Syntax for Interface }

Example Declaration

18

FaaDoOEngineers.com

Interface (Continued) Interface Implementation


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:

Syntax for Interface Example Implementation


class ClassName implements Interface1, Interface2,., InterfaceN public class BusDriver extends Person implements Driver { { // Body of Class // include each of the two methods from Driver } }
19 FaaDoOEngineers.com

Interface (Continued) More Examples on Interface


<<Interface>> Speaker
speak()

Politician speak()

Priest speak()

Lecturer speak()

20

FaaDoOEngineers.com

Interface (Continued) Exercise



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.

21

FaaDoOEngineers.com

Interface (Continued) Inheriting 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 extends keyword.

interface InterfaceName2 extends InterfaceName1 { // Body of InterfaceName2 }

22

FaaDoOEngineers.com

Abstract Class What is an Abstract Class



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.

23

FaaDoOEngineers.com

Abstract Class (Continued) Properties of an Abstract Class


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.

24

FaaDoOEngineers.com

Abstract Class (Continued) Abstract Class Example

Shape

Circle

Rectangle

25

FaaDoOEngineers.com

Abstract Class (Continued) Declaration of an Abstract Class


abstract class ClassName {

abstract public class Shape { public abstract double area();

... abstract DataType MethodName1(); DataType Method2() { // method body }


}

Example Syntax

public void move() { // non-abstract method // implementation } }

26

FaaDoOEngineers.com

Abstract Class (Continued) Question

Is the following statement valid?

Shape sh = new Shape();

27

FaaDoOEngineers.com

Abstract Class (Continued) Implementation of an Abstract Class


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; } ... }
28 FaaDoOEngineers.com

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.

29

FaaDoOEngineers.com

Summary

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.

30

FaaDoOEngineers.com

Summary (Continued)

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.

31

FaaDoOEngineers.com

Test Your Understanding


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
32 FaaDoOEngineers.com

Test Your Understanding (Continued)


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
33 FaaDoOEngineers.com

Packages
FaaDoOEngineers.com

FaaDoOEngineers.com

Objectives

Packages in Java Overview of java.lang package Overview of java.util package Creating User Defined Package

35

FaaDoOEngineers.com

Packages in Java Packages in Java



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.

Java packages are classified into

Java defined / Built in packages


36 FaaDoOEngineers.com

User defined packages

Packages in Java (Continued) Built in Java Packages


Java Package Name
java.lang java.io java.util java.sql

Description
Includes various classes, such as Object, System, Thread etc. Includes all Input-Output Stream related classes. Provides various classes that support Date, Collection. Provides API for Database operation

37

FaaDoOEngineers.com

Packages in Java (Continued) Built in Java Packages


Java Package Name
java.awt java.applet

Description
Providing Supporting classes for Graphic User Interface components. Provides the Applet class to create web based application. Includes classes that support network programming such as Socket, DatagramSocket.

java.net

38

FaaDoOEngineers.com

Packages in Java (Continued) Hierarchy of Java Packages

Java

java.lang

java.io

java.util

java.awt

java.applet

java.net

java.sql

39

FaaDoOEngineers.com

Packages in Java (Continued) Exploring java.lang package


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:

Class
Object

Description
All the classes in the java.lang package are the subclasses of the Object class. It provides a standard interface to input output and error devices, such as Keyboard & VDU.

System

40

FaaDoOEngineers.com

Packages in Java (Continued) Exploring java.lang package (Continued)


Class
Class String Integer Math

Description
Supports runtime processing of the class information of an object.
Provides functionality for String manipulation. Provides methods to convert an Integer object to a String object. Provides functions for statistical, exponential operations.

41

FaaDoOEngineers.com

Packages in Java (Continued) Exploring java.lang.Wrapper Class


Method Name
public int intValue() public float floatValue() public double doubleValue()

Description
Returns the value of an object as the primitive data type int. Returns the value of an object as the primitive data type float. Returns the value of an object as the primitive data type double.

42

FaaDoOEngineers.com

Packages in Java (Continued) Exploring java.lang.Math Class


Method Name
public static int max (int n1 int n2) public static float max (float n1, float n2) public static double max (double n1,double n2) public static int min (int n1 int n2) public static float min (float n1, float n2) public static double min (double n1,double n2) public static double sqrt (double x) Returns the positive square root of a number passed as an argument. Returns the minimum of two numbers. Returns the maximum of two numbers.

Description

43

FaaDoOEngineers.com

Packages in Java (Continued) Exploring java.lang.Math Class (Continued)


Method Name
public static int round (float x) public static long round (double x)

Description
Returns the integer value closest to the parameter. Returns the next highest integer of the supplied parameter. Returns the next smallest integer of the supplied parameter.

public static double ceil (double x)

public static double floor (double x)

44

FaaDoOEngineers.com

Packages in Java (Continued) Exploring java.lang.Math Class (Continued)


Method Name
public static int abs (int n1)

Description
Returns the absolute value of that parameter.

public static float abs (float n1)


public static double abs (double n1)

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.

45

FaaDoOEngineers.com

Packages in Java (Continued) Exploring java.lang.String Class


Method Name
public int length()

Description
Returns the length of a String object. Converts all the characters in the string object in uppercase. Converts all the characters in the string object in lowercase. Returns the String representation of the object.

public String toUpperCase()

public String toLowerCase()

public String toString()

46

FaaDoOEngineers.com

Packages in Java (Continued) Exploring java.lang.String Class (Continued)


Method Name
public Boolean equals (Object ob)

Description
Returns the length of a String object. 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

public int compareTo (String str2)

47

FaaDoOEngineers.com

Packages in Java (Continued) Exploring java.lang.String Class (Continued)


Method Name Description
searches for the first occurrence of a character or a substring in the invoking String and returns the position if found else return -1. searches for the last occurrence of a character or a substring in the invoking String and returns the position if found else return -1.

public int indexOf (String str) public int indexOf (String str, int startindex)

public int lastIndexOf(String str) public int lastIndexOf(String str, int startindex)

48

FaaDoOEngineers.com

Packages in Java (Continued) Exploring java.lang.String Class (Continued)


Method Name
public String trim()

Description
Returns a copy of the string, with leading and trailing whitespace omitted. Returns the char value at the specified index. Concatenates the specified String to the end of the String. Returns a new String that is a substring of a String.

public char charAt( int index)

public String concat(String str)

public String subString(int startInd)


public String subString(int startInd, int endInd)
49 FaaDoOEngineers.com

Packages in Java (Continued) Exploring java.lang.String Class (Continued)


Method Name
public boolean startsWith(String prefix)

Description
Tests if the String starts with the specified prefix. Tests if the String end with the specified suffix. Converts this String to a new character array. Copies characters from this string into the destination character array.

public boolean endsWith(int suffix)

public char[] toCharArray() public void getChars(int scrBegin,int srcEnd,char[] destination,int dstBegin)

50

FaaDoOEngineers.com

Packages in Java (Continued) Exploring java.util package

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:

Class
Date Calendar

Description
Encapsulates date and time information. Provides support for date conversion. It is a subclass of Calendar class, provides support for standard calendar used worldwide.

GregorianCalendar

51

FaaDoOEngineers.com

Packages in Java (Continued) Exploring java.util package (Continued)


Class
Random ArrayList

Description
Generated a stream of random numbers. An indexed sequence that grows and shrinks dynamically. An ordered sequence that allows efficient insertions and deletions at any location An unordered collection that rejects duplicates. A data structure that stores key/value associations.

LinkedList

HashSet

HashMap

52

FaaDoOEngineers.com

Packages in Java (Continued) Exploring java.util package (Continued)


Interface
List Set SortedSet Enumeration Map

Description
An ordered list of elements that may consist of duplicate elements.
A group of objects with no duplication. A sorted group of objects with no duplication. Provides an abstract mechanism for visiting elements in an arbitrary container Provides an object that maps keys to values.

53

FaaDoOEngineers.com

Packages in Java (Continued) Collection Interface



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.

54

FaaDoOEngineers.com

Packages in Java (Continued) Hierarchy of Collection Interface


Collection Map

Set

List

HashMap

TreeMap

HashSet SortedSet

ArrayList

LinkedList

Interface Class

TreeSet
55 FaaDoOEngineers.com

Packages in Java (Continued) Legacy Classes & Interfaces

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

56

FaaDoOEngineers.com

User Defined Packages User Defined Packages


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.

57

FaaDoOEngineers.com

User Defined Packages (Continued) Syntax & Example

Creating a user-defined package package <package_name> // Class definition package land.vehicle; public class Car {

Syntax public class <classname1>


{

for Creating Example Package // Body of the class.

String brand;
String color; int wheels; }

58

FaaDoOEngineers.com

User Defined Packages (Continued) Steps To Create User Defined Packages



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.

59

FaaDoOEngineers.com

User Defined Packages (Continued) Importing Packages



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. }

60

FaaDoOEngineers.com

CLASSPATH Variable

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.

61

FaaDoOEngineers.com

Summary

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.

62

FaaDoOEngineers.com

Summary (Continued)

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.

63

FaaDoOEngineers.com

Summary (Continued)

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
FaaDoOEngineers.com

64

Test Your Understanding


Match Group A with B

Group A
a. Character class b. Integer class c. Math class d. String class e. StringBuffer class
65 FaaDoOEngineers.com

Group B
i. Collection of useful numeric constants.

ii. Supports operations on strings of characters. iii. Used for manipulating strings. iv. Wrapper class for the primitive data type char. v. Wrapper class for the primitive data type int.

Das könnte Ihnen auch gefallen