Presentation is loading. Please wait.

Presentation is loading. Please wait.

Classes and Objects in Java

Similar presentations


Presentation on theme: "Classes and Objects in Java"— Presentation transcript:

1 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-ShareAlike 4.0 International License

2 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.

3 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 ClassName { //State (instance variables) // Behaviour(instance methods) // constructors // accessors // mutators // operations/messages }

4 General Form of a Class class <class-name> { datatype1 var1; datatype2 var2; return-type method-name1(arguments) { } return-type method-name2(arguments) }

5 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

6 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 * r;

7 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

8 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 } Description The first look at the complex class Important Points Identify the typical organisation of a class Object state is in the instance variables (data) Object behaviour is in the instance methods of the class The types of methods that you typically have include …

9 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 Description The first look at the complex class Important Points Object state is in the instance variables : real and imag Object behaviour is in the instance methods of the class So far, all we have is the default constructor that initialises the state. real = 5 imag = 9 real = 2 imag = 7 5 + 9i 2 + 7i

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

11 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”) getReal(), getImag() returns the real,imag part of the Complex object public double getReal() { return real; } public double getImag() return imag; Description : Now we are leading them into typical structure of well-designed classes.

12 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”) setReal(),setImag() changes the real,imag part of the Complex object public void setReal(double rp) { real = rp; } public void setImag(double ip) imag = ip; Answer : Follow the format of the constructors. setComplex (double rp) { real=rp; imag=0} setComplex (double rp, double ip) { real=rp; imag=ip}

13 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; } c3 = c1.plus(c2);

14 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

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

16 Assigning Object Reference Variables
Complex C1=new Complex(); Complex C2; C2=C1; C1 Complex C2 C1 Complex C2 Complex

17 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. Eg: Complex C2; C2

18 Accessing Object Syntax for accessing variable and methods in the class ObjectName.VariableName ObjectName.MethodName(parameter-list) Complex c1=new Complex(); c1.real=10; c1.img=5;//Variable c1.show();//method

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

20 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.

21 // Circle.java: Contains both Circle class and its 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 * r; Circle Class

22 Circle Class public static void main(String args[]) {
Circle aCircle; // creating reference aCircle = new Circle(); // creating object aCircle.x = 10; // assigning value to data field aCircle.y = 20; aCircle.r = 5; double area = aCircle.area(); // invoking method double circumf = aCircle.circumference(); System.out.println("Radius="+aCircle.r+" Area="+area +" Circumference ="+circumf); } Circle Class output Radius=5.0 Area=78.5 Circumference =31.400

23 Reading user input Command line argument Scanner class bufferedReader and InputStream Reader class DataInputstream class Console class

24 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 : HelloThe Second Argument is :welcome

25 2. Scanner class import java. util
2.Scanner class import java.util.Scanner; Scanner scan = new Scanner(System.in); String s = scan.next(); int i = scan.nextInt(); 3.BufferedReader and InputStreamReader classes import java.io.BufferedReader; BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String s = br.readLine(); int i = Integer.parseInt(br.readLine());

26 4. DataInputStream class import java. io
4.DataInputStream class import java.io.DataInputStream; DataInputStream dis = new DataInputStream(System.in); int i = dis.readInt(); 5.Console class import java.io.Console; Console console = System.console(); String s = console.readLine(); int i = Integer.parseInt(console.readLine());

27 METHOD

28 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; }

29 Method Name Parameters 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,

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

31 Method header Modifier return type
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

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

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

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

35 Trace Method Invocation
i is now 5

36 Trace Method Invocation
j is now 2

37 Trace Method Invocation
invoke max(i, j)

38 Trace Method Invocation
invoke max(i, j) Pass the value of i to num1 Pass the value of j to num2

39 Trace Method Invocation
declare variable result

40 Trace Method Invocation
(num1 > num2) is true since num1 is 5 and num2 is 2

41 Trace Method Invocation
result is now 5

42 Trace Method Invocation
return result, which is 5

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

44 Trace Method Invocation
Execute the print statement

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

46 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

47 Constructor

48 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 className() { }

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

50 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.

51

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

53 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

54 There are two types of constructors:
Default constructor (no-arg constructor) Parameterized constructor There are two types of constructors:

55 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 className { classname () block of statements; // Initialization }

56 class Test { int a, b; Test () System. out
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 t1=new Test (); Output: I am from default Constructor... Value of a: 10 Value of b: 20

57

58 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).

59 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 s1=new Student(); s1.show(); } 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. Output Roll: 0 Marks: 0.0 Name: null

60 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 ClassName { ClassName(list of parameters) { } ClassName objectname=new ClassName(value1, value2,.....);

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

62

63 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.

64 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.

65 Constructor Overloading
Syntax class ClassName { ClassName() { } ClassName(datatype1 value1) { } ClassName(datatype1 value1, datatype2 value2) { } ClassName(datatype2 variable2) { } ClassName(datatype2 value2, datatype1 value1) { } }

66 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 t1=new Test (); t1.show(); Test t2=new Test (10, 20); t2.show(); Test t3=new Test (1000); t3.show(); Test t4=new Test (t1); } t4.show();

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

68 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.

69 Java Array

70 Java Array Advantage of Java Array Disadvantage 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.

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

72 Types of Array in java Single Dimensional Array in java
Syntax to Declare an Array in java dataType[] arr; (or)   dataType []arr; (or)   dataType arr[];  Instantiation of an Array in java arrayRefVar=new datatype[size];  

73 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]); } }

74 Types of Array int a[]={33,3,4,5}; a[0]=33 a[1]=3 a[2]=4 a[3]=5;

75 Types of Array class Testarray2{ 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 }}

76 Multidimensional array
Syntax to Declare Multidimensional Array in java dataType[][] arrayRefVar; (or)   dataType [][]arrayRefVar; (or)   dataType arrayRefVar[][]; (or)   dataType []arrayRefVar[]; int[][] arr=new int[3][3];//3 row and 3 column

77 class Testarray3{ public static void main(String args[]){ //declaring and initializing 2D array int arr[][]={{1,2,3},{2,4,5},{4,4,5}}; //printing 2D array for(int i=0;i<3;i++){ for(int j=0;j<3;j++){ System.out.print(arr[i][j]+" "); } System.out.println(); } }}

78 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 srcPos,Object dest, int destPos, int length  )  

79 Copying a java array class TestArrayCopyDemo { public static void main(String[] args) { char[] copyFrom = { 'd', 'e', 'c', 'a', 'f', 'f', 'e', 'i', 'n', 'a', 't', 'e', 'd' }; char[] copyTo = new char[7]; System.arraycopy(copyFrom, 2, copyTo, 0, 7); For(i=0;i<=7i++) System.out.println(copyTo[i]); } }

80 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){}  

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

82 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.

83 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.

84 Syntax class classname { Returntype method() {
Syntax class classname { Returntype method() { } Returntype method(datatype1 variable1) { } Returntype method(datatype1 variable1, datatype2 variable2) {..} Returntype method(datatype2 variable2) { } Returntype method(datatype2 variable2, datatype1 variable1) {..} }

85 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

86 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); obj.sum(10, 20, 30); } Output 30 60

87 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) public static void main(String args[]) { Addition obj=new Addition(); obj.sum(10, 20); obj.sum(10.5, 20.54); } Output 30 31.04

88 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.

89 Access Modifiers

90 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

91 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.

92 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 }.

93 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

94 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

95 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 B.java package pack; Class B{ public static void main(String args[]) { A obj = new A(); obj.show(); } Output Hello Java //save by A.java package pack; class A { void show() { System.out.println("Hello Java"); } //save by C.java package pack2; import pack1.*; 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 }

96 Access Modifiers in Java

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

98 Inheritance

99 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

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

101 Inheritance Motivation
PaperBook ISBN Title Author Price Shipping Price Stock PaperBook ISBN Title Author Price Shipping Price Stock EBook ISBN Title Author Price URL Size EBook ISBN Title Author Price URL Size

102 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).

103 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

104 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

105 Size of Super and Sub classes

106 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.

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

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

109 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.

110 Inheritance Concepts - Hierarchy

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

112 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

113 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.

114 Inheritance Concepts - Example

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

116 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 derived class-name extends baseclass-name   {      //methods and fields   }   Eg: class HourlyEmployee extends Employee { … }

117 Vehicle String color; int speed; int size; Display() 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 int CC; int gears; displaycar()

118 // 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); } public class Test { public static void main(String a[]) { Car b1 = new Car(); b1.color = "Blue"; b1.speed = 200 ; b1.size = 22; b1.CC = 1000; b1.gears = 5; b1.displaycar(); } // 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); }

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

120 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?

121 Constructor Function Calls

122 Constructor Function Calls
B A

123 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 ConstuctorOrder1 {     public static void main(String args[])     {    C XX= new C();    } } OUTPUT : One Two Three

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

125

126 Cant direct implement with help of interface

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

128 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.

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

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

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

132 Parameterized Constructor using Super
When an object is created: only one constructor function is called parameters are passed only to that constructor function 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? Animal String Name String Owner Animal(String,String) Dog int age Dog()

133 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);

134 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.

135 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

136 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.

137 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).

138 Method overriding Output: Vehicle is running Vehicle run() Bike
class 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();     }   }    Bike Output: Vehicle is running

139 Method overriding Output: Bike is running safely Vehicle run() Bike
class 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();     }   }    Bike run() Output: Bike is running safely

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

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

142 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);

143 class sample { public static void main(String arg[]) C cc=new C(); } cc.show(); cc.show(“Hello”); cc.show(“Hello”, “World”); cc.show(“Hello”, “World”, “Nice”);

144 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

145 class A { void show() System.out.println("Inside A's show"); } class B extends A System.out.println("Inside B's show"); class C extends B 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=cc; }

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

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


Download ppt "Classes and Objects in Java"

Similar presentations


Ads by Google