Pages

Tuesday 6 August 2019

Inheritance

Agenda:
  • Inheritance
  • Abstract class
  • Interface
  • Polymorphism
  • Overriding
  • Casting
  • Use of super and this keyword
  • Lambda basics
Inheritance:
Inheritance is a way to form new classes using classes that have already been defined.
In other words, pull out common properties and behaviors of the classes and put these in the new class.

Benefits:
  • Helps in reusing existing code.
  • It helps in defining the relationship between classes.
  • Is-A Relationship.
For example:
Computer Engineer is an Engineer.
A manager is an Employee.
A lion is an Animal

Important points to remember:
  • A class can inherit another class(concrete or abstract) by using the keyword extends.
  • A class can at-most inherit only one class.
  • A class can inherit the interface by using keyword implements.
  • A class can inherit multiple interfaces.
For example: class A implements Interf1,interf2,interf2{}
  • An interface can inherit another interface by using the keyword extends.
  • A derived class can define additional properties and behaviors.
Q.Which base class members are inherited by a derived class?
Ans: A derived class can inherit only what it can see.
    For example default(if base class and derived class exist in the same package), protected and public members of the base class.

Q.Which base class members aren't inherited by a derived class.
  • private members,
  • default members(if base class and derived class exist in different packages)
  • Constructors of the base class.
Note: A derived class can call a base class's constructor, but it doesn't inherit them.
Abstract class:
  • It groups the common properties and behavior of its derived classes, but it prevents itself from being instantiated.
  • Using keyword abstract with class you can create an abstract class.
Important points to remember:
  • You can never create objects of an abstract class.
  • you can define methods(method with the body) in an abstract class.
  • you can declare abstract methods(method without body) in an abstract class.
  • You can define an abstract class in a base class(abstract class or concrete class).
  • A derived class should implement all the abstract methods of its base class. If it doesn't, it must be defined as an abstract derived class
  • You can use variables of an abstract base class.
Note: Derived class is aka Subclass, Extended class, Child class.
Note : Base class is aka Super-class, Parent class.

Interface
Any service requirement specification(SRS)  or any contract between client and service provider is considered an interface.

Important points to remember:
  • All variables of the interface by default public static final.
  • All methods declaration(method without body) by default public abstract.
  • Interfaces can't have a constructor.
  • You can define default methods in the interface from java 8 onward.
  • For example: public default void m1(){}
  • You can define static methods in the interface from java 8 onward.
  • For example: public static void m2(){}
  • An interface can inherit another interface by using the keyword extends.
  • An interface can't inherit class(concrete or abstract).
  • You can't define static and instance blocks in an interface.
  • You can't create an object of an interface.

Q.Valid modifiers for an interface.
Ans: public, abstract,strictfp(PAS).

Q.Valid modifiers for an interface's variables.
Ans: public static final.

Q.Valid modifiers for an interface's abstract methods.
Ans: public,abstract(PA).

Q.Valid modifiers for an interface's default methods.
Ans: public, strictfp,  default(DPS).

Q.Valid modifiers for an interface's static methods.
Ans:public,strictfp,static(PSS).

When a class implements a single interface:
Assume, there is an interface Animal and having
  • an abstract method,  eat().
  • a default method,  sleep().
  • a static method, run().
  1. interface Animal{
  2. public void eat();
  3. default void sleep(){
  4. System.out.println("Can sleep");
  5. }
  6. static void run(){
  7. System.out.println("Can run");
  8. }
  9. }
Now, A class Dog implements this interface
class Dog implements Animal{
public void eat(){}// Then you must implement the abstract method of an interface otherwise compiler error. You may or may not override the default method of an interface. If you want to override this, you must not use the keyword default and follow method-overriding rules.
The static method in a class doesn't hide or override the static method in the interface and both are not related to each other.

}
Interface Naming Conflicts:
Method Naming conflicts
Case 1:If two interfaces X, Y have a method with the same signature(method name + arguments) and same return type, in the implementation class A, only one method implementation is enough.
Example:
  1. interface X{
  2. void doSomething();
  3. }
  4. interface  Y{
  5. void doSomething();}
  6. class A implements X,Y{
  7. public void doSomething(){
  8. System.out.println("Do something");
  9. }
  10. }
Case 2:If two interfaces X,Y have a method with same signature but different return type, you can't implement both the interfaces at the same time,Otherwise you will get Compiler Error.
Example:
  1. interface X{
  2. String doSomething();
  3. }
  4. interface  Y{
  5. void doSomething();
  6. }
  7. class A implements X,Y{}//Compiler error(ambiguity problem)
Case 3:If two interfaces X, Y have a method with the same name but different arguments list, in the implementation class A, you have to provide the implementation for both the methods. And These methods act as overloaded methods.
Example:
  1. interface X{
  2. void doSomething(int a);
  3. }
  4. interface  Y{
  5. void doSomething();
  6. }
  7. class A implements X,Y{
  8. public void doSomething(){
  9. System.out.println("Do something");
  10. }
  11. public void doSomething(int a){
  12. System.out.println(a);
  13. }
  14. }
Case 4:If two interfaces X, Y have a method with same signature(method name + arguments) and same return type,and an interface Z extends both the interfaces(X,Y),there is no conflicts at all.
Example:
  1. interface X{
  2. void doSomething();
  3. }
  4. interface  Y{
  5. void doSomething();
  6. }
  7. interface Z extends X, Y{}//compile successfully

Case 5:If two interfaces X, Y have a method with the same signature but different return type, you can't extend both the interfaces at the same time, Otherwise, you will get Compiler Error.
Example:
  1. interface X{
  2. void doSomething();
  3. }
  4. interface  Y{
  5. int doSomething();
  6. }
  7. interface Z extends X, Y{}//Compiler Error(ambiguity problem)
Case 6:If two interfaces X, Y have a method with same name but different arguments list, and an interface Z extends both the interfaces(X.Y), then there is no conflicts at all.
Example:
  1. interface X{
  2. void doSomething(int a);
  3. }
  4. interface  Y{
  5. void doSomething();
  6. }
  7. interface Z extends X, Y{}//compile successfully
Note: For default method of an interface above rules are applicable w.r.t class and interface.
Note: For the static method of an interface no tension at all.No rule for a static method.

Variables Naming conflicts:

Case 1:If two interfaces X, Y have a variable with the same name, there may be a chance of variable naming conflicts but you can resolve it by using interface name.
Example:
  1.  interface X{
  2. int a=10;
  3. }
  4. interface Y{
  5. int a=20;
  6. }
  7. class A implements X, Y{
  8. public static void main(String[] args){
  9. //System.out.println(a);// Compiler Error
  10. //But you can resolve it as below
  11. System.out.println(X.a);
  12. //or
  13. System.out.println(Y.a);
  14. }
  15. }
Polymorphism:
  • Polymorphism means many forms
  • Generally
  • Reference type and object type are same.
  • Dog dog = new Dog();
  • But, with Polymorphism
  • The reference type and object type can be different.
  • Animal animal = new Dog();
Overriding
When you are not satisfied with any method of the parent class, then you can override that method and implement it according to your requirements. But you have to follow the following rules.
Rules:
  • In the overriding method signature(name+arguments) must be the same.
  • Until 1.4 version the return type must be the same, but from 1.5 onward co-variant return types allowed.
  • It means Child class method return type need not be the same as the Parent class method return type. Its child types also allowed.
Example:
  1. class Parent{
  2. public Object getName(){//overriden method
  3. return "Kalawati";
  4. }
  5. }
  6. class Child extends Parent{
  7. public String getName(){  //overriding method
  8. return "Anu";
  9. }
  10. }
Here String is child class of Object class.
Note: co-variant return type concept is applicable only for object types, but not for primitives types.
  • We can't override private, static and final methods.
  • While overriding if the child class method throws any checked exception compulsory the parent class method should throw the same checked exception or its parent otherwise we will get a compiler error. But there is no restriction on runtime exception.
  • You can't reduce the scope of the overriding method.
  • You can use the keyword final in the overriding method.
  • Note there are no restrictions on synchronized,strictfp, native and abstract methods.
Typecasting:
  • Parent class reference can be used to hold child class objects, but by using this reference you can't call Child-specific methods.
  • But your requirement is to invoke child class-specific method then you can go for typecasting.
Syntax:
A b = (C) d;
Here: A,C are class/interface
        b,d is the name of the reference variables.
Rules:
Compile-time checking:
  1. The type of d and C must have some relationship(child to parent or parent to child or same type) otherwise you will get a compiler error(In-convertible type).
  2. C must be either the same or derived type of A otherwise you will get a compiler error(Incompatible type).
Runtime checking:
  • The underlying object type of d must be either the same or derived type of C otherwise you will get runtime exception(ClassCastException).
  • Example: Object o = new String("amit");
  •     StringBuffer sb =(StringBuffer)o; //ClassCastException
Note:
Through type casting just you are converting the type of object but not object itself that is you are performing type casting but not object casting.

Use of this and super keywords:
  • this is used to call current class instance members.
  • super is used to call parent class instance members.
  • You can use this and super anywhere except static area(static block and static method).
User of super() and this():
super() is used to call parent class constructors.
this() is used to call current class constructors.
You can use super() or this() only in the first line of the constructor. If you are taking anywhere else you will get a compiler error.
You can either super() or this() but not both simultaneously.
You can use super() or this() only inside the constructor. If you are using anywhere else you will get a compiler error.

Lambda basics
For Lambda basics click on Lambda Basics
Predicate Function:
  • It is a functional interface.
  • It has only one abstract method test().
  • public boolean test(T t);
For example:
  1. class Test{
  2.    ArrayList<Integer> al = new ArrayList<>();
  3.       al.add(10);
  4.       al.add(20);
  5.       al.add(30);
  6.       al.add(40);
  7.       al.add(50);
  8.       Predicate<Integer> predicate = e->e>30;
  9.       al.removeIf(predicate);
  10.       //al.removeIf(e->e>30); // you can also pass code as an argument.
  11.       System.out.println(al);// [10, 20, 30]

  12. }
  13. }
Supporting topic: Use of Modifiers
Next Topic: EXCEPTION HANDLING