Classes and Objects in Java This work is

Classes and Objects in Java This work is created by N. Senthil madasamy, Dr. A. Noble Mary Juliet, Dr. M. Senthilkumar and is licensed under a Creative Commons Attribution-Share. Alike 4. 0 International License

Class Fundamentals • Classes create objects and objects use methods to communicate between them. • They provide a convenient method for packaging a group of logically related data items and functions that work on them. • A class essentially serves as a template for an object and behaves like a basic data type “int”. • It is therefore important to understand how the fields and methods are defined in a class and how they are used to build a Java program that incorporates the basic OO concepts such as encapsulation, inheritance, and polymorphism. 2

Classes • A class is a collection of fields (data) and methods (procedure or function) that operate on that data. • The basic syntax for a class definition: Circle centre radius circumference() area() class Class. Name { 3 //State (instance variables) // Behaviour(instance methods) // constructors // accessors // mutators // operations/messages }

General Form of a Class class <class-name> { datatype 1 var 1; datatype 2 var 2; return-type method-name 1(arguments) { } return-type method-name 2(arguments) { } } 4

Example: A Complex Number Class • Suppose we want to create and manipulate complex numbers – a complex number is a value of the form: a + bi Addition and Subtraction Multiplication and division

Classes-Example public class Circle { public double x, y; // centre of the circle public double r; // radius of circle //Methods to return circumference and area public double circumference() { return 2*3. 14*r; } public double area() { return 3. 14 * r; } 6 }

Example: A Complex Number Class • States – real and imag • Behaviours – initialize a new complex number – mathematical operations (add two complex numbers, etc. ) – relational operations (equal, not equal, etc. ) – set the values of the real and imaginary parts – get the values of the real and imaginary parts

Implementing a Complex Number Class in Java • An overview of a typical Java implementation, contained in the file Complex. java public class Complex { // State (instance variables) // Behaviour(instance methods) // constructors // accessors // mutators // operations/messages } 8

Implementing State • An object’s state is contained in instance variables // State private double real; private double imag; • Each object created from this class will have separate occurrences of the instance variables 5 + 9 i real = 5 imag = 9 2 + 7 i real = 2 imag = 7

Implementing Behaviour : Constructors • Constructors are methods that describe the initial state of an object created of this class. public Complex() Default Constructor { real = 0. 0; imag = 0. 0; } • Constructors are invoked only when the object is created. They cannot be called otherwise. Complex c 1, c 2, c 3; c 1 = new Complex(); • Constructors initialize the state of an object upon creation. c 1 real = 0 imag = 0 10

Implementing Behaviour : Accessor Methods • Objects often have methods that return information about their state called accessors or getters (because the method name begins with “get”) • get. Real(), get. Imag() returns the real, imag part of the Complex object public double get. Real() { return real; } public double get. Imag() { return imag; } 11

Implementing Behaviour : Mutator Methods • Objects often have methods that change aspects of their state called mutators or setters (because the method name begins with “set”) • set. Real(), set. Imag() changes the real, imag part of the Complex object public void set. Real(double rp) { real = rp; } public void set. Imag(double ip) { imag = ip; } 12

Implementing Behaviour : Operations • Operations or methods used to do some arithmetic or logical operations between state. • Class states may or may not change after its execution • Instead, we define a plus() method as one of the arithmetic operations supported by the Complex class: public Complex plus(Complex c) { Complex sum = new Complex(real + c. real, imag + c. imag); return sum; } c 3 = c 1. plus(c 2);

Implementing Behaviour : Message Passing • Message passing is a form of communication between objects, processes or other resources used in object-oriented programming, • In this model, processes or objects can send and receive messages (signals, functions, complex data structures, or data packets) to other processes or objects. • Objects interact by passing messages to each other • In Java, "message passing“ is performed by calling methods 14

Declaring Objects two-step process Declare a variable of the class type complex c 1; C 1 Acquire an actual, physical copy of the object and assign it to that variable c 1=new Complex(); Complex C 1 Equivalent to, Complex c 1=new Complex();

Assigning Object Reference Variables • Complex C 1=new Complex(); • Complex C 2; • C 2=C 1; C 1 Complex C 2 Complex C 1 C 2 Complex

Garbage Collector § Java handles de-allocation automatically using garbage collection technique. § Java automatically collects garbage periodically and releases the memory used to be used in the future. § If any object does not have a reference and cannot be used in future then that object becomes a candidate for automatic garbage collection. C 2 § Eg: Complex C 2; 17

Accessing Object • Syntax for accessing variable and methods in the class Object. Name. Variable. Name Object. Name. Method. Name(parameter-list) Complex c 1=new Complex(); c 1. real=10; c 1. img=5; //Variable c 1. show(); //method 18

• Complete Complex class available in current folder -file Name: complex. java

Example Write a java program to create a circle class with x , y and r data. And write a method to calculate Area and circumference of the circle.

// Circle. java: Contains both Circle class. Circle and its. Class user class public class Circle { public double x, y; // centre of the circle public double r; // radius of circle //Methods to return circumference and area public double circumference() { return 2*3. 14*r; } public double area() { return 3. 14 * r; } 21
![public static void main(String args[]) Circle Class { Circle a. Circle; // creating reference public static void main(String args[]) Circle Class { Circle a. Circle; // creating reference](http://slidetodoc.com/presentation_image_h2/1d9713e5f9f942c6992ecc2831ea99f0/image-22.jpg)
public static void main(String args[]) Circle Class { Circle a. Circle; // creating reference a. Circle = new Circle(); // creating object a. Circle. x = 10; // assigning value to data field a. Circle. y = 20; a. Circle. r = 5; double area = a. Circle. area(); // invoking method double circumf = a. Circle. circumference(); System. out. println("Radius="+a. Circle. r+" Area="+area +" Circumference ="+circumf); } } output Radius=5. 0 Area=78. 5 Circumference =31. 400 22

Reading user input 1. Command line argument 2. Scanner class 3. buffered. Reader and Input. Stream Reader class 4. Data. Inputstream class 5. Console class 23

1. Command line argument >javac sample. java >java sample Hello welcome class sample { public static void main( String arg[]) throws Exception { System. out. print("The First Argument is: “+ args[0]); System. out. print("The Second Argument is: “+args[1]); } } output ØThe First Arument is : Hello. The Second Argument is : welcome 24

2. Scanner class import java. util. Scanner; Scanner scan = new Scanner(System. in); String s = scan. next(); int i = scan. next. Int(); 3. Buffered. Reader and Input. Stream. Reader classes import java. io. Buffered. Reader; Buffered. Reader br = new Buffered. Reader(new Input. Stream. Reader(System. in)); String s = br. read. Line(); int i = Integer. parse. Int(br. read. Line()); 25

4. Data. Input. Stream class import java. io. Data. Input. Stream; Data. Input. Stream dis = new Data. Input. Stream(System. in); int i = dis. read. Int(); 5. Console class import java. io. Console; Console console = System. console(); String s = console. read. Line(); int i = Integer. parse. Int(console. read. Line()); 26

METHOD 27

METHOD • A collection of statements that are grouped together to perform an operation • A method definition consists of a method header and a method body. • A method has the following syntax modifier return_Type Method_Name (list of parameters) { // Method body; }

• Method Name – The actual name of the method. – Method name and the parameter list together constitute the method signature. • Parameters – Act as a placeholder. – When a method is invoked, a value is passed to parameter. – This value is referred to as actual parameter or argument. – The parameter list refers to the type, order, and number of the parameters of a method. – Parameters are optional; that is,

Methods A method is a collection of statements that are grouped together to perform an operation. It has two parts 1. Define Method üMethod header üMethod Body 2. Invoke Method ü Method name ü Local Parameters

Method header 1. Modifier 2. return type 3. method signature-Method signature is the combination of the method name and the parameter list. • Method name • Formal Parameter-The variables defined in the method header

Method Body Method body contains group of statements and with or with out return value. A method may return a value. The return. Value. Type is the data type of the value the method returns. If the method does not return a value, the return. Value. Type is the keyword void. For example, the return. Value. Type in the main method is void.

Invoke Methods can be invoke by calling the methods with method name and actual parameters.

Calling Methods Testing the max method This program demonstrates calling a method max to return the largest of the int values 34

Trace Method Invocation i is now 5 35

Trace Method Invocation j is now 2 36

Trace Method Invocation invoke max(i, j) 37

Trace Method Invocation invoke max(i, j) Pass the value of i to num 1 Pass the value of j to num 2 38

Trace Method Invocation declare variable result 39

Trace Method Invocation (num 1 > num 2) is true since num 1 is 5 and num 2 is 2 40

Trace Method Invocation result is now 5 41

Trace Method Invocation return result, which is 5 42

Trace Method Invocation return max(i, j) and assign the return value to k 43

Trace Method Invocation Execute the print statement 44

void Method Example This type of method does not return a value. The method performs some actions. void show() { System. out. println(“hai”); } 45

• Difference between Parameter and Argument ? – Parameter is a variable defined by the method that receives a value when the method is called. – Argument is a value that is passes to a method when it is invoked 46

Constructor 47

Constructor in Java Constructor is a special member method which will be called automatically when you create an object of any class. The main purpose of using constructor is to initialize an object. Syntax class. Name() {. . . }

Advantages of constructors in Java • A constructor eliminates placing the default values. • A constructor eliminates calling the normal or ordinary method implicitly.

How Constructor eliminate default values ? • Constructor are mainly used for eliminate default value, whenever you create object of any class then it allocate memory of variable and store or initialized default value. • Using constructor we initialized our own value in variable.


class Sum { public int a, b; Example Sum() { a=10; b=20; } public static void main(String s[]) { Sum s=new Sum(); Output 30 int c= s. a + s. b; System. out. println("Sum: "+c); }

Properties of constructor • Constructor will be called automatically when the object is created. • Constructor name must be similar to name of the class. • Constructor should not return any value even void also. Because basic aim is to place the value in the object • Constructor definitions should not be static. Because constructors will be called each and every time, whenever an object is creating. • Constructor should not be private provided an object of one class is created in another • Constructors will not be inherited from one class to another class

There are two types of constructors:

Default Constructor • A constructor is said to be default constructor if and only if it never take any parameters. • If any class does not contain at least one user defined constructor than the system will create a default constructor at the time of compilation it is known as system defined default constructor. Syntax class. Name { classname () { block of statements; // Initialization } }

class Test { int a, b; Test () { System. out. println("I am from default Constructor. . . "); a=10; b=20; System. out. println("Value of a: "+a); System. out. println("Value of b: "+b); } public static void main(String [] args) { Test t 1=new Test (); Output: } I am from default Constructor. . . Value of a: 10 } Value of b: 20


Important points Related to default constructor • Whenever we create an object only with default constructor, defining the default constructor is optional. • If we are not defining default constructor of a class, then JVM will call automatically system defined default constructor. • If we define, JVM will call user defined default constructor. Purpose of default constructor? • Default constructor provides the default values to the object like 0, 0. 0, null etc. depending on their type (for integer 0, for string null).

Example of default constructor that displays the default values class Student { int roll; float marks; String name; void show() { System. out. println("Roll: "+roll); System. out. println("Marks: "+marks); System. out. println("Name: "+name); } public static void main(String [] args) { Student s 1=new Student(); s 1. show(); } } Output Roll: 0 Marks: 0. 0 Name: null Explanation: In the above class, we are not creating any constructor so compiler provides a default constructor. Here 0, 0. 0 and null values are provided by default constructor.

Parameterized constructor • If any constructor contain list of variable in its signature is known as parameterized constructor. A parameterized constructor is one which takes some parameters. Syntax class Class. Name {. . . . Class. Name(list of parameters) {. . . } Class. Name objectname=new Class. Name(value 1, value 2, . . . );

Example of Parameterized Constructor class Test { int a, b; Test(int n 1, int n 2) { a=n 1; b=n 2; } void show() { System. out. println("Value of a = "+a); System. out. println("Value of b = "+b); } public static void main(String k []) { Test t 1=new Test(33, 55); t 1. show(); } } Output Value of a=33 Value fo b=55


• Important points Related to Parameterized Constructor • Whenever we create an object using parameterized constructor, it must be define parameterized constructor otherwise we will get compile time error. • Whenever we define the objects with respect to both parameterized constructor and default constructor, It must be define both the constructors. • In any class can have one default constructor and N number of parameterized constructors.

Constructor Overloading • Constructor overloading is a technique in Java in which a class can have any number of constructors that differ in parameter lists. • The compiler differentiates these constructors by taking the number of parameters, and their type. • In other words whenever same constructor is existing multiple times in the same class with different number of parameters or order of parameters or type of parameters is known as Constructor overloading. • In general constructor overloading can be used to initialized same or different objects with different values.

Constructor Overloading Syntax class Class. Name { Class. Name() {. . . . . } Class. Name(datatype 1 value 1) {. . . . } Class. Name(datatype 1 value 1, datatype 2 value 2) {. . . . } Class. Name(datatype 2 variable 2) {. . . . } Class. Name(datatype 2 value 2, datatype 1 value 1) {. . . . }

Example of overloaded constructor class Test { int a, b; Test () { System. out. println("I am from default Constructor. . . "); a=1; b=2; } Test (int x, int y) { System. out. println("I am from double Parameterized Constructor"); a=x; b=y; } Test (int x) { System. out. println("I am from single Parameterized Constructor"); a=x; b=x; } Test (Test T) { System. out. println("I am from Object Parameterized Constructor. . . "); a=T. a; b=T. b; } void show() { System. out. println("Value of a ="+a); System. out. println("Value of b ="+b); } public static void main (String k []) { Test t 1=new Test (); t 1. show(); Test t 2=new Test (10, 20); t 2. show(); Test t 3=new Test (1000); t 3. show(); Test t 4=new Test (t 1); } t 4. show(); } }

Difference between Method and Constructor Method can be any user defined name Method should have return type Constructor must be class name It should not have any return type (even void) Method should be called explicitly It will be called automatically either with object reference or whenever object is created class reference Method is not provided by The java compiler provides a compiler in any case. default constructor if we do not have any constructor.

Java Array • Array is a collection of similar type of elements that have contiguous memory location. • Java array is an object the contains elements of similar data type. It is a data structure where we store similar elements. We can store only fixed set of elements in a java array. • Array in java is index based, first element of the array is stored at 0 index.

Java Array

Java Array • Advantage of Java Array – Code Optimization: It makes the code optimized, we can retrieve or sort the data easily. – Random access: We can get any data located at any index position. • Disadvantage of Java Array – Size Limit: We can store only fixed size of elements in the array. It doesn't grow its size at runtime. To solve this problem, collection framework is used in java.

Types of Array • There are two types of array. – Single Dimensional Array – Multidimensional Array

Types of Array in java Single Dimensional Array in java Syntax to Declare an Array in java – data. Type[] arr; (or) – data. Type []arr; (or) – data. Type arr[]; Instantiation of an Array in java – array. Ref. Var=new datatype[size];
![Types of Array class Testarray{ public static void main(String args[]){ int a[]=new int[5]; //declaration Types of Array class Testarray{ public static void main(String args[]){ int a[]=new int[5]; //declaration](http://slidetodoc.com/presentation_image_h2/1d9713e5f9f942c6992ecc2831ea99f0/image-73.jpg)
Types of Array class Testarray{ public static void main(String args[]){ int a[]=new int[5]; //declaration and instantiation a[0]=10; //initialization a[1]=20; a[2]=70; a[3]=40; a[4]=50; //printing array for(int i=0; i<a. length; i++)//length is the property of array System. out. println(a[i]); } }
![Types of Array int a[]={33, 3, 4, 5}; a[0]=33 a[1]=3 a[2]=4 a[3]=5; Types of Array int a[]={33, 3, 4, 5}; a[0]=33 a[1]=3 a[2]=4 a[3]=5;](http://slidetodoc.com/presentation_image_h2/1d9713e5f9f942c6992ecc2831ea99f0/image-74.jpg)
Types of Array int a[]={33, 3, 4, 5}; a[0]=33 a[1]=3 a[2]=4 a[3]=5;
![Types of Array class Testarray 2{ static void min(int arr[]){ int min=arr[0]; for(int i=1; Types of Array class Testarray 2{ static void min(int arr[]){ int min=arr[0]; for(int i=1;](http://slidetodoc.com/presentation_image_h2/1d9713e5f9f942c6992ecc2831ea99f0/image-75.jpg)
Types of Array class Testarray 2{ static void min(int arr[]){ int min=arr[0]; for(int i=1; i<arr. length; i++) if(min>arr[i]) min=arr[i]; System. out. println(min); } public static void main(String args[]){ int a[]={33, 3, 4, 5}; min(a); //passing array to method }}
![Multidimensional array Syntax to Declare Multidimensional Array in java • data. Type[][] array. Ref. Multidimensional array Syntax to Declare Multidimensional Array in java • data. Type[][] array. Ref.](http://slidetodoc.com/presentation_image_h2/1d9713e5f9f942c6992ecc2831ea99f0/image-76.jpg)
Multidimensional array Syntax to Declare Multidimensional Array in java • data. Type[][] array. Ref. Var; (or) • data. Type [][]array. Ref. Var; (or) • data. Type array. Ref. Var[][]; (or) • data. Type []array. Ref. Var[]; • int[][] arr=new int[3][3]; //3 row and 3 column
![class Testarray 3{ public static void main(String args[]){ //declaring and initializing 2 D array class Testarray 3{ public static void main(String args[]){ //declaring and initializing 2 D array](http://slidetodoc.com/presentation_image_h2/1d9713e5f9f942c6992ecc2831ea99f0/image-77.jpg)
class Testarray 3{ public static void main(String args[]){ //declaring and initializing 2 D array int arr[][]={{1, 2, 3}, {2, 4, 5}, {4, 4, 5}}; //printing 2 D array for(int i=0; i<3; i++){ for(int j=0; j<3; j++){ System. out. print(arr[i][j]+" "); } System. out. println(); } }}

Copying a java array • We can copy an array to another by the arraycopy method of System class. Syntax of arraycopy method public static void arraycopy( Object src, int src. Pos, Object dest, int dest. Pos, int length )
![Copying a java array class Test. Array. Copy. Demo { public static void main(String[] Copying a java array class Test. Array. Copy. Demo { public static void main(String[]](http://slidetodoc.com/presentation_image_h2/1d9713e5f9f942c6992ecc2831ea99f0/image-79.jpg)
Copying a java array class Test. Array. Copy. Demo { public static void main(String[] args) { char[] copy. From = { 'd', 'e', 'c', 'a', 'f', 'e', 'i', 'n', 'a', 't', 'e', 'd' }; char[] copy. To = new char[7]; System. arraycopy(copy. From, 2, copy. To, 0, 7); For(i=0; i<=7 i++) System. out. println(copy. To[i]); } }

For-each loop (Advanced or Enhanced For loop): Advantage of for-each loop: • It makes the code more readable. • It elimnates the possibility of programming errors. • Syntax – for(data_type variable : array | collection){}

For-each loop (Advanced or Enhanced For loop): class For. Each. Example 1{ public static void main(String args[]){ int arr[]={12, 13, 14, 44}; for(int i: arr){ System. out. println(i); } } }

• Excerice – Create a student class with Name, no and 8 marks. – Read data from user and calculate average and class display in to screen – student. java file available in current folder.

Method Overloading • Methods of the same name can be declared in the same class, as long as they have different sets of parameters (determined by the number, types and order of the parameters) – this is called method overloading. • When an overloaded method is called, the Java compiler selects the appropriate method by examining the number, types and order of the arguments in the call. • Method overloading is commonly used to create several methods with the same name that perform the same or similar tasks, but on different types or different numbers of arguments.

Syntax classname { Returntype method() {. . . . } Returntype method(datatype 1 variable 1, datatype 2 variable 2) {. . } Returntype method(datatype 2 variable 2, datatype 1 variable 1) {. . } }

Different ways to overload the method • There are two ways to overload the method in java – By changing number of arguments or parameters – By changing the data type

By changing number of arguments • In this example, we have created two overloaded methods, first sum method performs addition of two numbers and second sum method performs addition of three numbers class Addition { void sum(int a, int b) { System. out. println(a+b); } void sum(int a, int b, int c) { System. out. println(a+b+c); } public static void main(String args[]) { Addition obj=new Addition(); obj. sum(10, 20, 30); } } Output 30 60

By changing the data type • In this example, we have created two overloaded methods that differs in data type. The first sum method receives two integer arguments and second sum method receives two float arguments. class Addition { void sum(int a, int b) { System. out. println(a+b); } void sum(float a, float b) { System. out. println(a+b); } public static void main(String args[]) { Addition obj=new Addition(); obj. sum(10, 20); obj. sum(10. 5, 20. 54); } } Output 30 31. 04

Can we overload main() method ? • Yes, We can overload main() method. • A Java class can have any number of main() methods. But run the java program, which class should have main() method with signature as "public static void main(String[] args)”. • If you do any modification to this signature, compilation will be successful. But, not run the java program. we will get the run time error as main method not found.

Access Modifiers 89

Access Modifiers in Java • Access modifiers are those which are applied before data members or methods of a class. These are used to where to access and where not to access the data members or methods. In Java programming these are classified into four types: – Private – Default (not a keyword) – Protected – Public

Access Modifiers in Java • Default is not a keyword (like public, private, protected are keyword) • If we are not using private, protected and public keywords, then JVM is by default taking as default access modifiers. • Access modifiers are always used for, how to reuse the features within the package and access the package between class to class, interface to interface and interface to a class. • Access modifiers provide features accessing and controlling mechanism among the classes and interfaces.

private • Private members of class in not accessible anywhere in program these are only accessible within the class. Private are also called class level access modifiers class Hello { private int a=20; private void show() { System. out. println("Hello java"); } } public class Demo { public static void main(String args[]) { Hello obj=new Hello(); System. out. println(obj. a); //Compile Time Error, you can't access private data obj. show(); //Compile Time Error, you can't access private methods } }.

public • Public members of any class are accessible anywhere in the program inside the same class and outside of class, within the same package and outside of the package. Public are also called universal access modifiers. class Hello { public int a=20; public void show() { System. out. println("Hello java"); } } public class Demo { public static void main(String args[]) { Hello obj=new Hello(); System. out. println(obj. a); obj. show(); } }. Output 20 Hello Java

protected • Protected members of the class are accessible within the same class and another class of the same package and also accessible in inherited class of another package. Protected are also called derived level access modifiers. public class A { protected void show() { System. out. println("Hello Java"); } } class B extends A { public static void main(String args[]) { B obj = new B(); obj. show(); } } Output Hello Java

Default: • Default members of the class are accessible only within the same class and another class of the same package. The default are also called package level access modifiers. //save by A. java package pack; class A { void show() { System. out. println("Hello Java"); } } //save by B. java package pack; Class B{ public static void main(String args[]) { A obj = new A(); obj. show(); } Output Hello Java //save by C. java package pack 2; import pack 1. *; class C { public static void main(String args[]) { A obj = new A(); //Compile Time Error, can't access outside the package obj. show(); //Compile Time Error, can't access outside the package }

Access Modifiers in Java

Rules for access modifiers: • The following diagram gives rules for Access modifiers.

Inheritance

Inheritance • One of the most effective features of Oop’s paradigm. • Establish a link/connectivity between 2 or more classes. • Permits sharing and accessing properties from one to another class. • SW industry requirement – Quick, Correct, Economic- • It apply only it have IS-A relation between classes

Inheritance Motivation • Inheritance in Java is achieved through extending classes Inheritance enables: • Code re-use • Grouping similar code • Flexibility to customize

Inheritance Motivation Paper. Book ISBN Title Author Price Shipping Price Stock EBook ISBN Title Author Price URL Size

Inheritance Concepts • Many real-life objects are related in a hierarchical fashion such that lower levels of the hierarchy inherit characteristics of the upper levels. e. g. , vehicle car Honda Accord person employee faculty member • These types of hierarchies/relationships may be called IS-A (e. g. , a car is-a vehicle).

IS A • • Cylinder is a type of circle Book is a type of page Horse is a type of vehicle Ice is a type of water Vapor is a type of water Water is a type of Gas House fly is a type of bird Student is a type of employee

IS A • • Cylinder is a type of circle Book is a type of page Horse is a type of vehicle Ice is a type of water Vapor is a type of water Water is a type of Gas House fly is type of bird Student is a type of employee

Super Sub class

• Every object of a class holds one copy of the instance of the class • Incase of inheritance , Every object of inherited object holds not only the copy of instance of the class also holds all the copy of instance of all its super classes.

Grand Dad Son Grand Son Property -A Property –B Property –C Property -D Grand son A, B, C, D Son A, B, C Dad A, B Grand Dad A

Over head Class A Class B 10 laks/15 laks A, B, C, D, E, F, G, H, I, J A, B, C D, E, F, G, H, J, i A, B, C X, Y, Z

Inheritance Concepts - Hierarchy • The inheritance hierarchy is usually drawn as an inverted (upside-down) tree. • The tree can have any number of levels. • The class at the top (base) of the inverted tree is called the root class. • In Java, the root class is called Object.

Inheritance Concepts - Hierarchy

Category of Classes on the Basis of Inheritance Super class (base/parentclass). Child class (sub/associate/inherited class).

Object Root Class • The Object root class provides the following capabilities to all Java objects: – Event handling - synchronizing execution of multiple executable objects (e. g. , a print spooler and a printer driver) – Cloning – creating an exact copy of an object – Finalization – cleaning up when an object is no longer needed

Inheritance Concepts - Terms • OOP languages provide specific mechanisms for defining inheritance relationships between classes. • Derived (Child) Class - a class that inherits characteristics of another class. • Base (Parent) Class - a class from which characteristics are inherited by one or more other classes. • A derived class inherits data and function members from ALL of its base classes.

Inheritance Concepts - Example

Inheritance - Embedded Objects < Think of each derived class object as having a base class object embedded within it.

Java Inheritance Declarations • No special coding is required to designate a base class, e. g. , class Employee { … } • A derived class must specifically declare the base class from which it is derived class-name extends baseclass-name { //methods and fields } Eg: class Hourly. Employee extends Employee { … }

Vehicle String color; int speed; int size; Display() int CC; int gears; Expected Output Color of Car : Blue Speed of Car : 200 Size of Car : 22 CC of Car : 1000 No of gears of Car : 5 Car displaycar()

// A class to display the attributes of the vehicle class Vehicle { String color; int speed; int size; void display() { System. out. println("Color : " + color); System. out. println("Speed : " + speed); System. out. println("Size : " + size); } } // A subclass which extends for vehicle class Car extends Vehicle { int CC; int gears; void displaycar() {System. out. println("Color of Car : " + color); System. out. println("Speed of Car : " + speed); System. out. println("Size of Car : " + size); System. out. println("CC of Car : " + CC); System. out. println("No of gears of Car : " + gears); } } public class Test { public static void main(String a[]) { Car b 1 = new Car(); b 1. color = "Blue"; b 1. speed = 200 ; b 1. size = 22; b 1. CC = 1000; b 1. gears = 5; b 1. displaycar(); } }

protected Members • protected access members – Between public and private in protection – Accessed only by • Superclass methods • Subclass methods • Methods of classes in same package

Inheritance - Constructor Functions • When an object of a derived class is created, the constructor functions of the derived class and all base classes are also called. – In what order are constructor functions called and executed? – How are parameters passed to base class constructor functions?

Constructor Function Calls

Constructor Function Calls A B C

Constructor Function Calls class A { A() { System. out. println("One"); } } class B extends A { B() { System. out. println("Two"); } } class C extends B { C() { System. out. println("Three"); } } class Constuctor. Order 1 { public static void main(String args[]) { C XX= new C(); } } OUTPUT : One Two Three

Types of inheritance • • • Single Inheritance. Multiple Inheritance (Through Interface) Multilevel Inheritance. Hierarchical Inheritance. Hybrid Inheritance (Through Interface)


Cant direct implement with help of interface

Types of inheritance • Multi-level inheritance is allowed in Java but not multiple inheritance

The keyword super • The super keyword in java is a reference variable which is used to refer immediate parent class object. • Whenever you create the instance of subclass, an instance of parent class is created implicitly which is referred by super reference variable. Usage of java super Keyword – super can be used to refer immediate parent class instance variable. – super can be used to invoke immediate parent class method. – super() can be used to invoke immediate parent class constructor.

super is used to refer immediate parent class instance variable Animal color Dog color Output: black class Animal{ String color="white"; } class Dog extends Animal{ String color="black"; void print. Color(){ System. out. println(color); //prints color of Dog } } class Test. Super 1{ public static void main(String args[]){ Dog d=new Dog(); d. print. Color(); }}

super is used to refer immediate parent class instance class Animal{ variable Animal color Dog color Output: black white String color="white"; } class Dog extends Animal{ String color="black"; void print. Color(){ System. out. println(color); //prints color of Dog System. out. println(super. color); // color of Animal } } class Test. Super 1{ public static void main(String args[]){ Dog d=new Dog(); d. print. Color(); }}

super can be used to invoke parent class method Animal eat() Dog work() Output: eating class Animal{ void eat(){System. out. println("eating. . . "); } } class Dog extends Animal{ void work(){ super. eat(); } } class Test. Super 2{ public static void main(String args[]){ Dog d=new Dog(); d. work(); }}

• Parameterized Constructor using Super When an object is created: – only one constructor function is called – parameters are passed only to that constructor function – Animal String Name String Owner Animal(String, String) Dog int age Dog() • Dog d=new Dog(“Dog”, ”XXX”, 15); • But the first two parameters “belong” to the base class (Animal) constructor function. • How can those parameters be passed to the Animal constructor function?

Parameterized Constructor using Super The keyword super enables parameter passing between derived and base class constructor functions For example, the following code passes the first two parameters from the Dog constructor function to the Animal constructor function: public Dog( String N, String O, int a){ super(N, O); age=a; } Dog d=new Dog(“Dog”, ”XXX”, 15);

What is difference between super and super() in Java? • super with variables and methods: super is used to call super class variables and methods by the subclass object when they are overridden by subclass. • super() with constructors: super() is used to call super class constructor from subclass constructor.

Method Overriding • When a method in a subclass has the same name and type signature as a method in its superclass, – Then the method in the subclass is said to override the method in the superclass. – No need of differences in argument type/number 137

Member Override • When a member of a derived class has the same name as a member of a base class the derived class member is said to override the base class member. (Or ) • If subclass (child class) has the same method as declared in the parent class, it is known as method overriding in java. • The derived class member “hides” the base class member unless a qualified name is used. • Both the base and derived class implementations of the overridden data or function member exist within each derived class object.

Member Override Usage of Java Method Overriding • Method overriding is used to provide specific implementation of a method that is already provided by its super class. • Method overriding is used for runtime polymorphism Rules for Java Method Overriding • method must have same name as in the parent class • must be IS-A relationship (inheritance).

Method overriding Vehicle run() Bike Output: Vehicle is running class Vehicle{ void run(){System. out. println("Vehicle is running"); } } public class Bike extends Vehicle{ public static void main(String args[]){ Bike obj = new Bike(); obj. run(); } } }

Method overriding Vehicle run() Bike run() Output: Bike is running safely class Vehicle{ void run(){System. out. println("Vehicle is running"); } } public class Bike extends Vehicle{ void run(){System. out. println("Bike is running safely"); } public static void main(String args[]){ Bike obj = new Bike(); obj. run(); } } }

class A { } void show() { System. out. println("Inside A's show"); } class B extends A { void show() { System. out. println("Inside B's show"); } } class sample { public static void main(String arg[]) { C cc=new C(); cc. show(); } } class C extends B { void show() { System. out. println("Inside C's show"); } } 142

class A { } void show() { System. out. println("Inside A's show"); } class B extends A { void show() { super. show(); System. out. println("Inside B's show"); } } class C extends B { void show() { super. show(); System. out. println("Inside C's show"); } } class sample { public static void main(String arg[]) { C cc=new C(); cc. show(); } } 143

class A { } void show() { System. out. println("Inside A's show; No arguments"); } class B extends A { void show(String a) { System. out. println("Inside B's show; 1 argument "+a); } } class C extends B { void show(String a, String b) { System. out. println("Inside C's show; 2 arguments "+a+" "+b); } } 144
![class sample { public static void main(String arg[]) { C cc=new C(); cc. show(); class sample { public static void main(String arg[]) { C cc=new C(); cc. show();](http://slidetodoc.com/presentation_image_h2/1d9713e5f9f942c6992ecc2831ea99f0/image-143.jpg)
class sample { public static void main(String arg[]) { C cc=new C(); cc. show(); } } cc. show(“Hello”); cc. show(“Hello”, “World”, “Nice”); 145

Dynamic Method Dispatch • Dynamic method dispatch is the mechanism by which a call to an overridden method is resolved at run time, rather than compile time • This is called as Run-time Polymorphism 146

class A { } void show() { System. out. println("Inside A's show"); } class B extends A { void show() { System. out. println("Inside B's show"); } } class C extends B { void show() { System. out. println("Inside C's show"); } } class sample { public static void main(String arg[]) { A aa=new A(); B bb=new B(); C cc=new C(); A rr; rr=aa; rr. show(); rr=bb; rr. show(); rr=cc; rr. show(); } } 147

method overloading and method overriding in java Method Overloading Method Overriding Method overloading is used to Method overriding is used to provide increase the readability of the specific implementation of the program. method that is already provided by its super class. Method overloading is Method overriding occurs in two performed within classes that have IS-A (inheritance) relationship. In case of method overloading, parameter must be overriding, parameter must be same. different. Method overloading is example of compile polymorphism. the Method overriding is the example of run time polymorphism. In java, method overloading can't Return type must be same be performed by changing return covariant in method overriding. type of the method only. Return type can be same or different in method overloading. But you must have to change the parameter. or

Difference between method overloading and method overriding in java Example for overloading class Overloading. Example{ static int add(int a, int b){return a+b; } static int add(int a, int b, int c){return a+b+c; } } Example for overriding class Animal{ void eat(){System. out. println("eating. . . "); } } class Dog extends Animal{ void eat(){System. out. println("eating bread. . . ") ; } }
- Slides: 147