Java Unit 2 (2025) PDF
Document Details
Uploaded by UnrivaledPolarBear
VNSGU
Dr. Darshna Rajput
Tags
Summary
This document provides introductory notes on Java classes and objects. It covers syntax, object creation, and instance variables in Java classes. It's a useful resource for understanding core object-oriented programming concepts in Java.
Full Transcript
Unit 2 – Classes and Objects 2.1 Simple Class, Field 2.2 Access Controls, Object creation 2.3 Construction and Initialization 2.4 Inheritance and Polymorphism in Java 2.4.1 Data encapsulation, overriding and overloading methods 2.5 this and super keywords 2.6 Static members...
Unit 2 – Classes and Objects 2.1 Simple Class, Field 2.2 Access Controls, Object creation 2.3 Construction and Initialization 2.4 Inheritance and Polymorphism in Java 2.4.1 Data encapsulation, overriding and overloading methods 2.5 this and super keywords 2.6 Static members, static block, static class 2.7 Interfaces: 2.7.1 Introduction to Interfaces, Interface Declaration. 2.7.2 Inheriting and Hiding Concepts. 2.7.3 Inheriting, Overloading and Overriding Methods and constructors. 2.7.4 Interfaces Implementations. Class structure of Java. (CH : 4 → P – 79) A class defines a new data type. Once defined, this new data type can be used to create objects of that type. Thus, a class is a template and object is an instance of a class. Syntax : class { datatype instance_var1; Variable Declaration datatype instance_var2;.. datatype method_name1(parameter_list) Method { //body of method } } The data or variables, defined within a class are called instance variables or member variables or fields. The code is contained within member methods. Dr. Darshna Rajput Page 1 Unit 2 – Classes and Objects Collectively, the methods and variables defined within a class are called members of the class. Variables defined within a class are called instance variables because each instance of the class contains its own copy of these variables. E.g. Creating class with member variables. class Box { double w; double h; double d; } This class declaration only creates a template, it does not create an actual object. To actually create a Box object : Box b1 = new Box(); After this statement executes, b1 will be an instance of Box. Thus, it will have physical reality. Each time you create an instance of a class, you are creating an object that contains its own copy of each instance variable defined by the class. Thus, every Box object will contain its own copies of the instance variables w, h and d. To access this variables, you will use dot(.) operator. The dot operator links the name of object with the name of an instance variable. E.g. b1.w=100; E.g. class Box { double w; double h; double d; Dr. Darshna Rajput Page 2 Unit 2 – Classes and Objects void setdim(double w1, double h1, double d1) { w=w1; h=h1; d=d1; } double volume() { return w*h*d; } } class p16_classdemo1 { public static void main(String args[]) { Box b1=new Box(); b1.setdim(10,20,15); double v=b1.volume(); System.out.println(“Volume is “+v); } } Encapsulation. Encapsulation is one of the four fundamental OOP concepts. The other three are inheritance, polymorphism, and abstraction. Dr. Darshna Rajput Page 3 Unit 2 – Classes and Objects Encapsulation is defined as the wrapping up of data under a single unit. It is the mechanism that binds together code and the data it manipulates. In other way, it is a protective shield that prevents the data from being accessed by the code outside this shield. In encapsulation, the variables of a class will be hidden from other classes, and can be accessed only through the methods of their current class. Therefore, it is also known as data hiding. To achieve encapsulation in Java − o Declare the variables of a class as private. o Provide public setter and getter methods to modify and view the variables values. E.g. class EncapTest { private String name; private int age; public int getAge() { return age; } public String getName() { return name; } public void setAge( int newAge) { age = newAge; } public void setName(String newName) { name = newName; Dr. Darshna Rajput Page 4 Unit 2 – Classes and Objects } } The public setXXX() and getXXX() methods are the access points of the instance variables of the EncapTest class. Normally, these methods are referred as getters and setters. Therefore, any class that wants to access the variables should access them through these getters and setters. The variables of the EncapTest class can be accessed using the following program − class p17_RunEncap { public static void main(String args[]) { EncapTest ob = new EncapTest(); ob.setName("Heena"); ob.setAge(20); System.out.print("Name : " + ob. getName()+ " Age : " + ob.getAge()); } } →Advantages of Encapsulation: Data Hiding: The user will have no idea about the inner implementation of the class. It will not be visible to the user that how the class is storing values in the variables. He only knows that we are passing the values to a setter method and variables are getting initialized with that value. Increased Flexibility: We can make the variables of the class as read-only or write-only depending on our requirement. If we wish to make the variables as read-only then we have to omit the setter methods like setName(), setAge() etc. from the above program or if we wish to make the variables as write-only then we have to omit the get methods like getName(), getAge() etc. from the above program Dr. Darshna Rajput Page 5 Unit 2 – Classes and Objects Reusability: Encapsulation also improves the re-usability and easy to change with new requirements. Testing code is easy: Encapsulated code is easy to test for unit testing. Construction and Initialization. Constructor in java is a special type of method that is used to initialize the object. Java allows objects to initialize themselves when they are created. This automatic initialization is performed through the use of a constructor. A constructor initializes an object immediately upon creation. It has the same name as the class in which it resides and is syntactically similar to a method. Once defined, the constructor is automatically called immediately after the object is created before the new operator completes. They have no return type, not even void. There are two types of constructor: (1) Default Constructor (2) Parameterized Constructor 1. Default Constructor – A constructor that have no parameter is known as default constructor. Syntax : (){} When you do not explicitly defined a constructor for a class, then java creates a default constructor for the class. It automatically initialized all instance variables to 0, null, etc. Once you defined your own constructor, the default constructor is no longer used. E.g. class Box { double w, h, d; Dr. Darshna Rajput Page 6 Unit 2 – Classes and Objects Box() { w=h=d=10; } double volume() { return w*h*d; } } class demo { public static void main(String args[]) { Box b1=new Box(); double v=b1.volume(); System.out.println(“Volume is “+v); } } 2. Parameterized Constructor – A constructor that have parameters is known as parameterized constructor. E.g. class Box { double w, h, d; Box(double w1, double h1, double d1 ) { w=w1; h=h1; d=d1; } Dr. Darshna Rajput Page 7 Unit 2 – Classes and Objects double volume() { return w*h*d; } } class p18_constructordemo { public static void main(String args[]) { Box b1=new Box(10,20,15); double v=b1.volume(); System.out.println(“Volume is “+v); Box b2=new Box(1,2,8); v=b2.volume(); System.out.println(“Volume is “+v); } } ➔ 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 into account the number of parameters in the list and their type. E.g. class Student { int id; String name; int age; Dr. Darshna Rajput Page 8 Unit 2 – Classes and Objects Student(int i,String n) { id = i; name = n; } Student(int i,String n,int a) { id = i; name = n; age=a; } void display() { System.out.println(id+" "+name+" "+age); } } class p19_constructoroverload { public static void main(String args[]) { Student s1 = new Student(111,"Karan"); Student s2 = new Student(222,"Aryan",25); s1.display(); s2.display(); } } this keyword. (CH : 5 → P – 135) ‘this’ can be used inside the Method or constructor of Class. Sometimes a method or constructor will need to refer the object that invoked it. To allow this, java defines the ‘this’ keyword. Dr. Darshna Rajput Page 9 Unit 2 – Classes and Objects ‘this’ works as a reference to the current Object whose Method or constructor is being invoked. The ‘this’ keyword can be used to refer to any member of the current object from within an instance Method or a constructor. There are different uses of ‘this’ keyword: 1. this keyword with instance variable. ‘this’ keyword can be very useful in the handling of Variable Hiding. When a local variable has the same name as an instance variable, the local variable hides the instance variable. ‘this’ refer directly to be object, you can use it to resolve any name space collisions that might occur between instance variables and local variables. E.g. Box(double w, double h, double d) { this.w=w; this.h=h; this.d=d; } Here, formal parameters of Box() constructor have the same name as instance variables of Box class i.e w, h, d. So, formal parameters hides the instance variables which were used by the ‘this’ keyword. 2. this keyword with method. this keyword can also be used inside Methods to call another Method from same Class. E.g. class JBT { void methodOne() { System.out.println("Inside Method ONE"); Dr. Darshna Rajput Page 10 Unit 2 – Classes and Objects } void methodTwo() { System.out.println("Inside Method TWO"); this.methodOne();// same as calling methodOne() } } class thismetdemo { public static void main(String[] args) { JBT obj = new JBT(); obj.methodTwo(); } } Output:- Inside Method TWO Inside Method ONE 3. this keyword with constructor. this keyword can be used inside the constructor to call another overloaded constructor in the same Class. This is called the Explicit Constructor Invocation. This occurs if a Class has two overloaded constructors, one without argument and another with argument. Then the “this” keyword can be used to call constructor with argument from the constructor without argument. This is required as the constructor can not be called explicitly. E.g. class JBT { Dr. Darshna Rajput Page 11 Unit 2 – Classes and Objects JBT() { this("AAA"); System.out.println("Inside Constructor without parameter"); } JBT(String str) { System.out.println("Inside Constructor with String parameter as " + str); } } class thisdemo3 { public static void main(String[] args) { JBT obj = new JBT(); } } Output:- Inside Constructor with String parameter as JBT Inside Constructor without parameter this keyword can only be the first statement in Constructor. A constructor can have either this or super keyword but not both. static keyword. The static keyword in java is used for memory management mainly. Java static keyword used with variables, methods, blocks and nested class. The static keyword belongs to the class than object of the class. That is, static members will be used independently of any object of the class. Dr. Darshna Rajput Page 12 Unit 2 – Classes and Objects When a member is declared static, it can be accessed before any objects of its class are created and accessed without reference to any object. The static can be: 1. variable (also known as class variable) 2. method (also known as class method) 3. block 4. nested class 1) Java static variable If you declare any variable as static, it is known static variable. The static variable can be used to refer the common property of all objects (that is not unique for each object) e.g. company name of employees, college name of students etc. The static variable gets memory only once in class area at the time of class loading. It makes your program memory efficient (i.e it saves memory). E.g. //Program of static variable class student { int rollno; String name; static String cname="DUIAS"; student(int rn,String nm) { rollno=rn; name=nm; } void display() { System.out.println(rollno+" "+name+" "+cname); } Dr. Darshna Rajput Page 13 Unit 2 – Classes and Objects } class p23_st_var { public static void main(String args[]) { student s1=new student(111,"Karan"); student s2=new student(222,"Aryan"); s1.display(); s2.display(); } } Output:- 111 Karan DUIAS 222 Aryan DUIAS →Program of counter by static variable : static variable will get the memory only once, if any object changes the value of the static variable, it will retain its value. E.g. class Counter Dr. Darshna Rajput Page 14 Unit 2 – Classes and Objects { int count=0;//will get memory only once and retain its value Counter() { count++; System.out.println(count); } } class p24_st_var_cnt { public static void main(String args[]) { Counter c1=new Counter(); Counter c2=new Counter(); Counter c3=new Counter(); } } Output:- 1 2 3 2) Java static method If you apply static keyword with any method, it is known as static method. A static method belongs to the class rather than object of a class. A static method can be invoked without the need for creating an object of a class. this and super cannot be used in static context. The static method can not use non static data member or call non-static method directly. static method can access static data member and can change the value of it. Dr. Darshna Rajput Page 15 Unit 2 – Classes and Objects E.g. //Program of changing the common property of all objects(static field). class Student { int rollno; String name; static String college = "ITS"; static void change() { college = "BBDIT"; } Student(int r, String n) { rollno = r; name = n; } void display () { System.out.println(rollno+" "+name+" "+college); } } class p25_st_method { public static void main(String args[]) { Student s1 = new Student(111,"Karan"); Student.change(); Student s2 = new Student(222,"Aryan"); Student s3 = new Student(333,"Sonoo"); s1.display(); s2.display(); Dr. Darshna Rajput Page 16 Unit 2 – Classes and Objects s3.display(); } } Output:- 111 Karan ITS 222 Aryan BBDIT 333 Sonoo BBDIT 3) Java static block It is used to initialize the static data members. It is executed only once i.e. before main method at the time of class loading. E.g. class A2 { static { System.out.println("static block is invoked"); } } class staticblockdemo { public static void main(String args[]) { System.out.println("Hello main"); } } Output:- static block is invoked Hello main Inner classes and local inner classes. OR Dr. Darshna Rajput Page 17 Unit 2 – Classes and Objects static and non-static classes. It is possible to define a class within another class, such classes are known as nested classes. If class B is defined within class A, then B is known to A, but not outside of A. A nested class has access to the members, including private members of the class in which it is nested. However the enclosing class does not have access to the members of the nested class. There are two types of nested classes : 1. Static(local inner class) 2. Non-static (Inner class) A static nested class is one which has the static modifier applied because it is static, it must access the members of its enclosing class through an object. That is, it can not refer to members of its enclosing class directly. An inner class is a non-static nested class. It has access to all of the variables and methods of its outer class and may refer to them directly. Members of inner class known only within the scope of inner class and may not be used by the outer class. You can define a nested class within the block defined by method or even within the body of for…loop. E.g. class outer { int x=10; void test2() { System.out.println(“x=” + x); // System.out.println(“y=” + y); // can’t access because y is of inner class. inner ob2=new inner(); ob2.test1(); Dr. Darshna Rajput Page 18 Unit 2 – Classes and Objects } class inner { int y=20; //local to inner class void test1() { System.out.println(“x=” + x); System.out.println(“y=” + y); } } } class test { public static void main(String args[]) { outer ob1= new outer(); ob1.test2(); } } Inheritance. (Ch : 4 → P -114) A class that is inherited is called a super class / base class / parent class. A class that does inheriting is called a subclass / derived class / child class. Therefore, a subclass is a specialized version of a super class. It inherits all of the instance variables and methods defined by the super class and add its own unique elements. Dr. Darshna Rajput Page 19 Unit 2 – Classes and Objects The sub class has access to all public members of its super class but it can not access the private members of its super class. A sub class can be a super class for another sub class. To inherit a class, use extends keyword. There are four different forms of inheritance : 1. Single Inheritance 2. Multilevel Inheritance 3. Hierarchical Inheritance 4. Hybrid Inheritance E.g. (Single Inheritance) class A { int i, j; private int a; void showij() { System.out.println(“a=”+a); System.out.println(“i and j : “+ i + “ and “ + j); } } class B extends A { int k; Dr. Darshna Rajput Page 20 Unit 2 – Classes and Objects void showk() { //System.out.println(“a : “+ a); //Not accessible because a is private System.out.println(“k : “ + k); } void sum() { System.out.println(“i+j+k : “ + (i+j+k)); } } class p26_s_inheritance { public static void main(String args[]) { A oba= new A(); B obb= new B(); Oba.i=10; Oba.j=20; System.out.println(“The content of super class”); Oba.showij(); Obb.i=1; Obb.j=2; Obb.k=3; System.out.println(“The content of sub class”); Obb.showij(); Obb.showk(); Obb.sum(); } } Dr. Darshna Rajput Page 21 Unit 2 – Classes and Objects Output:- The content of super calss i and j : 10 and 20 The content of sub class i and j : 1 and 2 k:3 i+j+k : 6 Multilevel inheritance. When a class extends a class, which extends another class then this is called multilevel inheritance. For example class C extends class B and class B extends class A then this type of inheritance is known as multilevel inheritance. E.g. class A { A() { System.out.println(“Constructor of A”); } } Dr. Darshna Rajput Page 22 Unit 2 – Classes and Objects class B extends A { B() { System.out.println(“Constructor of B”); } } class C extends B { C() { System.out.println(“Constructor of C”); } } class p27_MultiIh { public static void main(String args[]) { C ob=new C(); } } Output:- Constructor of A Constructor of B Constructor of C Here, in class hierarchy constructors are called in order of derivation, from super class to sub class. Access/visibility modifiers/specifiers and access controls at class and package level.(Ch : 5 → P – 143) Dr. Darshna Rajput Page 23 Unit 2 – Classes and Objects There are two types of modifiers in java: access modifiers and non-access modifiers. The access modifiers in java specifies accessibility (scope) of a data member, method, constructor or class. There are 4 types of java access modifiers: 1. private 2. default (Nothing to be written) 3. protected 4. public There are many non-access modifiers such as static, abstract, synchronized, native, volatile, transient etc. ➔ Class Member Accessibility :- 1. Defualt – When no access modifier is specified for a class, method or data member – It is said to be having the default access modifier by default. The data members, class or methods which are not declared using any access modifiers i.e. having default access modifier are accessible only within the same package. In this example, we will create two packages and the classes in the packages will be having the default access modifiers and we will try to access a class from one package from a class of second package. E.g. Dr. Darshna Rajput Page 24 Unit 2 – Classes and Objects package p1; //Class ABC is having Default access modifier class ABC { void display() { System.out.println("Hello World!"); } } //Java program to illustrate error while using class from different package with default modifier package p2; import p1.*; //This class is having default access modifier class XYZ { public static void main(String args[]) { //accessing class ABC from package p1 ABC obj = new ABC(); obj.display(); } } Output: Compile time error 2. Private – The private access modifier is specified using the keyword private. The methods or data members declared as private are accessible only within the class in which they are declared. Dr. Darshna Rajput Page 25 Unit 2 – Classes and Objects Any other class of same package will not be able to access these members. Classes or interface can not be declared as private. In this example, we will create two classes A and B within same package p1. We will declare a method in class A as private and try to access this method from class B. E.g. //Java program to illustrate error while using class from different package with private modifier package p1; class A { private void display() { System.out.println("GeeksforGeeks"); } } class B { public static void main(String args[]) { A obj = new A(); //trying to access private method of another class obj.display(); } } Output: error: display() has private access in A obj.display(); 3. Protected – The protected access modifier is specified using the keyword protected. Dr. Darshna Rajput Page 26 Unit 2 – Classes and Objects The methods or data members declared as protected are accessible within same package or sub classes in different package. In this example, we will create two packages p1 and p2. Class A in p1 is made public, to access it in p2. The method display in class A is protected and class B is inherited from class A and this protected method is then accessed by creating an object of class B. E.g. //Java program to illustrate protected modifier package p1; //Class A public class A { protected void display() { System.out.println("GeeksforGeeks"); } } //Java program to illustrate protected modifier package p2; import p1.*; //importing all classes in package p1 //Class B is subclass of A class B extends A { public static void main(String args[]) { B obj = new B(); obj.display(); } } Output: GeeksforGeeks Dr. Darshna Rajput Page 27 Unit 2 – Classes and Objects 4. Public – The public access modifier is specified using the keyword public. The public access modifier has the widest scope among all other access modifiers. Classes, methods or data members which are declared as public are accessible from every where in the program. There is no restriction on the scope of a public data members. E.g. //Java program to illustrate public modifier package p1; public class A { public void display() { System.out.println("GeeksforGeeks"); } } package p2; import p1.*; class B { public static void main(String args[]) { A obj = new A; obj.display(); } } Output: GeeksforGeeks Dr. Darshna Rajput Page 28 Unit 2 – Classes and Objects super keyword.(Ch : 5 → P – 135) The super keyword in java is a reference variable that is used to refer parent class objects. Whenever a sub class needs to refer to its immediate super class, it can do so by use of super keyword. 1. super keyword with variables. Super can be used when member variable’s names of sub class hide the member variables by the same name in the super class. So, the super class member variable access by the super keyword. E.g. class A { int i; } class B extends A { int i; This i hides the i in A class. B(int a, int b) { super.i = a; i=b; } void show() { System.out.println(“ i in super class : ”+ super.i); System.out.println(“i in sub class : “+ i); } } class p28_super1 { public static void main(String args[]) Dr. Darshna Rajput Page 29 Unit 2 – Classes and Objects { B ob=new B(10,20); ob.show(); } } Output:- i in super class :10 i in sub class : 20 2. super keyword with methods. This is used when we want to call parent class method. So whenever a parent and child class have same named methods then to resolve ambiguity, we use super keyword. E.g. class Person { void message() { System.out.println("This is person class"); } } class Student extends Person { void message() { System.out.println("This is student class"); } // Note that display() is only in Student class void display() Dr. Darshna Rajput Page 30 Unit 2 – Classes and Objects { // will invoke or call current class message() method message(); // will invoke or call parent class message() method super.message(); } } class p29_super2 { public static void main(String args[]) { Student s = new Student(); // calling display() of Student s.display(); } } Output:- This is student class This is person class 3. super keyword with constructors. A sub class can call a constructor defined by its super class i.e. super(Parameter list) Here parameter list specifies any parameters needed by the constructor in super class. Super() must be the first statement executed inside subclass constructor. E.g. class Person Dr. Darshna Rajput Page 31 Unit 2 – Classes and Objects { Person() { System.out.println("Person class Constructor"); } } class Student extends Person { Student() { // invoke or call parent class constructor super(); System.out.println("Student class Constructor"); } } class p30_super3 { public static void main(String[] args) { Student s = new Student(); } } Output:- Person class Constructor Student class Constructor Behavior of constructors in inheritance. Order of execution of constructors in inheritance relationship is from base/parent class to derived /child class. Dr. Darshna Rajput Page 32 Unit 2 – Classes and Objects When we create an object of a class then the constructors get called automatically. In inheritance relationship, when we create an object of a child class, then first base class constructor and then derived class constructor get called implicitly. ➔ Constructor call order in single inheritance java If we create object of child class in main() program, constructors of parent class then child class will be called. E.g. class Parent { Parent() { System.out.println("Parent()..."); } } class Child extends Parent { Child() { System.out.println("Child()..."); } } class TestConstructorCallOrder { public static void main(String[] args) { //Create object of Child class object System.out.println("Constructor call order..."); Child ob=new Child(); Dr. Darshna Rajput Page 33 Unit 2 – Classes and Objects } } Output:- Constructor call order… Parent()… Child()… → Constructor call order in Multilevel inheritance If we create object of bottom most derived class i.e. of Testing class in main() program, then constructors of Design class, Coding class and then Testing class will be called. E.g. class Design { Design() { System.out.println("Design()..."); } } class Coding extends Design { Coding() { System.out.println("coding()..."); } } class Testing extends Coding { Testing() { System.out.println("Testing()..."); Dr. Darshna Rajput Page 34 Unit 2 – Classes and Objects } } class TestConstructorCallOrder { public static void main(String[] args) { //Create object of bottom most class object System.out.println("Constructor call order..."); Testing ob=new Testing(); } } Output:- Constructor call order… Design()… coding()… Testing()… Method Overloading. (Ch : 5 → P- 127) In java, it is possible to define two or more methods within the same class that share the same name as long as their parameter declarations are different. This process is referred to as Method Overloading. Method overloading is one of the ways that java supports polymorphism i.e one interface, multiple methods. (One name and multiple forms) When an overloaded method is invoked, java uses the type and number of arguments to decide which version of the overloaded method is called. Thus, overloaded methods must differ in type and number of parameters. While overloaded methods may have different return types, the return type is not sufficient to distinguish two versions of a method. E.g. class test Dr. Darshna Rajput Page 35 Unit 2 – Classes and Objects { void area(int l) { System.out.println(“The area of square is “ + (l*l)); } void area(int l, int b) { System.out.println(“The area of rectangle is “+(l*b)); } } class p31_methodoverload1 { public static void main(String args[]) { test ob = new test(); ob.area(5); ob.area(5,7); } } Output:- The area of square is 25 The area of rectangle is 35 Sometimes in method overloading, the match need not always be exact. In this case, java performs automatic type conversion. E.g. class testdemo { void test() { System.out.println(“No Parameters”); } Dr. Darshna Rajput Page 36 Unit 2 – Classes and Objects void test(int a, int b) { System.out.println(“a and b : “+a+” and “+b); } void test(double a) { System.out.println(“Inside test(double) a:”+a); } } class p32_methodoverload2 { public static void main(String args[]) { testdemo ob= new testdemo(); int i=88; ob.test(); ob.test(10,20); ob.test(i); Automatic type conversion for int to double ob.test(123.2); } } Output:- No Parameters a and b : 10 and 20 Inside test(double) a: 88.0 Inside test(double) a: 123.2 Method overriding. (Ch : 5 → P- 125) In a class hierarchy, when a method in a sub class has the same name and type signature as a method in its super class then the method in the sub class is said to override or hide the method of the super class. Dr. Darshna Rajput Page 37 Unit 2 – Classes and Objects If you wish to access the super class version of an overridden function, you can do so by using super. E.g. class A { int i; void show() { System.out.println(“i = “+i); } } class B extends A { int j; B(int x, int y) { i=x; j=y; } void show() { super.show(); System.out.println(“i + j =” + (i+j)); } } class p33_methodoveride { public static void main(String args[]) { B ob=new B(10,20); ob.show(); → Call sub class method Dr. Darshna Rajput Page 38 Unit 2 – Classes and Objects } } Output:- i = 10 i+j = 30 Method overriding occurs only when the names and the type signatures of the two methods are identical. If they are not then the two methods are simply overloaded. E.g. class A { int i; void show(String msg) { System.out.println(msg+i); } } class B extends A { int j; B(int x, int y) { i=x; j=y; } void show() { System.out.println(“i+j = “+(i+j)); } } class p34_methodoverload3 Dr. Darshna Rajput Page 39 Unit 2 – Classes and Objects { public static void main(String args[]) { B ob=new B(10,20); ob.show(“The value of i is : “); → Call super class method ob.show(); → call subclass method } } Output:- The value of i is 10 i + j = 30 Difference between overloading and overriding. (Ch : 5 → P – 465) Overloading Overriding 1. It is an example of compile time 1. It is an example of run time polymorphism. polymorphism. 2. When a method in a class having 2. When a method in a class having the same method name with different the same method name with same arguments is said to be method arguments is said to be method overloading. overriding. 3. There is a relationship between 3. There is a relationship between a methods available in the same class. super class method and sub class method. 4. In this, separate methods share the 4. In this, sub class method replaces same name. the super class. Dr. Darshna Rajput Page 40 Unit 2 – Classes and Objects 5. Overloading must have different 5. Overriding must have same method signatures. signature. 6. Methods can be static or non static. 6. Static methods don’t participate in Since the methods are independent, it overriding. Because a static method in doesn’t matter. But if two methods a sub class can’t use super keyword. have the same signature, declaring one as static and another as non static does not provide a valid overload. 7. There is no limit on number of 7. Super class method may be overloaded methods a class can have. overridden at most once in any sub class. That is, you can’t have two identical methods in the same class. Polymorphism. (Ch : 5 → P – 125) Polymorphism is a concept of having more than one form. Poly is many and morph is forms. Thus poly + morph is having more than one form. Methods in a class having same names but having different signature are example of polymorphism. When the execution superiority of methods having same names but different signatures are resolved at the time of compilation is known as early binding. But when this resolve at the time of execution, it is known as late binding. Dynamic method dispatch / Runtime Polymorphism. Java runtime polymorphism is implemented by dynamic method dispatch. Dynamic method dispatch is the mechanism by which a call to an overridden function is resolved at runtime, rather than compile time. This is called late binding. Dr. Darshna Rajput Page 41 Unit 2 – Classes and Objects When all overridden function is called through a super class reference, java determines which version of that method to execute based upon the type of the object being referred to at runtime. If a super class contains a method that is overridden by a sub class then when different types of objects are referred to through a super class reference variable, different versions of that method are executed. E.g. class A { void show() { System.out.println(“Method of class A”); } } class B extends A { void show() { System.out.println(“Method of class B”); } } class C extends A { void show() { System.out.println(“Method of class C”); } } class p35_dynamicmet { public static void main(String args[]) Dr. Darshna Rajput Page 42 Unit 2 – Classes and Objects { A a=new A(); B b=new B(); C c=new C(); A r; → Reference variable of super class A r=a; r.show(); → Call class A method r=b; r.show(); → Call class B method r=c; r.show(); → Call class C method } } Output:- Method of A class Method of B class Method of C class Abstract Class. (Ch : 6 → P- 163) Sometimes you want to create a super class that only defines a general form that will be shared by all of its sub classes. You may have methods which must be overridden by the sub class. Such method is known as Abstract Methods. A sub class must override them, it can not simply used the version defined in the super class. To declare an abstract method, abstract method_name(parameter_list); Any class that contains one or more abstract methods must also be declared abstract. There can be no objects of an abstract class. Also you can not declared abstract constructor or abstract static method. Dr. Darshna Rajput Page 43 Unit 2 – Classes and Objects Any sub class of an abstract class must either implement all of the abstract methods in the super class or be itself declared as abstract. Although abstract classes can not be used to instantiate object, they can be used to create object references because java’s approach to run time polymorphism is implemented through the use of super class references. Thus, it must be possible to create a reference to an abstract class. So, that it can be used to point to a subclass object. Through super class reference variables overridden methods are resolved at run time. All sub class of an abstract super class must override the method, otherwise compile time error will be generated. E.g. abstract class figure { double dim1, dim2; figure(double x, double y) { dim1=x; dim2=y; } abstract double area(); } class rect extends figure { rect(double x, double y) { super(x,y); } double area() { return dim1 * dim2; Dr. Darshna Rajput Page 44 Unit 2 – Classes and Objects } } class triangle extends figure { triangle(double x, double y) { super(x,y); } double area() { return (dim1*dim2)/2; } } class p36_abstractdemo { public static void main(String args[]) { rect r=new rect(5,6); triangle t=new triangle(5,6); figure rf; rf=r; System.out.println(“The area of rectangle is : “ + rf.area()); rf=t; System.out.println(“The area of triangle is :”+rf.area()); } } Output:- The area of rectangle is : 30.0 The area of triangle is : 15.0 Dr. Darshna Rajput Page 45 Unit 2 – Classes and Objects Use of final keywords. The final keyword in java is used to restrict the user. Final can be: 1. variable 2. method 3. class 1) Java final variable If you make any variable as final, you cannot change the value of final variable i.e. to create constant final keyword is used with variable. Final variable must be initialized when it is declared. Variables declared as final do not occupy memory on per instance bases. Thus, it is a constant variable. E.g. final int size = 10; final double pi = 3.14; 2) Java final method To prevent a method from being overridden, specify final as a modifier at the start of its declaration. So, methods declared as final can not be overridden. E.g. Dr. Darshna Rajput Page 46 Unit 2 – Classes and Objects class A { final void show() { Sytem.out.println(“Final Method”); } } class B extends A { void show() //Compile time error i.e. can not be overrriden. { System.out.println(“Illegal”); } } Java resolves calls to methods dynamically, at run time. This is called late binding. But here final methods can not be overridden, a call to that can be resolved at compile time. This is called early binding. 3) Java final class To prevent the class from being inherited, precede the class declaration with final. Declaring a class as final implicitly declares all of its methods as final. It is illegal to declare a class as both abstract and final since an abstract class is incomplete by itself and relies upon its sub classes to provide complete implementations. E.g. final class A {...... } Dr. Darshna Rajput Page 47 Unit 2 – Classes and Objects class B extends A {......//Error i.e. can not be subclass A. } Interface. (Ch : 6 → P- 164) Java does not support multiple inheritance. That is, classes in java can not have more than one super class. Java provides an alternate approach known as interface to support the concept of multiple inheritance. Although a java can not be a sub class of more than one super class, it can implement more than one interface. ❖ Defining an interface : An interface is basically a kind of class. Like classes, interfaces contain methods and variables but with a major difference. The difference is that interfaces define only abstract methods and final fields/variables. This means that interfaces do not specify any code to implement these methods and data fields contain only constants. Therefore, it is the responsibility of the class that implements an interface to define the code for implementation of these methods. So, the class that implements interface must define the code for the methods. Syntax: interface { Variable declaration; Method declaration; } Dr. Darshna Rajput Page 48 Unit 2 – Classes and Objects Here, interface is the keyword. Variables are declared as, static final type var_name = value; Here, static and final means they can not be changed by the implementing class. They must also be initialized with a constant value. All the variables in an interface are treated as constants although the keyword final and static are not present. Methods are abstract methods, there can be no default implementation of any method specified within an interface. So, methods declaration will contain only a list of methods without any body of statements. Return_type method_name(parameter list); So, here each class that includes an interface must implement all of the methods. E.g. interface callback { void callback_meth(int param); } ❖ Implementing interface : Once an interface has been defined, one or more classes can implement that interface. To implement an interface, include the implements clause in a class definition, and then create the methods defined by the interface. Syntax: class implements ,,…. { //Class body } Dr. Darshna Rajput Page 49 Unit 2 – Classes and Objects If class implements more than one interface, than interfaces are separated with a comma. E.g. class client implements callback { Must → public void callback_meth(int p) { System.out.println(“Callback called with “ +p); } void nonifacemeth() { System.out.println(“Other method”); } } class anotherclient implements callback { Must → public void callback_meth(int p) { System.out.println(“Another version of callback”); System.out.printn(“p squaed is :”+(p*p)); } } Here, these classes also defined additional members of their own. ❖ Accessing methods through interface references – You can declare variables as object references that use an interface rather than a class type. Any instance of any class that implements the declared interface can be referred to by such a variable. Dr. Darshna Rajput Page 50 Unit 2 – Classes and Objects When you call a method through one of these references, the correct version will be called based on the actual instance of the interface being retrieved to. E.g. class p38_interfacedemo { public static void main(String args[]) { callback c; client ob1=new client(); c=ob1; c.callback_meth(42); Call method of client class c.nonifacemeth(); not valid because not a method of callback interface anotherclient ob2=new anotherclient(); c=ob2; c.callback_meth(4); call method of anotherclient class } } Here, an interface variable only has knowledge of the methods declared by its interface declaration. Thus, c, reference variable, not to be used to access noninterfacemeth() since it is defined by client but not by callback. In result, the version of callback_meth() that is called, is determined by the type of object that c refers to at run time. → Advantages of Interface : 1) Through interfaces we can implement multiple inheritances in java. 2) Interfaces function to break up the complex designs and clear the dependencies between objects. 3) Interfaces make your application loosely coupled. Dr. Darshna Rajput Page 51 Unit 2 – Classes and Objects 4) Interfaces are mainly used to provide polymorphic behavior. Class Vs Interface. (Ch : 6 → P- 176) Class Interface 1. We can create an object of the 1. We can not create an object of an class. interface. 2. A class have simple member 2. An interface have only final member variable and method. variable and abstract methods in it. 3. Methods in class have body part. 3. There is only declaration of method in an interface. 4. It is not necessary to inherit the 4. But to implement all methods class. defined in interface, it is necessary to implement the interface. Partially implemented interface. If a class includes an interface but does not fully implement the methods defined by that interface, then that class must be declared as abstract. E.g. abstract class incomplete implements callback { int a,b; void show() { System.out.println(a+” “+b); } abstract public void callback_meth(int p); } class compl extends incomplete { Dr. Darshna Rajput Page 52 Unit 2 – Classes and Objects public void callback_meth(int p) { System.out.println(“Method of demo_in”); System.out.println(“Callback called with “ + (p*p*p)); } } Extending Interface / Interface Inheritance. Like classes, interfaces can also be extended. That is, interface can be subinterfaced from other interfaces. The new subinterface will inherit all the members of the superinterface in the manner similar to subclasses. This is achieved using the keyword extends. Syntax : interface extends , { Body of interface. } We can combine several interfaces together in to a single interface. When an interface extends two or more interfaces, they are separated by commas. While interfaces are allowed to extend to other interfaces, subinterfaces can not define the methods declared in the superinterface. After all, subinterfaces are still interfaces, not classes. Instead, it is the responsibility of any class that implements the derived interface to define all the methods. An interface can not extend classes. E.g. interface A { void meth1(); Dr. Darshna Rajput Page 53 Unit 2 – Classes and Objects void meth2(); } interface B extends A { void meth3(); } class test implements B { public void meth1() { System.out.println(“Method 1”); } public void meth2() { System.out.println(“Method 2”); } public void meth3() { System.out.println(“Method 3”); } } class p39_extendinterfacedemo { public static void main(String args[]) { test ob=new test(); ob.meth1(); ob.meth2(); ob.meth3(); } } Dr. Darshna Rajput Page 54 Unit 2 – Classes and Objects Output :- Method 1 Method 2 Method 3 Dr. Darshna Rajput Page 55