Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Unit II Inheritance in Java Inheritance in java is a mechanism in which one object acquires all the properties and behaviors of parent object. The class which inherits the properties of other is known as subclass (derived class, child class) and the class whose properties are inherited is known as super class (base class, parent class). The idea behind inheritance in java is that you can create new classes that are built upon existing classes. When you inherit from an existing class, you can reuse methods and fields of parent class, and you can add new methods and fields also. Inheritance represents the IS-A relationship, also known as parent-child relationship. Why use inheritance in java o For Method Overriding (so runtime polymorphism can be achieved). o For Code Reusability. Syntax of Java Inheritance: class Subclass-name extends Superclass-name { //methods and fields } extends Keyword extends is the keyword used to inherit the properties of a class. Following is the syntax of extends keyword. Syntax: Class Super { …… } Class Sub Extends super { ……. { Understanding the simple example of inheritance As given in the above figure, Programmer is the subclass and Employee is the superclass. Relationship between two classes is Programmer IS-A Employee.It means that Programmer is a type of Employee. Example class Employee{ float salary=40000; } class Programmer extends Employee{ int bonus=10000; public static void main(String args[]){ Programmer p=new Programmer(); System.out.println("Programmer salary is:"+p.salary); System.out.println("Bonus of Programmer is:"+p.bonus); } } Output: Programmer salary is:40000.0 Bonus of programmer is:10000 Note − A subclass inherits all the members (fields, methods, and nested classes) from its superclass. Constructors are not members, so they are not inherited by subclasses, but the constructor of the superclass can be invoked from the subclass. 1.2 Types of inheritance in java On the basis of class, there can be three types of inheritance in java: 1. Single 2. Multilevel 3. Hierarchical. Single Inheritance: When a class extends only one class then we call it a single inheritance. The below diagram shows that class B extends only one class which is A. Here A is a parent class of B and B would be a child class of A. A B Multilevel Inheritance: It refers to a mechanism in OO technology where one can inherit from a derived class. There by making this derived class the base class for the new class. As u can see in below flow diagram C is subclass or child class of B and B is a child class of A. A B C In java programming, multiple and hybrid inheritance is supported through interface only. Note: Multiple inheritances are not supported in java through class. Whenever a class extends multiple classes then it is known as multiple inheritances. For Example: Hierarchical inheritance One class is inherited by many sub-classes. In below examples Class B, C and D inherit the same class A. A is a parent class (or base class) of B, C & D. When a class has more than one child classes or in other words more than one child classes have the same parent class then such kind of inheritance is known as hierarchical inheritance. A B C D Why multiple Inheritance is not supported in java? To reduce the complexity and simplify the language, multiple inheritance is not supported in java. Consider a scenario where A, B and C are three classes. The C class inherits A and B classes. If A and B classes have same method and you call it from child class object, there will be ambiguity to call method of A or B class. Since compile time errors are better than runtime errors, java renders compile time error if you inherit 2 classes. So whether you have same method or different, there will be compile time error now. class A{ void msg() { System.out.println("Hello"); } } class B{ void msg() { System.out.println("Welcome"); } } class C extends A,B {//suppose if it were// public static void main(String args[]) { C obj=new C(); obj.msg();//Now which msg() method would be invoked? } } Output: Compile time Error What will happen on creation of subclass object? On creation of sub-class object memory is allocated for instance variable of super class and subclass. Example: Class A { int x=10; } Class B extends A { int y=20; } B obj=new B ( ); Organization of data is done inside subclass object using linked-list. Regarding variables of super-class within subclass 1. Inherited variables of super-class can be used directly within subclass. 2. Private variables of super-class cannot access by methods of subclass. If sub-class require private variables of super-class provide a method to access. 3. Subclass can bare its own variables other than variables inherited from super-class. 4. Within subclass we can declare variable with same name as variable exist in super-class. Example: Inherited variables of super-class can be used directly within subclass. Class A { int x=10; } Class B extends A { int y=20; } Class Inherit_Test1 { Public static void void main(String args[ ]) { B obj1=new B( ); System.out.println(obj1.x); System.out.println(obj1.y); } } Output: 10 20 Private variable of super-class cannot be accessed by method of subclass. If subclass requires private variables of super-class, then super-class provides a method to access variables. Example: Class A { private int x=0; int getx(); { return x; } } Class B extends A { private int y=20; void sum() { int z=getx()+y; System.out.println(z); } } Class InheritTest3 { public static void main(string args[ ]) { B obj1=new B(); Obj1.sum(); } } Regarding methods of super-class method over-ridings within subclass 1. Inherit methods of super-class can be accessed within subclass directly. 2. Subclass can inherit its own methods which are not exist in super-class. 3. Subclass can have instance method with same signature of instance method exist in superclass(). 4. Subclass can have static method with same signature of static method exist in super-class (method hiding). 5. Subclass cannot access private methods of super-class. Super: 1. It is a keyword or reference variable which holds reference of super-class. 2. Sub-class refers members of immediate super-class using super keyword. 3. It is used implicitly by compiler to refer members of super-class. 4. It can be used explicitly by program to refer members of super-class. This keyword: Class A { int x=10; } Class B extends A { int x=20; void m1() { System.out.println(this.x); } } What is the difference between this and super? this Super 1. It holds address of current object 1. It holds address of super-class. 2. It is used for accessing non-static members of current class 2. It is used for accessing non-static members of immediate super-class within subclass. Example: Class A { int x=10; } Class B extends A { int x=20; } Class C extends B { int x=30; void m1() { System.out.println (x); System.out.println (super.x); System.out.println (getx()); } } Super( ) Constructor call: Calling the constructor of super-class within subclass is done by using “super()” constructor call. Calling the constructor of super class within two types: 1. Implicit calling 2. Explicit calling Implicit calling Calling of super class default constructor within subclass is implicit it is done by compiler. The constructor of sub-class must bind with constructor of supericlass. Prog1.java Class A{ Private int x; A() { int x=10; } } Class B extends A { Private int y; B() { int y=20; }} Compiler A.Class Private int x A() { int x=10; } Javac prog1.java Example: Class A { A() { System.out.println ("Default constructor of superclass"); } } Class B extends A { B() { System.out.println ("inside default constructor subclass"); B.Class Private int y; B() { int y=20;} } } B(int x) { System.out.println("Inside parameterized constructor of subclass"); } } Class supertest() { public static void main(String args[]) { B obj1=new B(10); B obj2=new B(); } } ................................................................... Example: Class A { A(int x) { System.out.println ("Inside parameterized constroctor of superclass"); } } Class B extends A { B() { System.out.println ("Inside default constructor of subclass"); } } Class Supertest2 { public static void main(String args[]) { B obj1=new B(); } } output: Error Explanation: The above program displays compile time error because there is no default constructor in super-class and no constructor of super-class is called explicitly within subclass. Explicit calling of super-class constructor within subclass: Only default constructor (non-parameterized) of super-class is called by the compiler other constructor has to be called explicitly by including super() call inside subclass constructor. Rules: 1. It must be first statement within constructor 2. It is used inside constructor 3. Subclass constructor can call only one constructor of super-class but cannot calling of multiple constructors. What is difference between “this” and “super()” ? this Super() It is used to call constructor of some It is used to call constructor within class inside another constructor. subclass. What is difference between “super” and “super()” ? super It is reference variable Super() It is constructor call It is used to refer variable and methods It is use to call constructor of superclass of superclass within subclass within subclass What is constructor chaining? Calling the constructor of super-class is called chaining. Note: A constructor can use this() or super() but cannot use both. Example: Class A { A(int x) { System.out.println (“Inside parameterized constructor”); } } When to use Abstract methods and Abstract class? Abstract methods are usually declared in two or more subclasses are expected to fulfill a similar role in different ways through different implementation (polymorphism). These subclasses extend the same abstract class and different implementation for the abstract method. Use abstract class to define broad types of behaviors at the top of an object oriented programming class hierarchy and use its subclasses to provide implementation details of the abstract class. Example of abstract class that has abstract method In this example, Bike the abstract class that contains only one abstract method run. It implementation is provided by the Honda class. abstract class Bike { abstract void run(); } class Honda4 extends Bike { void run() { System.out.println("running safely.."); } public static void main(String args[]) { Bike obj = new Honda4(); obj.run(); } } Output: running safely.. Understanding the real scenario of abstract class In this example, Shape is the abstract class; its implementation is provided by the Rectangle and Circle classes. Mostly, we don't know about the implementation class (i.e. hidden to the end user) and object of the implementation class is provided by the factory method. A factory method is the method that returns the instance of the class. We will learn about the factory method later. In this example, if you create the instance of Rectangle class, draw() method of Rectangle class will be invoked. File: TestAbstraction1.java abstract class Shape { abstract void draw(); } //In real scenario, implementation is provided by others i.e. unknown by end user // class Rectangle extends Shape { void draw() { System.out.println("drawing rectangle"); } } class Circle1 extends Shape { void draw() { System.out.println("drawing circle"); } } //In real scenario, method is called by programmer or user // class TestAbstraction1 { public static void main(String args[]) { Shape s=new Circle1(); //In real scenario, object is provided through method e.g. getShape() method // s.draw(); } } ……………………………………………………… Output: drawing circle Interface Interface is a collection of abstract methods and final static variables (constants). What is an interface? It is defined as standard and public way of specifying the behavior of classes. Defines a construct. All the methods of an interface are abstract methods. Defines a signature of a set of methods without the body (implementation of the methods). All concrete class must implement the interface (all the abstract methods of interface). It allows classes regardless of their locations in the class hierarchy to implement common behavior. Note: By using interface we can achieve loosely coupled application (or runtime polymorphism) develop a code which run independent to a subtypes is called loosely coupled. ATM RBI Detailed withdraw() HDFC Debit card SBI Debit card ICICI Debit card Caller Interface calle Calle Mobile SIM ……. ………….. ……… ……………… Airtel Sim BSNL sim DOCOMO sim Why do we use interface? Reason 1: To read an object programming interface (functionality of an object) without revealing its implementation, we use interfaces. This concept is of encapsulation The implementation can change without affecting the caller of the interface. The caller does not need the implementation at the compile time. It needs only the interface at the compile time. During runtime actual object instance is associated with the interface type. Reason2: To have an unrelated classes implement similar methods (behavior). One class is not sub-class of another. Reason3: To model multiple inheritance that we want to impose multiple set of behaviors to our class. Each set is defined as an interface A class can implement multiple interfaces while it can extend only one class. Note: Interface allows only one access specifiers i.e “public”. Interface defines: Public behavior of class Standard Protocols Contract Abstracts Specification Set of rules and regulations Interface consists of abstract methods and final static variables (constants). Implements: A class inherits interface using implements keyword. A class implements one or more than one interface. A class extends only one class but implements more than one interface. The class which implements interface is called concrete class. Concrete class that provides implementations of all abstract methods. What is the difference between extends and implents? Extends It allows reusability and extensibility. Implements It allows reusability. Syntax: Class <Class_name>implements <interface_name>, <interface_name>……………. { { Class <class_name > extends<clas_name> Implements <interface_name>,<interface_name>,………………….. { } What is difference between abstract classes and interfaces? Abstract class interface 1. It contains abstract methods and non-abstract methods. 1. It contains only abstract methods 2. It allows variables and constants. 2. It allows only constants. 3. Members can be private public or protected or default. 3. Members must be public. 4. It extends only one class 4. A class implements more than one interface. When to use of an Abstract class over interface? For non-abstract methods, you want to use them when you want to provide common implementation code for all sub-classes. Reading the duplications. For abstract methods, the motivation is the same with the one in the interface to impose a common behavior for all sub-classes without dictating how to implement it. Remember a concrete can extend only one super class whether the super class id in the form of concrete class or abstract class. Adapter Class Adapter class is an abstract class which implements interface. 1. Avoiding overriding of all the methods of interface. 2. To avoid code redundancy. What is a marker interface? It is an interface that contains no methods. Example: Serializable, clonable Single Thread model etc, It is used to just mark java classes that support certain capability. What are the Tag interfaces? The interface is an alternative name for marker interface. Interface of operator (keyword) This operator returns Boolean value. This operator verifies which type of object hold by reference variable. Final variables, methods and classes: Final is a keyword used to declare variables, methods and classes. Final Variable: It is a variable declared with final keyword it is called final variable and value of this variable cannot modified. Final variables are constants 1. 2. 3. 4. Local final variables Instance final variable Class final variable Final variable as parameters Local Final variables: If a variable declared inside method with final keyword it is called final local variables. Final variables must be initialized. Syntax: Final datatype variable_name=value; Example: Class Final Demo1 { Public static void main(String args[ ]) { int x; Final int y; } } Explanation: The above program does not display any error but local variables must beassign values before assigning it. Final instance variable: If a variable declared inside class with final and without static keyword., it is calledfinal instance variable. There are no default values given to final instance variable. Final instance variable are initialized within class or inside constructors. Class A { Final int x; } Explanation: The above program displays output but x is not given any value. Class A { Final int x=10; Final int y; A() { Y=20; } } Final class variables: If a variable declared inside class with final and static, it is called final variable. This variable is bind with class name. Syntax: Final static datatype variable_name; Final static variables can be initialized within calss static block or inside constructor. Example: Class A { Final static int x; } Output: Compile time error, variable might have not been initialized. Explanation: The above program displays compile time error, because final variable must assign value. Nested top level class What is nested top level class? A class declared within a class with static modifier is called nested top level class. Any class outside the declaring class can access the nested top level class with the declaring class. Top-level inner classes have access to static variables only. Static inner class is called nested top level class. What is difference between member class and nested top level class? Member class Nested top-level class Non-static inner class Static inner class Cannot access outside outer class Can be accessed outside outer class Can access static and non-static members of outer class Can access only static members of outer-class Rule: Nested top-level class access static member of outer class but cannot access non-static member. Class A { int x; Static int y; Static class B { System.out.println (x); System.out.println (y); } } Rule: Nested top level class can be accessed outside outer class Class A { Static class B { int x=10; } } A.B objb=new A.B(); Inner classes Inner Class Java inner class or nested class is a class i.e. declared inside the class or interface. We use inner classes to logically group classes and interfaces in one place so that it can be more readable and maintainable. Additionally, it can access all the members of outer class including private data members and methods. Syntax of Inner class: class Java_Outer_class { //code class Java_Inner_class { //code } } Advantage of java inner classes There are basically three advantages of inner classes in java. They are as follows: 1) Nested classes represent a special type of relationship that is it can access all the members (data members and methods) of outer class including private. 2) Nested classes are used to develop more readable and maintainable code because it logically group classes and interfaces in one place only. 3) Code Optimization: It requires less code to write. Note: Inner class is a part of nested class. Non-static nested classes are known as inner classes. Types of Nested classes There are two types of nested classes non-static and static nested classes.The non-static nested classes are also known as inner classes. 1. Non-static nested class(inner class) a) Member inner class b) Anonymous inner class c) Local inner class 2. Static nested class Type Member Inner Class Anonymous Inner Class Local Inner Class Static Nested Class Nested Interface Description A class created within class and outside method A class created for implementing interface or extending class. Its name is decided by the java compiler. A class created within method. A static class created within class. An interface created within class or interface. Local inner class A class i.e. created inside a method is called local inner class in java. If you want to invoke the methods of local inner class, you must instantiate this class inside the method. Example: public class localInner1{ private int data=30;//instance variable void display(){ class Local{ void msg(){System.out.println(data);} } Local l=new Local(); l.msg(); } public static void main(String args[]){ localInner1 obj=new localInner1(); obj.display(); } } Output: 30 Internal class generated by the compiler In such case, compiler creates a class named Simple $1 Local that have the reference of the outer class. import java.io.PrintStream; class localInner1$Local { final localInner1 this$0; localInner1$Local() { super(); this$0 = simple.this; } void msg() { System.out.println(localInner1.access$000(localInner1.this)); } } Note: Local variable can't be private, public or protected. Rules for Java Local Inner class: 1) Local inner class cannot be invoked from outside the method. 2) Local inner class cannot access non-final local variable till JDK 1.7. Since JDK 1.8, it is possible to access the non-final local variable in local inner class. Java Anonymous inner class A class that has no name is known as anonymous inner class in java. It should be used if you have to override method of class or interface. Java Anonymous inner class can be created by two ways: 1. Class (may be abstract or concrete). 2. Interface Anonymous inner class example using class: abstract class Person{ abstract void eat(); } class TestAnonymousInner{ public static void main(String args[]){ Person p=new Person(){ void eat(){System.out.println("nice fruits");} }; p.eat(); } } ………………………………………………………… Output: nice fruit Internal working of given code: It performs two main tasks behind this code: Eatable p=new Eatable() { void eat(){System.out.println("nice fruits");} }; A class is created but its name is decided by the compiler which implements the Eatable interface and provides the implementation of the eat() method. An object of Anonymous class is created that is referred by p reference variable of Eatable type. Java static nested class A static class i.e. created inside a class is called static nested class in java. It cannot access nonstatic data members and methods. It can be accessed by outer class name. o It can access static data members of outer class including private. o Static nested class cannot access non-static (instance) data member or method. Static nested class example with instance method: class TestOuter1{ static int data=30; static class Inner{ void msg(){System.out.println("data is "+data);} } public static void main(String args[]){ TestOuter1.Inner obj=new TestOuter1.Inner(); obj.msg(); } } ……………………………………………. Output: data is 30 In this example, you need to create the instance of static nested class because it has instance method msg(). But you don't need to create the object of Outer class because nested class is static and static properties, methods or classes can be accessed without object. Java static nested class example with static method If you have the static member inside static nested class, you don't need to create instance of static nested class. class TestOuter2{ static int data=30; static class Inner{ static void msg(){System.out.println("data is "+data);} } public static void main(String args[]){ TestOuter2.Inner.msg();//no need to create the instance of static nested class } } -------------- // Output: data is 30//----------------- Packages: What are packages? A package is a grouping of related types providing access protection and name space management. Note that types refer to classes, interfaces, enumerations and annotation types. Types are often referred to simply as classes and interfaces since enumeration and annotation are special kind of classes and interfaces respectively so types are often referred to simply as classes and interfaces. A packages is a collection of classes, interfaces and enum. A package is a directory which contains class file. Benefits of Packaging You and other programmers can easily determine that those classes and interfaces are related. The names of your classes and interfaces won’t conflict with the names in other packages because the package creates a new namespace. You can allow classes within the package to have unrestricted access to one another yet still restrict access for types outside the package. How to create package? Keyword “package” is used for creating package Syntax: Package package-name; Class class-name { // } Interface interface-name { // } Enum enum-name { // } 1. Package statement must be first statement within java source program. 2. On java source program allows only one package statement P1.java P2.java Package package1; Class A{ } Package package2; Package package1; 3. Package name must be in lower cases(name convention) Java.lang Bank.account Bank.tranfer Bank.reports Bank.account Com.bank.account Edu.students Contents of package can be public or default. Package contains top-level classes or default. Package package1; Class A { // } How to compile package? Java –d<location> source-program-name d(directory) Compiler creates a directory with package and generates dot class (.class) files. Using classes from other packages To use a public package member (classes and interface) from outside its package you must do one of the following. Important the package member using import statement. Refer to the member by its fully qualified name (without using import statement). Import Statement: Syntax1: Importing all the members from the package import package_name.*; Syntax2: Importing specific number of package “import package_name.member_name;” Eg: import java.util.*; (All the members of package) Import java.util.scanner; (only one member package.) Import is not including importing adding fully qualified name of the class. Fully qualified is class name with package name. Example: prog1.java .................................. import java.util.date; Class Demo { Public static void main(String args[]) {Date d=new Date(); System.out.println(d); }} Javac prog1.java Demo.Class ......................... Class Demo { Public static void main(String args[]) { java.util.date d=new java.util.Date(); }} } }} } What is class path? Classpath is a java environment variable used for locating packages or classes. This variable is used by java compiler and JVM. Syntax: Windows Set classpath=path1;path2;path3;………;*;.; // Dot indicates current directory// Set classpath=f:\;c:\java\1am; Syntax: UNIX, Linux Export classpath=path1;path2;……. Prog1.java Import-package1.A; Class A{ } Package1.class Javac package1.java Package1.A objA=new A(); Set classpath=f:\;c:\class1am Disk F: Package A.class Example: Adding a new class in package Package package1; Public class E { void m1() { System.out.println(“inside m1”); } } Example: Calling member of the class outside package Private Default Protected Public …………………………………………… import package1.c; Class package2 { public static void main(String args[]) { C obj=new c); Objc.m1(); } } …………………………………………….. Note: m1 is not public in “C class” cannot access from out of the package. Class Member Access: Within class Within subclass of same package Within nonsubclass of same package Within subclass outside package With non subclass outside package Private yes no no no no Default yes yes yes no no Protected yes yes yes yes no Public yes yes yes yes yes