Java - Module 2 PPT
Java - Module 2 PPT
Unit - II
Inheritance and Interfaces
Inheritance
○ Orange is a fruit.
○ A surgeon is a doctor
○ A dog is an animal
What is inherited?
● Public and protected fields and methods are inherited
● Private fields and methods of the superclass can never be referenced directly
by subclasses
class Superclass-name{
}
Single Inheritance
Single Inheritance - Syntax
class Parent {
// methods
// fields
}
class Child extends Parent {
// already supports the methods and fields in Parent class
// additional features
}
Example
class Parent {
public void p1() {
System.out.println("Parent method");
}
}
public class Child extends Parent {
public void c1() {
System.out.println("Child method");
}
public static void main(String[] args) {
Child cobj = new Child();
cobj.c1(); //method of Child class
cobj.p1(); //method of Parent class
}
}
Multilevel Inheritance
Multilevel Inheritance - Syntax
class GrandParent {
// methods
// fields
}
class Parent extends GrandParent {
// already supports the methods and fields in Parent class
// additional features
}
class Child extends Parent {
// already supports the methods and fields in Parent class
// additional features
}
Multilevel Inheritance - Example
class GrandParent {
public void gp1() {
System.out.println(“Grand Parent method");
}
}
class Parent extends GrandParent {
public void p1() {
System.out.println("Parent method");
}
}
public class Child extends Parent {
public void c1() {
System.out.println("Child method");
}
public static void main(String[] args) {
Child cobj = new Child();
cobj.c1(); //method of Child class
cobj.p1(); //method of Parent class
cobj.gp1(); //method of GrandParent class
}
}
Hierarchical Inheritance
Hierarchical Inheritance - Syntax
class Parent {
// methods
// fields
}
class Son extends Parent {
// already supports the methods and fields in Parent class
// additional features
}
class Daughter extends Parent {
// already supports the methods and fields in Parent class
// additional features
}
Hierarchical Inheritance - Example
class Parent {
public void p1() {
System.out.println(“Parent method");
}
}
class Son extends Parent {
public void s1() {
System.out.println(“Son method");
}
}
public class Daughter extends Parent {
public void d1() {
System.out.println(“Daughter method");
}
public static void main(String[] args) {
Child cobj = new Child();
cobj.d1(); //method of Daughter class
cobj.s1(); //method of Son class
cobj.p1(); //method of Parent class
}
}
this keyword
● this is a reference variable that refers to the current object inside a method
or a constructor.
● The most common use of the this keyword is to eliminate the confusion
between class attributes and parameters with the same name
● It can be used to refer to any member of the current object from within an
instance method or a constructor.
Usage of „this‟ keyword
● to refer current class instance variable
class ThisDemo{
ThisDemo(){
System.out.println(“Default Constructor”);
}
ThisDemo(int x){
this();
System.out.println(“x=“+x);
}
public static void main(String[] args){
ThisDemo td=new ThisDemo(5);
}
}
to pass as an argument in a method
class ThisDemo{
void show(ThisDemo td){
System.out.println("show method");
}
void callShow(){
show(this);
}
public static void main(String[] args){
ThisDemo td=new ThisDemo();
td.callShow();
}
}
to pass as argument in the constructor call
class Demo{
int y;
Demo(ThisDemo t1){
y=t1.x;
System.out.println("y="+y);
}
}
class ThisDemo{
int x=5;
ThisDemo(){
Demo d1=new Demo(this);
}
public static void main(String[] args){
ThisDemo td=new ThisDemo();
}
}
this keyword can be used to return current class instance
class Demo{
int y=5;
Demo retun(){
return this;
}
void show(){
System.out.println(y);
}
public static void main(String[] args){
new Demo().retun().show();
}
}
Super keyword
● It is a reference variable, used to refer immediate parent class object
● It is used to call superclass methods, and to access the superclass
constructor.
● The most common use of the super keyword is to eliminate the confusion
between superclasses and subclasses that have methods with the same
name
Optional
● Syntax
super([arguments]);
Rules of Super Keyword
● super() must be the first statement in the body of subclass constructor when
call the superclass constructor
● A superclass constructor can only be called from a subclass constructor.
Any other subclass method cannot call it.
● A superclass constructor call requires the use of super. It is illegal to specify
the actual name of the class.
● From outside the class, a constructor is always called with a new keyword, it
may be called from another constructor with this or super.
● “this” operator is used to call another constructor of the same class while
super is used to call the constructor of its superclass
Usage of “super” keyword
● Object class is the parent class of all the classes in java by default. ie it is the
topmost class of java
● Object class is beneficial if you want to refer any object whose type you don't
know
● parent class reference variable can refer the child class object, know as
upcasting
● getObject() method that returns an object but it can be of any type like
Employee,Student etc. Object obj=getObject();
● Object class is present in java.lang package
Object class methods
● toString() - public String toString()
● hashCode() - public int hashCode()
● equals(Object obj) - public boolean equals(Object obj)
● getClass() - public final Class getClass()
● finalize() - protected void finalize()throws Throwable
● clone() - protected Object clone() throws CloneNotSupportedException
● wait() - public final void wait(long timeout)throws InterruptedException
● notify() - public final void notify()
● notifyAll() - public final void notifyAll()
Abstract class
//non-abstract method
method name same as
//constructors
class name
//static methods
//final methods method with static keyword
}
method with final keyword
Example for abstract class
int color;
}
Using abstract class
abstract class Shape {
abstract void draw();
}
class Square extends Shape {
void draw() {
System.out.println(“Square shape");
}
}
class ShapeDemo {
public static void main(String args[]) {
Shape s1=new Shape(); X
Shape s1 = new Square(); // references of Base type.
s1.draw();
}
}
Quiz
Which of these method of Object class can generate duplicate copy of the object
on which it is called?
a) clone()
b) copy()
c) duplicate()
d) dito()
Abstract class with constructor
abstract class Base {
Base() {
System.out.println("Base Constructor Called");
}
Output
abstract void fun();
Base Constructor Called
} Derived Constructor Called
class Derived extends Base {
Derived(){
System.out.println("Derived Constructor Called");
}
void fun(){
System.out.println("Derived fun() called");
}
}
class Main {
public static void main(String[] args) {
Derived d = new Derived();
}
}
abstract class without any abstract method
abstract class Base {
void fun() {
System.out.println("Base fun() called");
}
} Output
class Derived extends Base { Base fun() called
}
class Main {
public static void main(String[] args) {
Derived d = new Derived();
d.fun();
}
}
abstract class with a final method
abstract class Base {
final void fun(){
System.out.println("Derived fun() called");
}
} Output
class Derived extends Base{ Derived fun() called
}
class Main{
public static void main(String[] args){
Base b = new Derived();
b.fun();
}
}
Method overriding
● Both sub class and the super class have the same method
● If the object belongs to super class then super class method will be invoked
● If an object belongs to sub class then sub class method will be invoked
Rules for Java Method Overriding
● The method must have the same name, same parameter and same return
type as in the parent class
● Both super class and sub class can have different access specifier
Example for method overriding
class Super{
void show(){
System.out.println("Super class method");
}
}
class Sub extends Super{
void show(){
System.out.println("Sub class method");
}
}
class OverRide{
public static void main(String[] args){
Super s1=new Super();
s1.show(); //Super class method
s1=new Sub();
s1.show(); //Sub class method
}
}
Quiz
(A) If we derive an abstract class and do not implement all the abstract methods,
then the derived class should also be marked as abstract using „abstract‟
keyword
● It is a non-access modifier
○ Methods
○ Classes
■ Stop inheriting
final variable
● Variable declared with final keyword
● It‟s value can‟t be modified ie. it is a constant
● It must be initialized
● If it is not initialized then it is called as blank final variable
● Blank final variable can be initialized by
○ Initializer block
○ constructor
● It can be static
● It can be a reference
○ Cannot be re-bound to reference another object
○ It can be updated
final variable
class FinalVariable {
}
final reference
class Reference{
public int value = 5;
}
class FinalRefVariable {
public static void main( String args[] ) {
final Reference example = new Reference(); //declaration
example.value = 6; // Modifying the object creates no disturbance
Reference another = new Reference();
// Attempting to change the object it refers to, creates an error
example = another;
}
}
final parameter
class FinalParameter {
//final parameter
}
final method
// declaring a final method
class Base{
public final void finalMethod(){
System.out.print("Base");
}
}
class Derived extends Base{
public final void finalMethod() { //Overriding the final method throws an error
System.out.print("Derived");
}
}
final class
● It is a blueprint of a class
● An interface is written in a file with a .java extension, with the name of the
interface matching the name of the file.
Syntax
}
Example
interface Shape {
int radius=3;
double getArea();
}
Interfaces
interface HemiSphere{
double volumeHS();
}
interface Cone{
double volumeC();
}
class Shape implements HemiSphere, Cone{
public volumeHS(){
}
public volumeC(){
}
public static void main(String[] args){
}
}
“default” methods in interface
● default method can contain its own implementation directly within the interface
● If no body for a default method then compiler generate an error
interface Shape{
default double area(){
return 3.14*3*3;
}
}
class Circle implements Shape{
public static void main(String[] args){
System.out.println(“Area of circle: ”+new Circle().area());
}
}
static method in interfaces
● Java 8 is the ability to add static methods to interfaces
● The only big difference is that static methods are not inherited in the classes
that implement the interface
● This means that the interface is referenced when calling the static method
not the class that implements it
static method in interfaces
interface Shape{
static void show(){
System.out.println(“Static method”);
}
}
class InterDemo implements Shape{
public static void main(String[] args){
InterDemo id=new InterDemo();
id.show(); //Error
Shape.show();
}
}
Inheritance in interfaces
Multiple inheritance
Difference between class and interface
CLASS INTERFACE
The keyword used to create a class is “class” The keyword used to create an interface is “interface”
A class can be instantiated i.e, objects of a class can An Inteface cannot be instantiated i.e, objects cannot
be created. be created.
Classes does not support multiple inheritance. Inteface supports multiple inheritance.
It can be inherit another class. It cannot inherit a class.
It can be inherited by a class by using the keyword
It can be inherited by another class using the keyword
„implements‟ and it can be inherited by an interface
„extends‟.
using the keyword „extends‟.
It can contain constructors. It cannot contain constructors.
It cannot contain abstract methods. It contains abstract methods only.
Variables and methods in a class can be declared
All variables and methods in a interface are declared as
using any access specifier(public, private, default,
public.
protected)
Variables in a class can be static, final or neither. All variables are static and final.
Object cloning
● Override the clone() method and it must invoke super class clone() method
● Shallow cloning
● Deep cloning
● Syntax
class Outer_Class{
//…
class Inner_Class{
//…
}
}
Types of Nested classes
Nested Classes
● It can have access modifier or even can be marked as abstract and final
● it can access all the members of outer class including private data members
and methods
● To access the inner class, create an object of the outer class, and then
create an object of the inner class
Predefined or user-
defined object
Example
void add(int index, E element) It is used to insert the specified element at the specified position in a list.
boolean add(E e) It is used to append the specified element at the end of a list.
void clear() It is used to remove all of the elements from this list.
E get(int index) It is used to fetch the element from the particular position of the list.
boolean isEmpty() It returns true if the list is empty, otherwise false.
int lastIndexOf(Object o) It is used to return the index in this list of the last occurrence of the specified
element, or -1 if the list does not contain this element.
Object[] toArray() It is used to return an array containing all of the elements in this list in the correct
order.
Object clone() It is used to return a shallow copy of an ArrayList.
boolean contains(Object o) It returns true if the list contains the specified element
int indexOf(Object o) It is used to return the index in this list of the first occurrence of the specified
element, or -1 if the List does not contain this element.
E remove(int index) It is used to remove the element present at the specified position in the list.
boolean remove(Object o) It is used to remove the first occurrence of the specified element.
E set(int index, E element) It is used to replace the specified element in the list, present at the specified
position.
int size() It is used to return the number of elements present in the list.
Creating ArrayList
namelist.add(“Ganesh”);
namelist.add(“Mahesh”);
namelist.add(“Gukesh”);
namelist.add(“Rupesh”);
namelist.add(“Rajesh”);
Print the elements of an ArrayList
System.out.println(namelist);
or
for(String s1:namelist){
System.out.println(s1);
}
or
for(i=0;i<namelist.size();i++){
System.out.println(namelist.get(i);
}
Insert an element in a list
add( index, value )
Example
Insert element in third location
namelist.add(2, “Rakesh”);
Delete an element from a list
remove(index)
or
remove(element)
Example
namelist.remove(2);
or
namelist(“Rakesh”);
Retrieve and Modify an element
get(index)
Example
set(index, value)
Example
Example
Collection.sort(namelist);
for(String name:namelist){
System.out.println(name);
}
String
● Strings are a sequence of characters
● Strings are treated as objects that are backed internally by a char array
● Strings are immutable
● Syntax
String variable = “sequence of string”;
or
String variable=new String(“sequence of string”);
● Example
String s1=“String value”; //by literal
String s1=new String(“String value”); //by object
Strings
● String literal
○ While creating string literal, JVM checks in the string constant pool, if already available, it
won‟t create the literal
○ Example
■ String s1=“Java”;
■ String s2=“Java”;
String length
● int length()
s1.length() – returns 16
String compare
● Comparing two string
○ Comparison based on reference (==), content (equals and compareTo)
● equals
○ boolean equals(String)
○ boolean equalsIgnoreCase(String)
String s1=“Java”
String s2=“Java”
String s3=„java”;
● Example
String s1=“Java”;
String s2=“Java”;
String s3=“java”;
String s1=“Java”;
String s2=“Programming”;
String s1=“Java”;
String s2=“Programming”;
String s="hello";
System.out.println(s.substring(2)); //llo
System.out.println(s.substring(0,2)); //he
String class method
● toUpperCase() – change the case into uppercase
● toLowerCase() – change the case into lowercase
● trim() – elliminate white space before and after string
● startsWith(String) and endsWith(String)
String s1=“Hello”;
System.out.println(s1.startsWith(“H”); //true
System.out.println(s1.endsWith(“o”); //true
● charAt(index) – Character at the specified index (index-1)
● valueOf(value) – convert int, long, float, double, boolean, char and char array
into string
● replace(source, target) - replaces all occurrence of source sequence of
character with target sequence of character.
String methods
● contains(CharSequence) - searches the sequence of characters in this string,
returns boolean value, if available true else false
String s1=“Hello how are you”;
System.out.println(s1.contains(“how”)); //true
● getBytes() – returns byte array of the string
String s1="ABCDEFG";
byte[] barr=s1.getBytes();
System.out.println(barr); 65666768697071
● isEmpty() - checks if this string is empty or not. It returns true, if length of
string is 0 otherwise false
split() method
● splits the string against given regular expression and returns a char array
● Example
public class SplitExample{
public static void main(String args[]){
String s1=“this is the example for spilt string";
String[] words=s1.split(“\\s"); //splits the string based on whitespace
for(String w:words){
System.out.println(w);
}
}
}
indexOf() method
● returns index of given character value or substring
○ int indexOf(int ch)
■ returns index position for the given char value and from index
■ returns index position for the given substring and from index