20IT301 JAVA PROGRAMMING By M.Mohanraj Assistant Professor Department of Artificial Intelligence and Data Science Kongunadu College of Engineering
UNIT-2
TOPICS 1 2 3 4 5 6 7 1 Hierarchical abstractions Base class object. subclass, subtype, substitutability. forms of inheritance- specialization, construction, extension, limitation, combination. Benefits of inheritance, costs of inheritance. 2 Memberaccess rules, super uses, using final with inheritance. polymorphism- method overriding, abstract classes. Defining, Creating and Accessing a Package Importing packages 3 Differences between classesand interfaces 4 Defining an interface 5 Implementing interface 6 Applying interfaces 7 variables in interface and extending interfaces
10 Inheritance ⚫Methodsallows a software developer to reuse a sequence of statements ⚫Inheritance allows a software developer to reuse classes by deriving a new class from an existing one ⚫The existing class is called the parent class, or superclass, or base class ⚫The derived class is called the child class or subclass. ⚫As the name implies, the child inherits characteristics of the parent ⚫That is, the child class inherits the methods and data defined for the parent class
10 I⚫nInhheerirtaintcaenrelcateionship s are often shown graphically in a class diagram, with the arrow pointing to the parent class Inheritance should create an is-a relationship, meaning the child is a more specific version of the parent Animal weight : int + getWeight() : int Bird + fly() : void
10 Deriving Subclasses ⚫In Java, we use the reserved word extends to establish an inheritance relationship class Animal { // class contents int weight; public void int getWeight() {…} } class Bird extends Animal { // class contents public void fly() {…}; }
11 Class Hierarchy ⚫A child class of one parent can be the parent of another child, forming class hierarchies Animal Reptile Bird Mammal Snak e Lizar d Hors e Ba t Parrot  At the top of the hierarchy there’s a default class
1 Class Hierarchy ⚫Good class design puts all common features as high in the hierarchy as reasonable ⚫inheritance is transitive ⚫ An instance of class Parrot is also an instance of Bird, an instance of Animal, …, and an instance of class Object ⚫The class hierarchy determines how methods are executed: ⚫ Previously, we took the simplified view that when variable v is an instance of class C, then a procedure call v.proc1() invokes the method proc1() defined in class C ⚫ However, if C is a child of some superclass C’ (and hence v is both an instance of C and an instance of C’), the picture becomes more complex, because methods of class C can override the methods of class C’ (next two slides).
11 Defining Methods in the Child Class: Overriding by Replacement ⚫ A child class can override the definition of an inherited method in favorof its own ⚫ that is, a child can redefine a method that it inherits from its parent ⚫ the new method must have the same signature as the parent's method, but can have different code in the body ⚫ In java, all methods except of constructors override the methods of their ancestor class by replacement. E.g.: ⚫ the Animal class has method eat() ⚫ the Bird class has method eat() and Bird extends Animal ⚫ variable b is of class Bird, i.e. Bird b = … ⚫ b.eat() simply invokes the eat() method of the Bird class ⚫ If a method is declared with the final modifier, it cannot be overridden
Defining Methods in the Child Class: Overriding by Refinement ⚫ Constructors in a subclass override the definition of an inherited constructor method by refining them (instead of replacing them) - Assume class Animal has constructors Animal(), Animal(int weight), Animal(int weight, int livespan) - Assume class Bird which extends Animal has constructors Bird(), Bird(int weight), Bird(int weight, int livespan) - Let’s say we createa Bird object, e.g. Bird b = Bird(5) - This will invoke first the constructorof the Animal (the superclass of Bird) and then theconstructorof the Bird ⚫ This is called constructor chaining: If class C0 extends C1 and C1 extends C2 and … Cn-1 extends Cn = Object then when creating an instance of object C0 first constructor of Cn is invoked, then constructors of Cn-1, …, C2, C1, and finally the constructorof C - The constructors (in each case) arechosen by their signature, e.g. (), (int), etc… - If no constructor with matching signature is found in any of the class Ci for i>0 then the default constructor is executed for that class - If no constructor with matching signature is found in the class C0 then this
11 Recap: Class Hierarchy ⚫ In Java, a class can extend a single otherclass (If none is stated then it implicitly extends an Object class) Animal Reptile Bird Mammal Snake Lizard Hors e Ba t Parrot  Imagine what would happen to method handling rules if every class could extend two others…
Hierarchical Abstraction ⚫An essential element of object-oriented programming is abstraction. ⚫Humans manage complexity through abstraction. For example, people do not think of a car as a set of tens of thousands of individual parts. They think of it as a well- defined object with its own unique behavior. ⚫This abstraction allows people to use a car without being overwhelmed by the complexity of the parts that form the car. They can ignore the details of how the engine, transmission, and braking systems work. ⚫Instead they are free to utilize the object as a whole.
Class Hierarchy ⚫A child class of one parent can be the parent of another child, forming class hierarchies Animal Reptile Bird Mammal Snake Lizard Horse Bat Parrot  At the top of the hierarchy there’s a default class called Object.
Class Hierarchy ⚫Good class design puts all common features as high in the hierarchy as reasonable ⚫The class hierarchy determines how methods are executed ⚫inheritance is transitive ⚫An instance of class Parrot is also an instance of Bird, an instance of Animal, …, and an instance of class Object
Base Class Object ⚫In Java, all classes use inheritance. ⚫If no parent class is specified explicitly, the base class Object is implicitly inherited. ⚫All classes defined in Java, is a child of Object class, which provides minimal functionality guaranteed to e common to all objects. ⚫Methods defined in Object class are; 1. equals(Object obj): Determine whether the argument object is the same as the receiver. 2. getClass(): Returns the class of the receiver, an object of type Class. 3. hashCode(): Returns a hash value for this object. Should be overridden when the equals method is changed. 4. toString(): Converts object into a string value. This method is also often overridden.
Base class 1)a class obtains variables and methods from another class 2) the former is called subclass, the latter super-class (Base class) 3)a sub-class provides a specialized behavior with respect to its super-class 4)inheritance facilitates code reuse and avoids duplication of data Extends  Is a keyword used to inherit a class from another class Allows to extend f rom only one class  class One { int a=5; } class Two extends One { int b=10; }
Subclass, Subtype and Substitutability ⚫A subtype is a class that satisfies the principle of substitutability. ⚫A subclass is something constructed using inheritance, whether or not it satisfies the principle of substitutability. ⚫The two concepts are independent. Not all subclasses are subtypes, and (at least in some languages) you can construct subtypes that are not subclasses. ⚫Substitutability is fundamental to many of the powerful software development techniques in OOP. ⚫The idea is that, declared a variable in one type may hold the value of different type. ⚫Substitutability can occur through use of inheritance, whether using extends, or using implements keywords.
Subclass, Subtype, and Substitutability When new classes are constructed using inheritance, the argument used to justify the validity of substitutability is as follows; •Instances of the subclass must possess all data fields associated with its parent class. • Instances of the subclass must implement, through inheritance at least, all functionality defined for parent class. (Defining new methods is not important for the argument.) • Thus, an instance of a child class can mimic the behavior of the parent class and should be indistinguishable from an instance of parent class if substituted in a similar situation.
Subclass, Subtype, and Substitutability The term subtype is used to describe the relationship between types that explicitly recognizes the principle of substitution. A type B is considered to be a subtype of A if an instances of B can legally be assigned to a variable declared as of type A. The term subclass refers to inheritance mechanism made by extends keyword. Not all subclasses are subtypes. Subtypes can also be formed using interface, linking types that have no inheritance relationship.
Subclass ⚫ Methods allows to reuse a sequenceof statements ⚫ Inheritance allows to reuse classes by deriving a new class from an existing one ⚫ The existing class is called the parent class, or superclass, or base class ⚫ The derived class is called the child class or subclass. ⚫ As the name implies, the child inherits characteristics of the parent(i.e the child class inherits the methods and data defined for the parent class
Subtype ⚫Inheritance relationships are often shown graphically in a class diagram, with the arrow pointing to the parent class Animal weight : int + getWeight() : int Bird + fly() : void
Substitutability (Deriving Subclasses) ⚫In Java, we use the reserved word extends to establish an inheritance relationship class Animal { // class contents int weight; public void int getWeight() {…} } class Bird extends Animal { // class contents
Defining Methods in the Child Class: Overriding by Replacement ⚫ A child class can override the definition of an inherited method in favorof its own ⚫ that is, a child can redefine a method that it inherits from its parent ⚫ the new method must have the same signature as the parent's method, but can have different code in the body ⚫ In java, all methods except of constructorsoverridethe methods of their ancestorclass by replacement. E.g.: ⚫ the Animal class has method eat() ⚫ the Bird class has method eat() and Bird extends Animal ⚫ variable b is of class Bird, i.e. Bird b = … ⚫ b.eat() simply invokes the eat() method of the Bird class ⚫ If a method is declared with the final modifier, it cannot be overridden
Forms of Inheritance Inheritance is used in a variety of way and for a variety of different purposes . • Inheritance for Specialization • Inheritance for Specification • Inheritance for Construction • Inheritance for Extension • Inheritance for Limitation • Inheritance for Combination One or many of these forms may occur in a single case.
Forms of Inheritance (- Inheritance for Specialization -) Most commonly used inheritance and sub classification is for specialization. Always creates a subtype, and the principles of substitutability is explicitly upheld. It is the most ideal form of inheritance. An example of subclassification for specialization is; public class PinBallGame extends Frame { // body of class }
Specialization ⚫ By far the most common form of inheritance is for specialization. ⚫ Child class is a specialized form of parent class ⚫ Principle of substitutability holds ⚫ A good example is the Java hierarchy of Graphical components in the AWT: • Component ⚫ Label ⚫ Button ⚫ TextComponent ⚫ TextArea ⚫ TextField ⚫ CheckBox ⚫ ScrollBar
Forms of Inheritance (- Inheritance for Specification -) This is another most common use of inheritance. Two different mechanisms are provided by Java, interface and abstract, to make use of subclassification for specification. Subtype is formed and substitutability is explicitly upheld. Mostly, not used for refinement of its parent class, but instead is used for definitions of the properties provided by its parent. class FireButtonListener implements ActionListener { // body of class } class B extends A { // class A is defined as abstract specification class }
Specification ⚫The next most common form of inheritance involves specification. The parent class specifies some behavior, but does not implement the behavior ⚫ Child class implements the behavior ⚫ Similar to Java interface or abstract class ⚫ When parent class does not implement actual behavior but merely defines the behavior that will be implemented in child behavior, but classes ⚫ Example, Java 1.1 Event Listeners: ActionListener, MouseListener, and so on specify must be subclassed.
Forms of Inheritance (- Inheritance for Construction -) Child class inherits most of its functionality from parent, but may change the name or parameters of methods inherited from parent class to form its interface. This type of inheritance is also widely used for code reuse purposes. It simplifies the construction of newly formed abstraction but is not a form of subtype, and often violates substitutability. Example is Stack class defined in Java libraries.
Construction ⚫The parent class is used only for its behavior, the child class has no is-a relationship to the parent. ⚫Child modify the arguments or names of methods ⚫ ⚫An example might be subclassing the idea of a Set from an existing List class. ⚫Child class is not a more specialized form of parent class; no substitutability
Forms of Inheritance (- Inheritance for Extension -) Subclassification for extension occurs when a child class only adds new behavior to the parent class and does not modify or alter any of the inherited attributes. Such subclasses are always subtypes, and substitutability can be used. Example of this type of inheritance is done in the definition of the class Properties which is an extension of the class HashTable.
Generalization or Extension ⚫The child class generalizes or extends the parent class by providing more functionality ⚫ In some sense, opposite of subclassing for specialization ⚫The child doesn't change anything inherited from the parent, it simply adds new features ⚫ Often used when we cannot modify existing base parent class ⚫Example, ColoredWindow inheriting from Window ⚫ Add additional data fields ⚫ Override window display methods
Forms of Inheritance (- Inheritance for Limitation -) Subclassification for limitation occurs when the behavior of the subclass is smaller or more restrictive that the behavior of its parent class. Like subclassification for extension, this form of inheritance occurs most frequently when a programmer is building on a base of existing classes. Is not a subtype, and substitutability is not proper.
Limitation ⚫The child class limits some of the behavior of the parent class. ⚫Example, you have an existing List data type, and you want a Stack ⚫Inherit from List, but override the methods that allow access to elements other than top so as to produce errors.
Forms of Inheritance (- Inheritance for Combination -) This types of inheritance is known as multiple inheritance in Object Oriented Programming. Although the Java does not permit a subclass to be formed be inheritance from more than one parent class, several approximations to the concept are possible. Example of this type is Hole class defined as; class Hole extends Ball implements PinBallTarget{ // body of class }
Combimnation ⚫Two or more classes that seem to be related, but its not clear who should be the parent and who should be the child. ⚫Example: Mouse and TouchPad and JoyStick ⚫Better solution, abstract out common parts to new parent class, and use subclassing for specialization.
Summary of Forms of Inheritance • Specialization. The child class is a special case of the parent class; in other words, the child class is a subtype of the parent class. • Specification. The parent class defines behavior that is implemented in the child class but not in the parent class. • Construction. The child class makes use of the behavior provided by the parent class, but is not a subtype of the parent class. • Generalization. The child class modifies or overrides some of the methods of the parent class. • Extension. The child class adds new functionality to the parent class, but does not change any inherited behavior. • Limitation. The child class restricts the use of some of the behavior inherited from the parent class. • Variance. The child class and parent class are variants of each other, and the class- subclass relationship is arbitrary. • Combination. The child class inherits features from more than one parent class. This is multiple inheritance and will be the subject of a later chapter.
The Benefits of Inheritance ⚫Software Reusability (among projects) ⚫Increased Reliability (resulting from reuse and sharing of well-tested code) ⚫Code Sharing (within a project) ⚫Consistency of Interface (among related objects) ⚫Software Components ⚫Rapid Prototyping (quickly assemble from pre- existing components) ⚫Polymorphism and Frameworks (high-level reusable components)
The Costs of Inheritance ⚫Execution Speed ⚫Program Size ⚫Message-Passing Overhead ⚫Program Complexity (in overuse of inheritance)
Types of inheritance  Acquiring the properties of an existing Object into newly creating Object to overcome the re-declaration of properties in deferent classes.  These are 3 types: 1.Simple Inheritance SUPE R SUB SUPE R SUB 1 SUB 2 extend s extend s
2. Multi Level Inheritanc e 3. Multiple Inheritanc e SUPE R SUB SUB SUB SUPER 1 SUPER 2 extend s extend s implemen t s SUB SUPER 1 SUPER 2 implemen t s SUB extend s
Member access rules ⚫Visibility modifiers determine which class members are accessible and which do not ⚫Members (variables and methods) declared with public visibility are accessible, and those with private visibility are not ⚫Problem: How to make class/instance variables visible only to its subclasses? ⚫Solution: Java provides a third visibility modifier that helps in inheritance situations: protected
Modifiers and Inheritance (cont.) Visibility Modifiers for class/interface: public : can be accessed from outside the class definition. protected : can be accessed only within the class definition in which it appears, within other classess in the same package, or within the definition of subclassess. private : can be accessed only within the class definition in which it appears. default-access (if omitted) features accessible from inside the current Java package
The protected Modifier ⚫ The protected visibility modifier allows a member of a base class to be accessed in the child ⚫ protected visibility provides more encapsulation than public does ⚫ protected visibility is not as tightly encapsulated as private visibility Book protected int pages + getPages() : int + setPages(): void Dictionary + getDefinitions() : int + setDefinitions(): void + computeRatios() : double
“super” uses  ‘super’ is a keyword used to refer to hidden variables of super class from sub class.  super.a=a;  It is used to call a constructor of super class from constructor of sub class which should be first statement.  super(a,b);  It is used to call a super class method from sub class method to avoid redundancy of code  super.addNumbers(a, b);
Super and Hiding ⚫Why is super needed to access super-class members? ⚫When a sub-class declares the variables or methods with the same names and types as its super-class: class A { int i = 1; } class B extends A { int i = 2; System.out.println (“i is “ + i); } ⚫The re-declared variables/methods hide those of the super-class.
Example: Super and Hiding class A { int i; } class B extend s A { int i; B(int a, int b) { super.i = a; i = b; } void
Example: Super and Hiding ⚫Although the i variable in B hides the i variable in A, super allows access to the hidden variable of the super-class: class UseSuper { public static void main(String args[]) { B subOb = new B(1, 2); subOb.show(); } }
Using final with inheritance ⚫final keyword is used declare constants which can not change its value of definition. ⚫final Variables can not change its value. ⚫final Methods can not be Overridden or Over Loaded ⚫final Classes can not be extended or inherited
Preventing Overriding with final ⚫A method declared final cannot be overridden in any sub-class: class A { final void meth() { System.out.println("This is a final method."); } } This class declaration is illegal: class B extends A { void meth() { System.out.println("Illega
Preventing Inheritance with final ⚫A class declared final cannot be inherited – has no sub- classes. final class A { … } ⚫This class declaration is considered illegal: class B extends A { … } ⚫Declaring a class final implicitly declares all its methods final. ⚫It is illegal to declare a class as both abstract and final.
Polymorphism one of three pillars of object- ⚫Polymorphism is orientation. ⚫Polymorphism: many different (poly) forms of objects that share a common interface respond differently when a method of that interface is invoked: 1) a super-class defines the common interface 2)sub-classes have to follow this interface (inheritance), but are also permitted to provide their own implementations (overriding) ⚫A sub-class provides a specialized behaviors relying on the common elements defined by its super-class.
Polymorphism ⚫ A polymorphic reference can refer to different types of objects at different times ⚫ In java every reference can be polymorphicexcept of references to base types and final classes. ⚫ It is the type of the object being referenced, not the reference type, that determineswhich method is invoked ⚫ Polymorphicreferences are therefore resolved at run- time, not during compilation; this is called dynamic binding
Method Overriding ⚫When a method of a sub-class has the same name and type as a method of the super-class, we say that this method is overridden. ⚫When an overridden method is called from within the sub-class: 1)it will always refer to the sub-class method 2) super-class method is hidden
Example: Hiding with Overriding 1 class A { int i, j; A(int a, int b) { i = a; j = b; } void show() { System.out.p rintln("i and j: " + i + " " + j); }
Example: Hiding with Overriding 2 class B extends A { int k; B(int a, int b, int c) { super(a, b); k = c; } void show() { System.out.println("k: " + k); } }
Example: Hiding with Overriding 3 ⚫When show() is invoked on an object of type B, the version of show() defined in B is used: class Override { public static void main(String args[]) { B subOb = new B(1, 2, 3); subOb.show(); } } ⚫The version of show() in A is hidden through overriding.
Overloading vs. Overriding ⚫Overloading deals with multiple methods in the same class with the same name but different signatures ⚫Overriding deals with two methods, one in a parent class and one in a child class, that have the same signature ⚫Overloading lets you define a similar operation in different ways for different data o Overriding lets you define a similar operation in different ways for different object types
Abstract Classes ⚫Java allows abstract classes ⚫ use the modifier abstract on a class header to declarean abstract class abstract class Vehicle { … } ⚫An abstract class is a placeholder in a class hierarchy that represents a generic concept Vehicle Car Boat Plane
Abstract Class: Example  An abstract class often contains abstract methods, though it doesn’t have to  Abstract methods consistof only methods declarations, without any method body public abstract class Vehicle { String name; public String getName() { return name; } method body abstract public void move(); no body! }
Abstract Classes ⚫An abstract class often contains abstract methods, though it doesn’t have to ⚫ Abstract methods consistof only methods declarations, without any method body ⚫The non-abstract child of an abstract class must override the abstract methods of the parent ⚫An abstract class cannot be instantiated ⚫The use of abstract classes is a design decision; it helps us establish common elements in a class that is too general to instantiate
Abstract Method ⚫ Inheritanceallows a sub-class to override the methods of its super-class. ⚫ A super-class may altogether leave the implementation details of a method and declare such a method abstract: ⚫ abstract type name(parameter-list); ⚫ Two kinds of methods: 1)concrete– may be overridden by sub-classes 2) abstract – must be overridden by sub-classes ⚫ It is illegal to define abstract constructorsor static methods.
Defining a Package A package is both a naming and a visibility control mechanism: 1) divides the name space into disjoint subsets It is possible to define classes within a package that are not accessible by code outside the package. 2) controls the visibility of classes and their members It is possible to define class members that are only exposed to other members of the same package. Same-package classes may have an intimate knowledge of each other, but not expose that knowledge to other packages
Creating a Package ⚫A package statement inserted as the first line of the source file: package myPackage; class MyClass1 { … } class MyClass2 { … } ⚫means that all classes in this file belong to the myPackage package. ⚫ The package statement creates a name space
Multiple Source Files ⚫ Other files may include the same package instruction: 1. package myPackage; class MyClass1 { … } class MyClass2 { … } 2. package myPackage; class MyClass3{ … } ⚫ A package may be distributed through several source files
Packages and Directories ⚫Java uses file system directories to store packages. ⚫Consider the Java source file: package myPackage; class MyClass1 { … } class MyClass2 { … } ⚫The byte code files MyClass1.class and MyClass2.class must be stored in a directory
Package Hierarchy separateeach package name ⚫To create a package hierarchy, with a dot: package myPackage1.myPackage2.myPackage3; ⚫A package hierarchy must be stored accordingly in the file system: 1)Unix myPackage1/myPackage2/myPackage3 2) Windows myPackage1myPackage2myPackage3 3) Macintosh myPackage1:myPackage2:myPackage3 ⚫You cannot rename a package without renaming its directory!
Accessing a Package ⚫As packages are stored in directories, how does the Java run-time system know where to look for packages? ⚫Two ways: defaul t 1)The current directory is the packages are stored in the current directory or start point - if sub- by setting the directories, they will be found. 2)Specify a directory path or paths CLASSPATH environment variable.
CLASSPATH Variable ⚫CLASSPATH - environment variable that points to the root directory of the system’s package hierarchy. ⚫Several root directories may be specified in CLASSPATH, ⚫e.g. the current directory and the C:rajumyJava directory: .;C:rajumyJava ⚫Java will search for the required packages by looking up subsequent directories described in the CLASSPATH variable.
Finding Packages ⚫ Consider this package statement: package myPackage; In order for a program to find myPackage, one of the following must be true: 1)program is executed from the directory immediately above myPackage(the parentof myPackagedirectory) 2) CLASSPATH must be set to include the path to myPackage
Example: Package package MyPack; class Balance { String name; double bal; Balance(String n, double b) { name = n; bal = b; } void show() { if (bal<0) System.out.print("-->> "); System.out.println(name + ": $" + bal); } }
Example: Package class AccountBalance { public static void main(String args[]) { Balance current[] = new Balance[3]; current[0] = new Balance("K. J. Fielding", 123.23); current[1] = new Balance("Will Tell", 157.02); current[2] = new Balance("Tom Jackson", -12.33); for (int i=0; i<3; i++) current[i].show(); } }
Example: Package ⚫Save, compile and execute: 1)call the file AccountBalance.java 2) save the file in the directory MyPack 3) compile; AccountBalance.class should be also in MyPack 4)set access to MyPack in CLASSPATH variable, or make the parent of MyPack your current directory 5) run: java MyPack.AccountBalance ⚫Make sure to use the package-qualified class name.
Importing of Packages ⚫Since classes within packages must be fully-qualified with their package names, it would be tedious to always type long dot-separated names. ⚫The import statement allows to use classes or whole packages directly. ⚫Importing of a concrete class: import myPackage1.myPackage2.myClass; ⚫Importing of all classes within a package: import myPackage1.myPackage2.*;
Import Statement ⚫The import statement occurs immediately after the package statement and before the class statement: package myPackage; ⚫import otherPackage1;otherPackage2.otherClass; class myClass { … } ⚫The Java system accepts this import statement by default: import java.lang.*; ⚫This package includes the basic language functions.
Example: Packages 1 ⚫ A package MyPack with one public class Balance. The class has two same-package variables: public constructor and a public show method. package MyPack; public class Balance { String name; double bal; public Balance(String n, double b) { name = n; bal = b; } public void show() { if (bal<0) System.out.print("-- >> "); System.out.println(n ame + ": $" + bal);
Example: Packages 2 The importing code has access to the public class Balance of the MyPack package and its two public members: import MyPack.*; class TestBalance { public static void main(String args[]) { Balance test = new Balance("J. J. Jaspers", 99.88); test.show();
Java Source File Finally, a Java source file consists of: 1) a single package instruction (optional) 2) several import statements (optional) 3)a single public class declaration (required) 4) several classes private to the package (optional) At the minimum, a file contains a single public class declaration.
Differences between classes and interfaces ⚫ Interfaces are syntactically similar to classes, but they lack instance variables, and their methods are declared without any body. ⚫ One class can implement any number of interfaces. ⚫ Interfaces are designed to support dynamic method resolution at run time. ⚫ Interface is little bit like a class...but interface is lack in instance variables....that's u can't create object for it..... ⚫ Interfaces are developed to support multiple inheritance... ⚫ The methods present in interfaces r pure abstract.. ⚫ The access specifiers public,private,protected are possible with classes, but the interface uses only one spcifier public..... ⚫ interfaces contains only the method declarations.... no definitions....... ⚫ A interface defines, which method a class has to implement. This is way - if you want to call a method defined by an interface - you don't need to know the exact class type of an object, you only need to know that it implements a specific interface.
Defining an interface ⚫ Using interface, we specify what a class must do, but not how it does this. ⚫ An interfaceis syntacticallysimilar to a class, but it lacks instance variables and its methods are declared without any body. ⚫ An interface is defined with an interface keyword. keywor d paren t  An interface declaration consists of modifiers, the interface,the interfacename, a comma-separated list of interfaces (if any), and the interface body. For example: public interface GroupedInterface extends Interface1, Interface2, Interface3 { // constant declarations double E = 2.718282; // base of natural logarithms // //method signatures void doSomething (int i, double x); int doSomethingElse(String s); }  The public access specifier indicates that the interface can be used by any class in any package. If you do not specify that the interface is public, your interface will be accessible only to classes defined in the same package as the interface.  An interface can extend other interfaces, just as a class can extend or subclass another class. However, whereas a class can extend only one other class, an interfacecan extend any number of interfaces. The interface declaration includes a comma-separated list of all the interfaces that it extends
Implementing interface General format: access interface name { type method-name1(parameter-list); type method-name2(parameter-list); … type var-name1 = value1; type var-nameM = valueM; … }
⚫Two types of access: 1)public – interface may be used anywhere in a program 2)default – interface may be used in the current package only ⚫Interface methods have no bodies – they end with the semicolon after the parameter list. ⚫They are essentially abstract methods. ⚫An interface may include variables, but they must be final, static and initialized with a constant value. ⚫In a public interface, all members are implicitly
Interface Implementation ⚫A class implements an interface if it provides a complete set of methods defined by this interface. 1) any number of classes may implement an interface of its 2) one class may implement any number of interfaces ⚫Each class is free to determine the details implementation. ⚫Implementation relationis writtenwith the implements keyword.
Implementation Format ⚫General format of a class that includes the implements clause: ⚫Syntax: access class name extends super-class implements interface1, interface2, …, interfaceN { … } ⚫ Access is public or default.
Implementation Comments ⚫If a class implements several interfaces, they are separated with a comma. ⚫If a class implements two interfaces that declare the same method, the same method will be used by the clients of either interface. ⚫The methods that implement an interface must be declared public. ⚫The type signature of the implementing method must match exactly the type signature specified in the interface definition.
Example: Interface Declaration of the Callback interface: interface Callback { void callback(int param); } Client class implements the Callback interface: class Client implements Callback { public void callback(int p) { System.out.println("callback called with " + p); } }
More Methods in Implementation ⚫ An implementing class may also declare its own methods: class Client implements Callback { public void callback(int p) { System.out.println("callback called with " + p); } void nonIfaceMeth() { System.out.println("Classes that implement “ + “interfaces may also define ” + “other members, too."); }
Applying interfaces A Java interface declares a set of method signatures i.e., says what behaviorexists Does not say how the behavior is implemented i.e., does not give code for the methods Does not describe any state (but may include “final” constants) A concrete class that implements an interface Contains “implements InterfaceName” in the class declaration Must provide implementations (either directly or inherited from a superclass) of all methods declared in the interface or all interface An abstract class can also implementan interface Can optionally have implementationsof some methods
⚫Interfaces and Extends both describe an “is- a” relation. ⚫If B implements interface A, then B inherits the (abstract) method signatures in A ⚫If B extends class A, then B inherits everything in A. ⚫which can include method code and instance variables as well as abstract method signatures. ⚫Inheritance” is sometimes used to talk about thesuperclass / subclass “extends” relation only
Variables in interface ⚫Variables declared in an interface must be constants. ⚫A technique to import shared constants into multiple classes: 1)declare an interface with variables initialized to the desired values 2)include that interface in a class through implementation. ⚫As no methods are included in the interface, the class does not implement. ⚫anything except importing the variables as
Example: Interface Variables 1 An interface with constant values: import java.util.Random; interface SharedConstants { int NO = 0; int YES = 1; int MAYBE = 2; int LATER = 3; int SOON = 4; int NEVER = 5; }
⚫ Question implements SharedConstants, including all its constants. ⚫ Which constant is returned depends on the generated random number: class Question implements SharedConstants { Random rand = new Random(); int ask() { int prob = (int) (100 * rand.nextDouble()); if (prob < 30) return NO; else if (prob < 60) return YES; else if (prob < 75) return LATER; else if (prob < 98) return SOON; else return NEVER; } }
⚫ AskMe includes all shared constants in the same way, using them to display the result, depending on the value received: class AskMe implements SharedConstants { static void answer(int result) { switch(result) { case NO: System.out.println("No"); break; case YES: System.out.println("Yes"); break; case MAYBE: System.out.println("Maybe"); break; case LATER: System.out.println("Later"); break; case SOON: System.out.println("Soon"); break; case NEVER: System.out.println("Never"); break;
Example: Interface Variables 4 ⚫The testing function relies on the fact that both ask and answer methods. ⚫defined in different classes, rely on the same constants: public static void main(String args[]) { Question q = new Question(); answer(q.ask()); answer(q.ask()); answer(q.ask()); answer(q.ask()); } }
Extending interfaces ⚫One interface may inherit another interface. ⚫The inheritance syntax is the same for classes and interfaces. interface MyInterface1 { void myMethod1(…) ; } interface MyInterface2 extends MyInterface1 { void myMethod2(…) ; } ⚫When a class implements an interface that inherits another interface, it must provide implementations for all methods defined within the interface inheritance chain.
Example: Interface Inheritance 1 ⚫Consider interfaces A and B. interface A { void meth1(); void meth2(); } B extends A: interface B extends A { void meth3(); }
Example: Interface Inheritance 2 ⚫MyClass must implement all of A and B methods: class MyClass implements B { public void meth1() { System.out.println("Implementmeth1()."); } public void meth2() { System.out.println("Implement meth2()."); } public void meth3() { System.out.println("Implementmeth3()."); } }
Example: Interface Inheritance 3 ⚫Create a new MyClass object, then invoke all interface methods on it: class IFExtend { public static void main(String arg[]) { MyClassob = new MyClass(); ob.meth1(); ob.meth2(); ob.meth3(); } }

METHOD OVERLOADING AND INHERITANCE INTERFACE

  • 1.
    20IT301 JAVA PROGRAMMING By M.Mohanraj AssistantProfessor Department of Artificial Intelligence and Data Science Kongunadu College of Engineering
  • 2.
  • 3.
    TOPICS 1 2 3 4 5 6 7 1 Hierarchical abstractions Baseclass object. subclass, subtype, substitutability. forms of inheritance- specialization, construction, extension, limitation, combination. Benefits of inheritance, costs of inheritance. 2 Memberaccess rules, super uses, using final with inheritance. polymorphism- method overriding, abstract classes. Defining, Creating and Accessing a Package Importing packages 3 Differences between classesand interfaces 4 Defining an interface 5 Implementing interface 6 Applying interfaces 7 variables in interface and extending interfaces
  • 4.
    10 Inheritance ⚫Methodsallows a softwaredeveloper to reuse a sequence of statements ⚫Inheritance allows a software developer to reuse classes by deriving a new class from an existing one ⚫The existing class is called the parent class, or superclass, or base class ⚫The derived class is called the child class or subclass. ⚫As the name implies, the child inherits characteristics of the parent ⚫That is, the child class inherits the methods and data defined for the parent class
  • 5.
    10 I⚫nInhheerirtaintcaenrelcateionship s are oftenshown graphically in a class diagram, with the arrow pointing to the parent class Inheritance should create an is-a relationship, meaning the child is a more specific version of the parent Animal weight : int + getWeight() : int Bird + fly() : void
  • 6.
    10 Deriving Subclasses ⚫In Java,we use the reserved word extends to establish an inheritance relationship class Animal { // class contents int weight; public void int getWeight() {…} } class Bird extends Animal { // class contents public void fly() {…}; }
  • 7.
    11 Class Hierarchy ⚫A childclass of one parent can be the parent of another child, forming class hierarchies Animal Reptile Bird Mammal Snak e Lizar d Hors e Ba t Parrot  At the top of the hierarchy there’s a default class
  • 8.
    1 Class Hierarchy ⚫Good classdesign puts all common features as high in the hierarchy as reasonable ⚫inheritance is transitive ⚫ An instance of class Parrot is also an instance of Bird, an instance of Animal, …, and an instance of class Object ⚫The class hierarchy determines how methods are executed: ⚫ Previously, we took the simplified view that when variable v is an instance of class C, then a procedure call v.proc1() invokes the method proc1() defined in class C ⚫ However, if C is a child of some superclass C’ (and hence v is both an instance of C and an instance of C’), the picture becomes more complex, because methods of class C can override the methods of class C’ (next two slides).
  • 9.
    11 Defining Methods inthe Child Class: Overriding by Replacement ⚫ A child class can override the definition of an inherited method in favorof its own ⚫ that is, a child can redefine a method that it inherits from its parent ⚫ the new method must have the same signature as the parent's method, but can have different code in the body ⚫ In java, all methods except of constructors override the methods of their ancestor class by replacement. E.g.: ⚫ the Animal class has method eat() ⚫ the Bird class has method eat() and Bird extends Animal ⚫ variable b is of class Bird, i.e. Bird b = … ⚫ b.eat() simply invokes the eat() method of the Bird class ⚫ If a method is declared with the final modifier, it cannot be overridden
  • 10.
    Defining Methods inthe Child Class: Overriding by Refinement ⚫ Constructors in a subclass override the definition of an inherited constructor method by refining them (instead of replacing them) - Assume class Animal has constructors Animal(), Animal(int weight), Animal(int weight, int livespan) - Assume class Bird which extends Animal has constructors Bird(), Bird(int weight), Bird(int weight, int livespan) - Let’s say we createa Bird object, e.g. Bird b = Bird(5) - This will invoke first the constructorof the Animal (the superclass of Bird) and then theconstructorof the Bird ⚫ This is called constructor chaining: If class C0 extends C1 and C1 extends C2 and … Cn-1 extends Cn = Object then when creating an instance of object C0 first constructor of Cn is invoked, then constructors of Cn-1, …, C2, C1, and finally the constructorof C - The constructors (in each case) arechosen by their signature, e.g. (), (int), etc… - If no constructor with matching signature is found in any of the class Ci for i>0 then the default constructor is executed for that class - If no constructor with matching signature is found in the class C0 then this
  • 11.
    11 Recap: Class Hierarchy ⚫In Java, a class can extend a single otherclass (If none is stated then it implicitly extends an Object class) Animal Reptile Bird Mammal Snake Lizard Hors e Ba t Parrot  Imagine what would happen to method handling rules if every class could extend two others…
  • 12.
    Hierarchical Abstraction ⚫An essentialelement of object-oriented programming is abstraction. ⚫Humans manage complexity through abstraction. For example, people do not think of a car as a set of tens of thousands of individual parts. They think of it as a well- defined object with its own unique behavior. ⚫This abstraction allows people to use a car without being overwhelmed by the complexity of the parts that form the car. They can ignore the details of how the engine, transmission, and braking systems work. ⚫Instead they are free to utilize the object as a whole.
  • 13.
    Class Hierarchy ⚫A childclass of one parent can be the parent of another child, forming class hierarchies Animal Reptile Bird Mammal Snake Lizard Horse Bat Parrot  At the top of the hierarchy there’s a default class called Object.
  • 14.
    Class Hierarchy ⚫Good classdesign puts all common features as high in the hierarchy as reasonable ⚫The class hierarchy determines how methods are executed ⚫inheritance is transitive ⚫An instance of class Parrot is also an instance of Bird, an instance of Animal, …, and an instance of class Object
  • 15.
    Base Class Object ⚫InJava, all classes use inheritance. ⚫If no parent class is specified explicitly, the base class Object is implicitly inherited. ⚫All classes defined in Java, is a child of Object class, which provides minimal functionality guaranteed to e common to all objects. ⚫Methods defined in Object class are; 1. equals(Object obj): Determine whether the argument object is the same as the receiver. 2. getClass(): Returns the class of the receiver, an object of type Class. 3. hashCode(): Returns a hash value for this object. Should be overridden when the equals method is changed. 4. toString(): Converts object into a string value. This method is also often overridden.
  • 16.
    Base class 1)a classobtains variables and methods from another class 2) the former is called subclass, the latter super-class (Base class) 3)a sub-class provides a specialized behavior with respect to its super-class 4)inheritance facilitates code reuse and avoids duplication of data Extends  Is a keyword used to inherit a class from another class Allows to extend f rom only one class  class One { int a=5; } class Two extends One { int b=10; }
  • 17.
    Subclass, Subtype andSubstitutability ⚫A subtype is a class that satisfies the principle of substitutability. ⚫A subclass is something constructed using inheritance, whether or not it satisfies the principle of substitutability. ⚫The two concepts are independent. Not all subclasses are subtypes, and (at least in some languages) you can construct subtypes that are not subclasses. ⚫Substitutability is fundamental to many of the powerful software development techniques in OOP. ⚫The idea is that, declared a variable in one type may hold the value of different type. ⚫Substitutability can occur through use of inheritance, whether using extends, or using implements keywords.
  • 18.
    Subclass, Subtype, andSubstitutability When new classes are constructed using inheritance, the argument used to justify the validity of substitutability is as follows; •Instances of the subclass must possess all data fields associated with its parent class. • Instances of the subclass must implement, through inheritance at least, all functionality defined for parent class. (Defining new methods is not important for the argument.) • Thus, an instance of a child class can mimic the behavior of the parent class and should be indistinguishable from an instance of parent class if substituted in a similar situation.
  • 19.
    Subclass, Subtype, and Substitutability Theterm subtype is used to describe the relationship between types that explicitly recognizes the principle of substitution. A type B is considered to be a subtype of A if an instances of B can legally be assigned to a variable declared as of type A. The term subclass refers to inheritance mechanism made by extends keyword. Not all subclasses are subtypes. Subtypes can also be formed using interface, linking types that have no inheritance relationship.
  • 20.
    Subclass ⚫ Methods allowsto reuse a sequenceof statements ⚫ Inheritance allows to reuse classes by deriving a new class from an existing one ⚫ The existing class is called the parent class, or superclass, or base class ⚫ The derived class is called the child class or subclass. ⚫ As the name implies, the child inherits characteristics of the parent(i.e the child class inherits the methods and data defined for the parent class
  • 21.
    Subtype ⚫Inheritance relationships areoften shown graphically in a class diagram, with the arrow pointing to the parent class Animal weight : int + getWeight() : int Bird + fly() : void
  • 22.
    Substitutability (Deriving Subclasses) ⚫InJava, we use the reserved word extends to establish an inheritance relationship class Animal { // class contents int weight; public void int getWeight() {…} } class Bird extends Animal { // class contents
  • 23.
    Defining Methods inthe Child Class: Overriding by Replacement ⚫ A child class can override the definition of an inherited method in favorof its own ⚫ that is, a child can redefine a method that it inherits from its parent ⚫ the new method must have the same signature as the parent's method, but can have different code in the body ⚫ In java, all methods except of constructorsoverridethe methods of their ancestorclass by replacement. E.g.: ⚫ the Animal class has method eat() ⚫ the Bird class has method eat() and Bird extends Animal ⚫ variable b is of class Bird, i.e. Bird b = … ⚫ b.eat() simply invokes the eat() method of the Bird class ⚫ If a method is declared with the final modifier, it cannot be overridden
  • 24.
    Forms of Inheritance Inheritanceis used in a variety of way and for a variety of different purposes . • Inheritance for Specialization • Inheritance for Specification • Inheritance for Construction • Inheritance for Extension • Inheritance for Limitation • Inheritance for Combination One or many of these forms may occur in a single case.
  • 25.
    Forms of Inheritance (-Inheritance for Specialization -) Most commonly used inheritance and sub classification is for specialization. Always creates a subtype, and the principles of substitutability is explicitly upheld. It is the most ideal form of inheritance. An example of subclassification for specialization is; public class PinBallGame extends Frame { // body of class }
  • 26.
    Specialization ⚫ By farthe most common form of inheritance is for specialization. ⚫ Child class is a specialized form of parent class ⚫ Principle of substitutability holds ⚫ A good example is the Java hierarchy of Graphical components in the AWT: • Component ⚫ Label ⚫ Button ⚫ TextComponent ⚫ TextArea ⚫ TextField ⚫ CheckBox ⚫ ScrollBar
  • 27.
    Forms of Inheritance (-Inheritance for Specification -) This is another most common use of inheritance. Two different mechanisms are provided by Java, interface and abstract, to make use of subclassification for specification. Subtype is formed and substitutability is explicitly upheld. Mostly, not used for refinement of its parent class, but instead is used for definitions of the properties provided by its parent. class FireButtonListener implements ActionListener { // body of class } class B extends A { // class A is defined as abstract specification class }
  • 28.
    Specification ⚫The next mostcommon form of inheritance involves specification. The parent class specifies some behavior, but does not implement the behavior ⚫ Child class implements the behavior ⚫ Similar to Java interface or abstract class ⚫ When parent class does not implement actual behavior but merely defines the behavior that will be implemented in child behavior, but classes ⚫ Example, Java 1.1 Event Listeners: ActionListener, MouseListener, and so on specify must be subclassed.
  • 29.
    Forms of Inheritance (-Inheritance for Construction -) Child class inherits most of its functionality from parent, but may change the name or parameters of methods inherited from parent class to form its interface. This type of inheritance is also widely used for code reuse purposes. It simplifies the construction of newly formed abstraction but is not a form of subtype, and often violates substitutability. Example is Stack class defined in Java libraries.
  • 30.
    Construction ⚫The parent classis used only for its behavior, the child class has no is-a relationship to the parent. ⚫Child modify the arguments or names of methods ⚫ ⚫An example might be subclassing the idea of a Set from an existing List class. ⚫Child class is not a more specialized form of parent class; no substitutability
  • 31.
    Forms of Inheritance (-Inheritance for Extension -) Subclassification for extension occurs when a child class only adds new behavior to the parent class and does not modify or alter any of the inherited attributes. Such subclasses are always subtypes, and substitutability can be used. Example of this type of inheritance is done in the definition of the class Properties which is an extension of the class HashTable.
  • 32.
    Generalization or Extension ⚫Thechild class generalizes or extends the parent class by providing more functionality ⚫ In some sense, opposite of subclassing for specialization ⚫The child doesn't change anything inherited from the parent, it simply adds new features ⚫ Often used when we cannot modify existing base parent class ⚫Example, ColoredWindow inheriting from Window ⚫ Add additional data fields ⚫ Override window display methods
  • 33.
    Forms of Inheritance (-Inheritance for Limitation -) Subclassification for limitation occurs when the behavior of the subclass is smaller or more restrictive that the behavior of its parent class. Like subclassification for extension, this form of inheritance occurs most frequently when a programmer is building on a base of existing classes. Is not a subtype, and substitutability is not proper.
  • 34.
    Limitation ⚫The child classlimits some of the behavior of the parent class. ⚫Example, you have an existing List data type, and you want a Stack ⚫Inherit from List, but override the methods that allow access to elements other than top so as to produce errors.
  • 35.
    Forms of Inheritance (-Inheritance for Combination -) This types of inheritance is known as multiple inheritance in Object Oriented Programming. Although the Java does not permit a subclass to be formed be inheritance from more than one parent class, several approximations to the concept are possible. Example of this type is Hole class defined as; class Hole extends Ball implements PinBallTarget{ // body of class }
  • 36.
    Combimnation ⚫Two or moreclasses that seem to be related, but its not clear who should be the parent and who should be the child. ⚫Example: Mouse and TouchPad and JoyStick ⚫Better solution, abstract out common parts to new parent class, and use subclassing for specialization.
  • 37.
    Summary of Formsof Inheritance • Specialization. The child class is a special case of the parent class; in other words, the child class is a subtype of the parent class. • Specification. The parent class defines behavior that is implemented in the child class but not in the parent class. • Construction. The child class makes use of the behavior provided by the parent class, but is not a subtype of the parent class. • Generalization. The child class modifies or overrides some of the methods of the parent class. • Extension. The child class adds new functionality to the parent class, but does not change any inherited behavior. • Limitation. The child class restricts the use of some of the behavior inherited from the parent class. • Variance. The child class and parent class are variants of each other, and the class- subclass relationship is arbitrary. • Combination. The child class inherits features from more than one parent class. This is multiple inheritance and will be the subject of a later chapter.
  • 38.
    The Benefits ofInheritance ⚫Software Reusability (among projects) ⚫Increased Reliability (resulting from reuse and sharing of well-tested code) ⚫Code Sharing (within a project) ⚫Consistency of Interface (among related objects) ⚫Software Components ⚫Rapid Prototyping (quickly assemble from pre- existing components) ⚫Polymorphism and Frameworks (high-level reusable components)
  • 39.
    The Costs ofInheritance ⚫Execution Speed ⚫Program Size ⚫Message-Passing Overhead ⚫Program Complexity (in overuse of inheritance)
  • 40.
    Types of inheritance  Acquiringthe properties of an existing Object into newly creating Object to overcome the re-declaration of properties in deferent classes.  These are 3 types: 1.Simple Inheritance SUPE R SUB SUPE R SUB 1 SUB 2 extend s extend s
  • 41.
  • 42.
    Member access rules ⚫Visibilitymodifiers determine which class members are accessible and which do not ⚫Members (variables and methods) declared with public visibility are accessible, and those with private visibility are not ⚫Problem: How to make class/instance variables visible only to its subclasses? ⚫Solution: Java provides a third visibility modifier that helps in inheritance situations: protected
  • 43.
    Modifiers and Inheritance (cont.) VisibilityModifiers for class/interface: public : can be accessed from outside the class definition. protected : can be accessed only within the class definition in which it appears, within other classess in the same package, or within the definition of subclassess. private : can be accessed only within the class definition in which it appears. default-access (if omitted) features accessible from inside the current Java package
  • 44.
    The protected Modifier ⚫ Theprotected visibility modifier allows a member of a base class to be accessed in the child ⚫ protected visibility provides more encapsulation than public does ⚫ protected visibility is not as tightly encapsulated as private visibility Book protected int pages + getPages() : int + setPages(): void Dictionary + getDefinitions() : int + setDefinitions(): void + computeRatios() : double
  • 45.
    “super” uses  ‘super’is a keyword used to refer to hidden variables of super class from sub class.  super.a=a;  It is used to call a constructor of super class from constructor of sub class which should be first statement.  super(a,b);  It is used to call a super class method from sub class method to avoid redundancy of code  super.addNumbers(a, b);
  • 46.
    Super and Hiding ⚫Whyis super needed to access super-class members? ⚫When a sub-class declares the variables or methods with the same names and types as its super-class: class A { int i = 1; } class B extends A { int i = 2; System.out.println (“i is “ + i); } ⚫The re-declared variables/methods hide those of the super-class.
  • 47.
    Example: Super and Hiding classA { int i; } class B extend s A { int i; B(int a, int b) { super.i = a; i = b; } void
  • 48.
    Example: Super andHiding ⚫Although the i variable in B hides the i variable in A, super allows access to the hidden variable of the super-class: class UseSuper { public static void main(String args[]) { B subOb = new B(1, 2); subOb.show(); } }
  • 49.
    Using final withinheritance ⚫final keyword is used declare constants which can not change its value of definition. ⚫final Variables can not change its value. ⚫final Methods can not be Overridden or Over Loaded ⚫final Classes can not be extended or inherited
  • 50.
    Preventing Overriding withfinal ⚫A method declared final cannot be overridden in any sub-class: class A { final void meth() { System.out.println("This is a final method."); } } This class declaration is illegal: class B extends A { void meth() { System.out.println("Illega
  • 51.
    Preventing Inheritance withfinal ⚫A class declared final cannot be inherited – has no sub- classes. final class A { … } ⚫This class declaration is considered illegal: class B extends A { … } ⚫Declaring a class final implicitly declares all its methods final. ⚫It is illegal to declare a class as both abstract and final.
  • 52.
    Polymorphism one of threepillars of object- ⚫Polymorphism is orientation. ⚫Polymorphism: many different (poly) forms of objects that share a common interface respond differently when a method of that interface is invoked: 1) a super-class defines the common interface 2)sub-classes have to follow this interface (inheritance), but are also permitted to provide their own implementations (overriding) ⚫A sub-class provides a specialized behaviors relying on the common elements defined by its super-class.
  • 53.
    Polymorphism ⚫ A polymorphicreference can refer to different types of objects at different times ⚫ In java every reference can be polymorphicexcept of references to base types and final classes. ⚫ It is the type of the object being referenced, not the reference type, that determineswhich method is invoked ⚫ Polymorphicreferences are therefore resolved at run- time, not during compilation; this is called dynamic binding
  • 54.
    Method Overriding ⚫When amethod of a sub-class has the same name and type as a method of the super-class, we say that this method is overridden. ⚫When an overridden method is called from within the sub-class: 1)it will always refer to the sub-class method 2) super-class method is hidden
  • 55.
    Example: Hiding withOverriding 1 class A { int i, j; A(int a, int b) { i = a; j = b; } void show() { System.out.p rintln("i and j: " + i + " " + j); }
  • 56.
    Example: Hiding withOverriding 2 class B extends A { int k; B(int a, int b, int c) { super(a, b); k = c; } void show() { System.out.println("k: " + k); } }
  • 57.
    Example: Hiding withOverriding 3 ⚫When show() is invoked on an object of type B, the version of show() defined in B is used: class Override { public static void main(String args[]) { B subOb = new B(1, 2, 3); subOb.show(); } } ⚫The version of show() in A is hidden through overriding.
  • 58.
    Overloading vs. Overriding ⚫Overloadingdeals with multiple methods in the same class with the same name but different signatures ⚫Overriding deals with two methods, one in a parent class and one in a child class, that have the same signature ⚫Overloading lets you define a similar operation in different ways for different data o Overriding lets you define a similar operation in different ways for different object types
  • 59.
    Abstract Classes ⚫Java allowsabstract classes ⚫ use the modifier abstract on a class header to declarean abstract class abstract class Vehicle { … } ⚫An abstract class is a placeholder in a class hierarchy that represents a generic concept Vehicle Car Boat Plane
  • 60.
    Abstract Class: Example An abstract class often contains abstract methods, though it doesn’t have to  Abstract methods consistof only methods declarations, without any method body public abstract class Vehicle { String name; public String getName() { return name; } method body abstract public void move(); no body! }
  • 61.
    Abstract Classes ⚫An abstractclass often contains abstract methods, though it doesn’t have to ⚫ Abstract methods consistof only methods declarations, without any method body ⚫The non-abstract child of an abstract class must override the abstract methods of the parent ⚫An abstract class cannot be instantiated ⚫The use of abstract classes is a design decision; it helps us establish common elements in a class that is too general to instantiate
  • 62.
    Abstract Method ⚫ Inheritanceallowsa sub-class to override the methods of its super-class. ⚫ A super-class may altogether leave the implementation details of a method and declare such a method abstract: ⚫ abstract type name(parameter-list); ⚫ Two kinds of methods: 1)concrete– may be overridden by sub-classes 2) abstract – must be overridden by sub-classes ⚫ It is illegal to define abstract constructorsor static methods.
  • 63.
    Defining a Package Apackage is both a naming and a visibility control mechanism: 1) divides the name space into disjoint subsets It is possible to define classes within a package that are not accessible by code outside the package. 2) controls the visibility of classes and their members It is possible to define class members that are only exposed to other members of the same package. Same-package classes may have an intimate knowledge of each other, but not expose that knowledge to other packages
  • 64.
    Creating a Package ⚫Apackage statement inserted as the first line of the source file: package myPackage; class MyClass1 { … } class MyClass2 { … } ⚫means that all classes in this file belong to the myPackage package. ⚫ The package statement creates a name space
  • 65.
    Multiple Source Files ⚫Other files may include the same package instruction: 1. package myPackage; class MyClass1 { … } class MyClass2 { … } 2. package myPackage; class MyClass3{ … } ⚫ A package may be distributed through several source files
  • 66.
    Packages and Directories ⚫Javauses file system directories to store packages. ⚫Consider the Java source file: package myPackage; class MyClass1 { … } class MyClass2 { … } ⚫The byte code files MyClass1.class and MyClass2.class must be stored in a directory
  • 67.
    Package Hierarchy separateeach package name ⚫Tocreate a package hierarchy, with a dot: package myPackage1.myPackage2.myPackage3; ⚫A package hierarchy must be stored accordingly in the file system: 1)Unix myPackage1/myPackage2/myPackage3 2) Windows myPackage1myPackage2myPackage3 3) Macintosh myPackage1:myPackage2:myPackage3 ⚫You cannot rename a package without renaming its directory!
  • 68.
    Accessing a Package ⚫Aspackages are stored in directories, how does the Java run-time system know where to look for packages? ⚫Two ways: defaul t 1)The current directory is the packages are stored in the current directory or start point - if sub- by setting the directories, they will be found. 2)Specify a directory path or paths CLASSPATH environment variable.
  • 69.
    CLASSPATH Variable ⚫CLASSPATH -environment variable that points to the root directory of the system’s package hierarchy. ⚫Several root directories may be specified in CLASSPATH, ⚫e.g. the current directory and the C:rajumyJava directory: .;C:rajumyJava ⚫Java will search for the required packages by looking up subsequent directories described in the CLASSPATH variable.
  • 70.
    Finding Packages ⚫ Considerthis package statement: package myPackage; In order for a program to find myPackage, one of the following must be true: 1)program is executed from the directory immediately above myPackage(the parentof myPackagedirectory) 2) CLASSPATH must be set to include the path to myPackage
  • 71.
    Example: Package package MyPack; class Balance {String name; double bal; Balance(String n, double b) { name = n; bal = b; } void show() { if (bal<0) System.out.print("-->> "); System.out.println(name + ": $" + bal); } }
  • 72.
    Example: Package class AccountBalance { publicstatic void main(String args[]) { Balance current[] = new Balance[3]; current[0] = new Balance("K. J. Fielding", 123.23); current[1] = new Balance("Will Tell", 157.02); current[2] = new Balance("Tom Jackson", -12.33); for (int i=0; i<3; i++) current[i].show(); } }
  • 73.
    Example: Package ⚫Save, compileand execute: 1)call the file AccountBalance.java 2) save the file in the directory MyPack 3) compile; AccountBalance.class should be also in MyPack 4)set access to MyPack in CLASSPATH variable, or make the parent of MyPack your current directory 5) run: java MyPack.AccountBalance ⚫Make sure to use the package-qualified class name.
  • 74.
    Importing of Packages ⚫Sinceclasses within packages must be fully-qualified with their package names, it would be tedious to always type long dot-separated names. ⚫The import statement allows to use classes or whole packages directly. ⚫Importing of a concrete class: import myPackage1.myPackage2.myClass; ⚫Importing of all classes within a package: import myPackage1.myPackage2.*;
  • 75.
    Import Statement ⚫The importstatement occurs immediately after the package statement and before the class statement: package myPackage; ⚫import otherPackage1;otherPackage2.otherClass; class myClass { … } ⚫The Java system accepts this import statement by default: import java.lang.*; ⚫This package includes the basic language functions.
  • 76.
    Example: Packages 1 ⚫A package MyPack with one public class Balance. The class has two same-package variables: public constructor and a public show method. package MyPack; public class Balance { String name; double bal; public Balance(String n, double b) { name = n; bal = b; } public void show() { if (bal<0) System.out.print("-- >> "); System.out.println(n ame + ": $" + bal);
  • 77.
    Example: Packages 2 Theimporting code has access to the public class Balance of the MyPack package and its two public members: import MyPack.*; class TestBalance { public static void main(String args[]) { Balance test = new Balance("J. J. Jaspers", 99.88); test.show();
  • 78.
    Java Source File Finally,a Java source file consists of: 1) a single package instruction (optional) 2) several import statements (optional) 3)a single public class declaration (required) 4) several classes private to the package (optional) At the minimum, a file contains a single public class declaration.
  • 79.
    Differences between classesand interfaces ⚫ Interfaces are syntactically similar to classes, but they lack instance variables, and their methods are declared without any body. ⚫ One class can implement any number of interfaces. ⚫ Interfaces are designed to support dynamic method resolution at run time. ⚫ Interface is little bit like a class...but interface is lack in instance variables....that's u can't create object for it..... ⚫ Interfaces are developed to support multiple inheritance... ⚫ The methods present in interfaces r pure abstract.. ⚫ The access specifiers public,private,protected are possible with classes, but the interface uses only one spcifier public..... ⚫ interfaces contains only the method declarations.... no definitions....... ⚫ A interface defines, which method a class has to implement. This is way - if you want to call a method defined by an interface - you don't need to know the exact class type of an object, you only need to know that it implements a specific interface.
  • 80.
    Defining an interface ⚫ Usinginterface, we specify what a class must do, but not how it does this. ⚫ An interfaceis syntacticallysimilar to a class, but it lacks instance variables and its methods are declared without any body. ⚫ An interface is defined with an interface keyword. keywor d paren t  An interface declaration consists of modifiers, the interface,the interfacename, a comma-separated list of interfaces (if any), and the interface body. For example: public interface GroupedInterface extends Interface1, Interface2, Interface3 { // constant declarations double E = 2.718282; // base of natural logarithms // //method signatures void doSomething (int i, double x); int doSomethingElse(String s); }  The public access specifier indicates that the interface can be used by any class in any package. If you do not specify that the interface is public, your interface will be accessible only to classes defined in the same package as the interface.  An interface can extend other interfaces, just as a class can extend or subclass another class. However, whereas a class can extend only one other class, an interfacecan extend any number of interfaces. The interface declaration includes a comma-separated list of all the interfaces that it extends
  • 81.
    Implementing interface General format: accessinterface name { type method-name1(parameter-list); type method-name2(parameter-list); … type var-name1 = value1; type var-nameM = valueM; … }
  • 82.
    ⚫Two types ofaccess: 1)public – interface may be used anywhere in a program 2)default – interface may be used in the current package only ⚫Interface methods have no bodies – they end with the semicolon after the parameter list. ⚫They are essentially abstract methods. ⚫An interface may include variables, but they must be final, static and initialized with a constant value. ⚫In a public interface, all members are implicitly
  • 83.
    Interface Implementation ⚫A classimplements an interface if it provides a complete set of methods defined by this interface. 1) any number of classes may implement an interface of its 2) one class may implement any number of interfaces ⚫Each class is free to determine the details implementation. ⚫Implementation relationis writtenwith the implements keyword.
  • 84.
    Implementation Format ⚫General formatof a class that includes the implements clause: ⚫Syntax: access class name extends super-class implements interface1, interface2, …, interfaceN { … } ⚫ Access is public or default.
  • 85.
    Implementation Comments ⚫If aclass implements several interfaces, they are separated with a comma. ⚫If a class implements two interfaces that declare the same method, the same method will be used by the clients of either interface. ⚫The methods that implement an interface must be declared public. ⚫The type signature of the implementing method must match exactly the type signature specified in the interface definition.
  • 86.
    Example: Interface Declaration ofthe Callback interface: interface Callback { void callback(int param); } Client class implements the Callback interface: class Client implements Callback { public void callback(int p) { System.out.println("callback called with " + p); } }
  • 87.
    More Methods inImplementation ⚫ An implementing class may also declare its own methods: class Client implements Callback { public void callback(int p) { System.out.println("callback called with " + p); } void nonIfaceMeth() { System.out.println("Classes that implement “ + “interfaces may also define ” + “other members, too."); }
  • 88.
    Applying interfaces A Javainterface declares a set of method signatures i.e., says what behaviorexists Does not say how the behavior is implemented i.e., does not give code for the methods Does not describe any state (but may include “final” constants) A concrete class that implements an interface Contains “implements InterfaceName” in the class declaration Must provide implementations (either directly or inherited from a superclass) of all methods declared in the interface or all interface An abstract class can also implementan interface Can optionally have implementationsof some methods
  • 89.
    ⚫Interfaces and Extendsboth describe an “is- a” relation. ⚫If B implements interface A, then B inherits the (abstract) method signatures in A ⚫If B extends class A, then B inherits everything in A. ⚫which can include method code and instance variables as well as abstract method signatures. ⚫Inheritance” is sometimes used to talk about thesuperclass / subclass “extends” relation only
  • 90.
    Variables in interface ⚫Variablesdeclared in an interface must be constants. ⚫A technique to import shared constants into multiple classes: 1)declare an interface with variables initialized to the desired values 2)include that interface in a class through implementation. ⚫As no methods are included in the interface, the class does not implement. ⚫anything except importing the variables as
  • 91.
    Example: Interface Variables1 An interface with constant values: import java.util.Random; interface SharedConstants { int NO = 0; int YES = 1; int MAYBE = 2; int LATER = 3; int SOON = 4; int NEVER = 5; }
  • 92.
    ⚫ Question implementsSharedConstants, including all its constants. ⚫ Which constant is returned depends on the generated random number: class Question implements SharedConstants { Random rand = new Random(); int ask() { int prob = (int) (100 * rand.nextDouble()); if (prob < 30) return NO; else if (prob < 60) return YES; else if (prob < 75) return LATER; else if (prob < 98) return SOON; else return NEVER; } }
  • 93.
    ⚫ AskMe includesall shared constants in the same way, using them to display the result, depending on the value received: class AskMe implements SharedConstants { static void answer(int result) { switch(result) { case NO: System.out.println("No"); break; case YES: System.out.println("Yes"); break; case MAYBE: System.out.println("Maybe"); break; case LATER: System.out.println("Later"); break; case SOON: System.out.println("Soon"); break; case NEVER: System.out.println("Never"); break;
  • 94.
    Example: Interface Variables4 ⚫The testing function relies on the fact that both ask and answer methods. ⚫defined in different classes, rely on the same constants: public static void main(String args[]) { Question q = new Question(); answer(q.ask()); answer(q.ask()); answer(q.ask()); answer(q.ask()); } }
  • 95.
    Extending interfaces ⚫One interfacemay inherit another interface. ⚫The inheritance syntax is the same for classes and interfaces. interface MyInterface1 { void myMethod1(…) ; } interface MyInterface2 extends MyInterface1 { void myMethod2(…) ; } ⚫When a class implements an interface that inherits another interface, it must provide implementations for all methods defined within the interface inheritance chain.
  • 96.
    Example: Interface Inheritance1 ⚫Consider interfaces A and B. interface A { void meth1(); void meth2(); } B extends A: interface B extends A { void meth3(); }
  • 97.
    Example: Interface Inheritance2 ⚫MyClass must implement all of A and B methods: class MyClass implements B { public void meth1() { System.out.println("Implementmeth1()."); } public void meth2() { System.out.println("Implement meth2()."); } public void meth3() { System.out.println("Implementmeth3()."); } }
  • 98.
    Example: Interface Inheritance3 ⚫Create a new MyClass object, then invoke all interface methods on it: class IFExtend { public static void main(String arg[]) { MyClassob = new MyClass(); ob.meth1(); ob.meth2(); ob.meth3(); } }