4 Inheritance
4 Inheritance
Debasis Samanta
Department of Computer Science & Engineering
Indian Institute of Technology Kharagpur
Static Scope Rule in Java
Static scope rule
class Box{ class Circle{
float x = 10.0; float x = 0.0;
float y = 20.0; float y = 0.0;
float w = 15.0; float r = 5.0;
class GeoClass{
float x = 50;
float y = 60;
public static void main(String args[]){
Box b = new Box();
Circle c = new Circle();
System.out.println("GeoClass Data: x = “ + x);
System.out.println("Box Data: x = “ + b.x);
System.out.println("Box Area: “ + b.area);
System.out.println("Circle Data: x = “ + c.x);
System.out.println("Circle Area: “ + c.area);
}
}
Static scope rule : Another example
class StaticScope {
public static void main(String args[]) {
int x; // known to all code within main
x = 10;
In class Box and class Circle, we declared three variables (x, y, w) and (x, y, r), respectively.
They are so called because each instance of the class, say, Circle, has its own copy.
Instance variable versus Class variable
Java does not allow global variables.
x
Every variable in Java must be declared inside a class. b1 y
w
The keyword static is used to make a variable just like global
variable. x
A variable declared with static keyword is called class b2 y w
variable. w static float w;
It acts like a global variable, that is, there is only one copy of the x
variable associated with the class. b3 y
That is, one copy of the variable regardless of the number of w
instances of the class. Three instances of class Box
Static variable : An example
public class Circle{
static int circlecount = 0; // class variable
public double x,y,r; // instance variables public double circumference(){
public Circle(double x, double y, double r){ return (2*3.14159*r);
this.x = x; this.y = y; this.r = r; }
circlecount++; public double area(){
} return(3.14159*r*r);
public Circle(double r){ }
this(0.0,0.0,r); public static void main(String args[ ]){
circlecount++; Circle c1 = new Circle();
} Circle c2 = new Circle(5.0);
public Circle(Circle c){ Circle c3 = new Circle(c1);
this(c.x,c.y,c.r); System.out.println("c1#“ + c1.circlecount + "c2#“ +
circlecount++; c2.circlecount + "c3#“ + c3.circlecount);
} }
public Circle(){ }
this(0.0,0.0,0.1);
circlecount++;
}
Declaring static method : An example
// A class method and instance method
public class Circle{
public double x,y,r;
// All constructors are here.
// An instance method. Return the bigger of two circles.
public Circle bigger(Circle c){
if(c.r>r) return c;
else return this;
}
// A class method: Return the bigger of two classes.
public static Circle bigger (Circle a, Circle b) {
if (a.r > b.r) return a;
else return b:
}
class Circle{
static double x,y,r;
Circle(double r){
this.r = r;
}
// Following is the nested class
public static class Point{
double x, y;
void display(){
System.out.println("(x,y): (“ + this.x + ",“ + this.y + ")");
}
Point(double a, double b){
this.x = a;
this.y = b;
}
}
Continued to the next slide……
Nested class in Java
In Java, a class can be defined inside a class. Let us look at the following example.
GCD(35, 15) = 5
GCD(10, 50) = 10
GCD(11, 0) = 11
GCD(8, 8) = 8 For any two integers m and n (such that m < n), the GCD (m,n)
GCD(1, 13) = 1 calculation can be defined recursively is as follows.
Debasis Samanta
Department of Computer Science & Engineering
Indian Institute of Technology Kharagpur
Inheritance Concept
Concept of inheritance
Hybrid inheritance
Multiple inheritance
Inheritance types
Single inheritance Multiple single inheritance Multilevel single inheritance
Hybrid inheritance
Multiple inheritance
Single inheritance : An example
• name
• dob
Person • mobileNo
• readData()
• printData()
• empNo
• institution
• salaryHistory[]
• qualif[]
• organization
• rollNo Student Employee • designation
• marks[]
• doj
• printBioData()
• printSalary()
Single Inheritance in Java
Single Inheritance : Person class
class Person{
String name;
Date dob;
int mobileNo;
void readData(String n, Date d, int m){
name = n;
dob = d;
mobileNo = m;
}
void printData(){
System.out.println("Name : "+ name);
dob.printDate();
System.out.println("Mobile : "+ mobileNo);
}
}
Single inheritance : Student class
class Person{
String name;
Date dob;
int mobileNo;
void readData(String n, Date d, int m){ class Student extends Person{
name = n;
String institution;
dob = d;
mobileNo = m; int[] qualif = new int[20];
} int rollNo;
void printData(){ int[] marks = new int[5];
System.out.println("Name : "+ name);
dob.printDate(); void printBioData(){
System.out.println("Mobile : "+ mobileNo); printData();
} System.out.println("Institution : "+ institution);
}
System.out.println("Roll : "+ rollNo);
for(int q=0; q<qualif.length;q++){
System.out.println(“Marks "+q+": "+ qualif[q]);
}
for(int m=0; m<marks.length;m++){
System.out.print(“Result "+m+": "+marks[m]);
}
}
}
Single Inheritance – employee
class Person{
String name;
Date dob;
int mobileNo;
void readData(String n, Date d, int m){
name = n;
dob = d;
mobileNo = m;
} class Employee extends Person{
void printData(){ int empNo;
System.out.println("Name : "+ name); int[] salaryHistory = new int[12];
dob.printDate(); String organization;
System.out.println("Mobile : "+ mobileNo); String designation;
} Date doj;
}
void printSalary(){
for(int s=0; s<salaryHistory.length;s++){
System.out.println("Salary "+s+": "+salaryHistory[s]);
}
}
}
Single Inheritance : An example
class inheritanceDemo1{
public static void main(String args[]){
Person p = new Person();
//Code with the objects p…
Student s = new Student [100];
//Code with the objects s…
Employee e = new Employee[50];
//Code with the objects e…
}
}
Multilevel inheritance : An example
Geo Object
Triangle Quadrilateral
class MethodOverridingTest{
public static void main(String args[]){
Point2D p = new Point2D(3.0, -4.0);
p.display(); // Refers to the method in Point2D
A sub class object can reference a super class variable or method if it is not
overridden.
class B extends A {
void callMe ( ) {
System.out.println ( "I am from B ");
}
}
class Who {
public void static main (String args [ ] ) {
A a = new B ( ) ;
a.callMe();
B b = new B( );
b.callMe();
}
}
Abstract class in Java
Abstract concept
• Abstraction lets you focus on what the object does instead of how
it does it.
Note:
If you make any class as final, you cannot extend it.
Final class in inheritance : An Example
Debasis Samanta
Department of Computer Science & Engineering
Indian Institute of Technology Kharagpur
Access Modifiers in Java
Concept of access modifiers
The access modifiers in Java specify accessibility (scope) of a data member,
method, constructor or class.
Access modifier
Public ✔ ✔ ✔ ✔
Protected ✔ ✔ ✔ ✘
Default ✔ ✔ ✘ ✘
Private ✔ ✘ ✘ ✘
Default access modifier
class A {
void msg(){System.out.println(“Hi! I am in Class A");
}
} Here, two classes are with default access
modifier, and thy are residing in the same
directory (or may be in the same file).
/* Save this program as B.java in the same directory */ Hence, in this case, the class A is
class B{ accessible to class B and vice-versa.
public static void main(String args[]){
A obj = new A(); //Okay. It is accessible.
obj.msg(); //It is also accessible.
}
}
Public access modifier
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
public access modifier : An example
public class A{
public int data = 40;
public void msg(){ We have created two classes class A and
System.out.println(“Class A: Hello Java!");
} class B. The class A contains public
} data member and public method and are
public class B{
accessible to class B.
public static void main(String args[]){
A obj = new A(); //OK : Class A is public
System.out.println(obj.data);
Note:
//OK : data is public It does not matter whether the class A and
obj.msg(); //OK: msg is public class B belong to the same directory or in
}
} the same program file.
Public access modifier : Another example
//Save this program as A.java
package pack1; // It is a sub-directory “pack1”
public class A {
void msg(){System.out.println(“Hi! I am in Class A");}
}
public class A{
private int data = 40;
public void msg(){
System.out.println(“Class A: Hello Java!");
}
}
public class B{
public static void main(String args[]){
A obj = new A(); //OK : Class A is public
System.out.println(obj.data);
//Compile Time Error : data is private
obj.msg(); //OK : msg is public
}
}
Private access modifier : An example
private class A{
int data = 40;
void msg(){
System.out.println(“Class A: Hello Java!"); When a class is private, all its
}
} member with default access specifier
are also private.
public class B{
public static void main(String args[]){
A obj = new A(); //Error : Class A is public How, if a member in a public class is
System.out.println(obj.data);
//Compile Time Error : data is private declared as public or protected?
obj.msg(); //Error : msg is private
}
}
Think about this…
public class A{
private int data = 40;
public void msg(){
System.out.println("Hello Java!“ + data);
}
}
public class B{
public static void main(String args[]){
A obj = new A(); //OK : Class A is public
System.out.println(obj.data);//Compile Time Error : data is private
obj.msg(); //Calls msg() method of class A, which in turns private data : Error!
}
}
private constructor : An example
public class A{
private A(){
//private constructor
}
void msg(){ If you make any class constructor
}
System.out.println(“Class A: Hello Java!"); private, you can not create an
} instance of that class from outside the
public class Simple{ class.
public static void main(String args[]){
A obj = new A(); //Compile Time Error!
}
}
Protected access modifier
public class A{
protected int i = 555; Here, the protected data i is accessible to
void msg(){ any methods in the same class. Alos, it is
System.out.println(“Class A: Hello Java!“ + i);
}
accessible to any of its sub class.
}
Here, class A is accessible to class B
as it is declared public; however, any
class B { method in the class B (even they are in
public static void main(String args[]){
A obj = new A(); the same file or package) cannot access
obj.msg(); // Error: Compilation error protected data of class A directly or
}
} indirectly.
Protected access modifier : An Example
public class A{
public int i = 555; Here, the msg() method of the
protected void msg(){ class A is declared as protected,
System.out.println("Hello Java! + i");
} and hence, it can be accessed from
}
outside the class only through
inheritance.
class B extends A{
public static void main(String args[]){
B obj = new B(); What will happen if i is made private
obj.msg();
} in class A?
}
Protected access modifier : Another Example
//Save as A.java in a sub directory pack1
package pack1;
public class A{
protected void msg(){
We have created the two packages pack1
System.out.println(“Class A: Hello Java!"); and pack2.
}
}
The class A of pack1 package is
//Save as B.java in another sub-directory pack2 public, so can be accessed from outside
package pack2; the package. The method msg() of the
import pack1.*;
class A is declared as protected, so it
class B extends A{ can be accessed from outside the class
public static void main(String args[]){
B obj = new B();
through inheritance.
obj.msg();
}
}
Java access modifiers with method overriding
public class A{
protected void msg(){ If you are overriding any method, overridden
System.out.println(“Class A: Hello Java!"); method (i.e. declared in sub class) must not be
}
} more restrictive.
public class Simple extends A{
void msg(){ The default modifier is more restrictive than
System.out.println(“Class B: Welcome!"); protected. That is why, there is compile time
//Compile Time Error
} error.
public static void main(String args[]){ What will happen if the msg() in class
Simple obj = new Simple();
obj.msg(); Simple is declared as public or
} protected?
}
Questions to think…