Module - 2 Closer Look - Inheritance
Module - 2 Closer Look - Inheritance
Module – 2:
Chapter – 1: A Closer Look at Methods and Classes
Prepared by
Mrs. Suma M G
Assistant Professor
Department of MCA
RNSIT
Bengaluru – 98.
JAVA Programming [20MCA22] Module-2
Chapter-1
ob.change(a,b);
System.out.println("A and B before
call " + a + " " +b);
}
}
Call-by-reference:
• A reference to an argument (instead the value) is passed to the parameter. The passed reference is used
to access the actual argument specified in the call.
• Objects are passed by default as call-by-reference.
• When you pass reference to a method, the parameter that receives it will refer to the same. Thus Changes
to the object inside the method do affect the object used as an argument.
class ConstructorOver{
public static void main(String[] args){
Overload o1=new Overload();
Overload o2=new Overload(10);
Overload o3=new Overload(10,20);
Overload o4=new Overload(1.1,2.1);
}
}
Another Example for Method overloading and Constructor overloading: Lab Program
class Shape{
int length, breadth, height
Shape(){ //Default constructor
Length = breadth = height = 0;
}
Shape(int length, int breadt, int height) { // parameterized constructor
Length = breadth = height = side;
}
int volume() { // method with no parameters
return length * breadth * height;
}
int volume(int length, int breadth, int height) { // method with parameters
return length * breadth * height;
}
public static void main(String [] args){
System.out.println(“ --Demonstrating Constructor Overloading-- ”);
Shape square = new Shape(10);
Shape rectangle = new Shape();
System.out.println(“ --Demonstrating Method Overloading-- ”);
int volume1 = square.volume();
int volume2 = rectangle.volume(10,20, 30);
System.out.println(“ –Volume of Square = ” + volume1);
System.out.println(“ –Volume of Rectangle = ” + volume2);
}
}
1.7 Recursion:
A method can call itself. This process is called recursion. A method that calls itself is said to be recursive.
Why recursion:
✓ It requires the least amount of code to perform the necessary functions.
✓ Solves complicated problems in simple steps
class Fact{
static int factorial(int n){
if (n == 0)
return 1;
else
return(n * factorial(n-1));//Recursively call
}
public static void main(String args[]){
int fact=1,number=4;
fact = factorial(number);
System.out.println("Factorial of "+ number+" is: "+fact);
}
}
class Staticdata{
int x;
static int y;//Static Variable
void print(){
System.out.println("X= " + x + "\nY= " + y);
}
}
class StaticDemo{
public static void main(String[] args)
{
Staticdata std1=new Staticdata();
Staticdata std2=new Staticdata();
std1.print();
std2.print();
std1.x=5; //Accesing variable with class object
Staticdata.y=10; //Accessing static variable with class name
System.out.println("After modified");
std1.print();
std2.print();
}
}
Static Methods:
Method can also declared as static.
Syntax: className.staticMehtod();
Restriction:
• They can access only other static members of the class
• A static member does not have a this or super
• They cannot be declared as final
• A static member function can be called, even when a class is not instantiated.
• They cannot be a static and non-static version of the same method.
class StaticMethod{
int x;
static int y;
static void print(){ //Static Method
StaticMethod ob1=new StaticMethod();
//Instance variable can access with the object
System.out.println("X= " + ob1.x + "\nY= " + y);
}
}
class StaticDemoM{
public static void main(String[] args){
StaticMethod.print();//Invoking static method
}
}
Static Block:
Example 1.11:
class StaticBlock{
static double x;
static int y=10;
static{ //Static Block
System.out.println("Inside the static block");
x=Math.sqrt(2.0);
}
void print(){
System.out.println("X= " + x +"\nY= " + y);
}
}
class StaticDemoB{
public static void main(String[] args){
StaticBlock sb1=new StaticBlock();
sb1.print();
}
}
------
}
Example 1.13:
class VarArgs{
static void vaTest(int ...v){
System.out.println("Number of Arguments: " + v.length);
System.out.println("Contents");
for(int i=0;i<v.length;i++){
System.out.println("Arg " + (i+1) +": "+ v[i] + "\n");
}
}
public static void main(String[] args){
vaTest(10);
vaTest(1,2,3,4);
vaTest();
}
}
Additional Examples
❖ Mathematical definition
Mathematical definition
Inheritance
class Employee{
float salary = 40000;
}
class Programmer extends Employee {
int bonus = 10000;
public static void main(String args[]){
Programmer p = new Programmer();
System.out.println("Programmer salary is:" + p.salary);
System.out.println("Bonus of Programmer is " + p.bonus);
}
}
Methods of Inheritance
• By extending a class:
• By implementing an interface:
Types of Inheritance:
There can be five types of inheritance:
1. Single or Simple Inheritance
2. Multilevel Inheritance
3. Hierarchical Inheritance
4. Multiple Inheritance
5. Hybrid Inheritance Supported by interface only
2. Multi-Level Inheritance:
There is just one base and one derived class at the same time at one level. At next level, the derived class becomes
base class for the next derived class.
class Base{
Syntax: class Base
//methods and fields of Base class
}
extends
class Derived1 extends Base{
class Derived1 //methods and fields of Derived class
}
extends class Derived2 extends Derived1{
//methods and fields of Derived class
class Derived2 }
3. Hierarchical Inheritance:
Multiple classes share the same base class i.e., number of classes inherit the properties of same base class. The
derived class may also become base class for other class.
class Base{
Syntax: class Base
//methods & fields of Base
}
class Derived1 extends Base{
extends
//methods & fields of Derived
class Derived1 class Derived2 }
class Derived2 extends Base{
extends //methods & fields of Derived
}
class Derived3 class Derived4
4. Multiple Inheritance:
A child can have more than one parent ie., a child can inherit properties from more than one base class. Doesn’t
support, but it support using interface.
Syntax:
class Base1 class Base2
extends Doesn’t support, but it support
using interface.
class Derived
class Derived3
• Java has a special access modifier known as protected which is meant to support Inheritance in Java.
• Any protected member including protected method and field are accessible for classes of same package and only
Sub class outside the package.
class Base{
Base(){
System.out.println("Base class constructors called");
}
}
class Derived extends Base{
Derived(){
System.out.println("Derived class constructors called");
}
}
public class Constructs{
public static void main(String[] args){
Derived obj=new Derived();
}
}
In the above example, when the object obj is created for the class Derived; the default constructor of a base class
Base is called automatically before the logic of the custom Derived constructor is executed.
When both the superclass and subclass define parameterized constructor, then the process is a bit more
complicated because both the superclass and subclass parameterized constructor must be executed. In this case,
“super” keyword can be used.
class SuperC{
SuperC() {
System.out.println("Default constructor of super");
}
SuperC(String str){
System.out.println("Constructor of super displays :" + str);
}
}
class Sub extends SuperC{
Sub() {
super();
System.out.println("Constructor of Subclass");
}
Sub(String s1) {
super(s1);
System.out.println("parameter passed to Subclass");
}
}
class SuperDemo {
public static void main(String args[]){
Sub Ob = new Sub();
Sub Ob1=new Sub("RNSIT");
}
}
class Parent{
int i;
void show(){
System.out.println("i = " + i);
}
}
class Child extends Parent{
int i; //this i hides the i in A
class Animal{
public void move(){
System.out.println("Animals can move");
}
}
class Dog extends Animal{
public void move(){
System.out.println("Dogs can walk and run");
}
}
public class TestDog{
public static void main(String args[]){
// Animal reference but Dog object
Animal bullDog = new Dog();
//Runs the method in Dog class
bullDog.move();
}
}
class Animal{
public void move(){
System.out.println("Animals can move");
}
}
class Dog extends Animal{
public void move(){
System.out.println("Dogs can walk and run");
}
}
class Snake extends Animal{
public void move(){
System.out.println("Snake can't walk But run");
}
}
public class TestAnimalD{
public static void main(String args[]){
Animal animal = new Animal();
Snake cobra = new Snake();
Dog bullDog = new Dog();
Abstract Method:
An abstract method is a method that is declared without an implementation (without braces and followed by a
semicolon).
Syntax:
abstract Return-Type MyAbstractClass(arg-list);
p.setColor("Red");
System.out.println(p.getColor());
}
}
“final” variable:
If you make any variable as final, you cannot change the value of final variable (It will be constant).
Points
• a final variable that have no value it is called blank final variable or uninitialized final variable.
• Non-static final variable can be initialized either in the constructor or with the declaration.
• The static final variable can’t be assigned value in constructor; they must be assigned in the static block
only.
Example 2.12:
class FinalVar{ static{
final int i=90; //final variable x=100;
final int j;//blank final variable System.out.println("X= "+ x);
final static int x;//non-static final }
FinalVar(){ public static void main(String a[])
j=10; {
System.out.println("J= "+ j); FinalVar obj=new FinalVar();
} obj.run();
void run(){ }
//i=400; //can’t modified }
System.out.println("i= "+ i);
}
“final” Class:
• When a class is declared as final, it cannot be extended further.
• All methods in a final class are implicitly final.
Example 2.14:
final class Stud{
void show() {
System.out.println("Class - stud : method defined");
}
}
class Books extends Stud {
void show(){
System.out.println("Class - books : method defined");
}
}
class FinalCla{
public static void main(String args[]) {
Books B2 = new Books();
B2.show();
}
}
Example: Consider you have a super class called Circle and Subclass called PlaneCircle then it can be viewed
as shown below.
Object defines the following methods, which means that they are available in every object.
Method Purpose
Object clone() Creates a new object that is the same as the object being cloned.
boolean equals(Object object) Determines whether one object is equal to another.
void finalize() Called before an unused object is recycled
Class<?>getClass() Obtains the class of an object at run time
int hashCode() Returns the hash code associated with the invoking object
public final void notify() Resumes execution of a thread waiting on the invoking object
public final void notify All() Resumes execution of all threads waiting on the invoking objects
String toString() Returns a string that describes the object
void wait() Waits on another thread of execution
public final void wait (long milliseconds) throws InterruptedException
public final void wait (long milliseconds, int nanoseconds) throws InterruptedException
Questions: