Download as pdf or txt
Download as pdf or txt
You are on page 1of 24

Object Oriented Programming Using Java 22MCA22

MODULE-2
MULTIPLE INHERITANCE

Inheritance
• Java, Inheritance is an important pillar of OOP(Object-Oriented
Programming).
• It is the mechanism in Java by which one class is allowed to inherit the
features(fields and methods) of another class.
• In Java, Inheritance means creating new classes based on existing ones.
• A class that inherits from another class can reuse the methods and fields of
that class.
• Inheritance represents the IS-A relationship which is also known as
a parent-child relationship.

Why Do We Need Java Inheritance?
• Code Reusability: The code written in the Superclass is common to all
subclasses.
• Child classes can directly use the parent class code.
• Method Overriding: Method Overriding is achievable only through
Inheritance. It is one of the ways by which Java achieves Run Time
Polymorphism.
• Abstraction: The concept of abstract where we do not have to provide all
details is achieved through inheritance. Abstraction only shows the
functionality to the user.

Terms used in Inheritance


• Class: A class is a group of objects which have common properties. It is a
template or blueprint from which objects are created.
• Sub Class/Child Class: Subclass is a class which inherits the other class. It
is also called a derived class, extended class, or child class.
• Super Class/Parent Class: Superclass is the class from where a subclass
inherits the features. It is also called a base class or a parent class.
• Reusability: As the name specifies, reusability is a mechanism which
facilitates you to reuse the fields and methods of the existing class when you
create a new class. You can use the same fields and methods already defined
in the previous class.

The syntax of Java Inheritance


class Subclass-name extends Superclass-name
{
//methods and fields
}
The extends keyword indicates that you are making a new class that
derives from an existing class
class Employee
{
float salary=40000;
}
class Programmer extends Employee
{
int bonus=10000;

YOGEESH S Page 1
Object Oriented Programming Using Java 22MCA22

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

Types of inheritance in java


• On the basis of class, there can be three types of inheritance in java:
o Single,
o Multilevel
o Hierarchical.
• In java programming, multiple and hybrid inheritance is supported through
interface only.

• When one class inherits multiple classes, it is known as multiple


inheritance.

YOGEESH S Page 2
Object Oriented Programming Using Java 22MCA22

• Java does not support Multiple Inheritance by extending a class.


• Multiple inheritance can be achieved using implementing a interface.

extends

Single Inheritance
• When a class inherits another class, it is known as a single inheritance.
Example:
class Animal
{
void run()
{
System.out.println("MCA");
}
}
class Dog extends Animal
{
void display()
{
System.out.println("MBA");
}
}
class Single
{
public static void main(String args[])
{
Dog d=new Dog();
d.run();
d.display();
}
}

YOGEESH S Page 3
Object Oriented Programming Using Java 22MCA22

Multilevel Inheritance
• When there is a chain of inheritance, it is known as multilevel inheritance.
Example
class Animal
{
void run()
{
System.out.println("MCA");
}
}
class Dog extends Animal
{
void display()
{
System.out.println("MBA");
}
}
class Cat extends Dog
{
void ball()
{
System.out.println("BCA");
}
}
class multilevel
{
public static void main(String args[])
{
Cat d=new Cat();
d.ball();
d.run();
d.display();
}
}

Hierarchical Inheritance
• When two or more classes inherits a single class, it is known as
hierarchical inheritance.
Example
class Animal
{
void run()
{
System.out.println("MCA");
}
}
class Dog extends Animal
{
void display()
{
System.out.println("MBA");
}
}

YOGEESH S Page 4
Object Oriented Programming Using Java 22MCA22

class Cat extends Animal


{
void ball()
{
System.out.println("BCA");
}
}
class hierarchical
{
public static void main(String args[])
{
Cat d=new Cat();
d.ball();
d.run();

}
}

Access Modifiers in Java


• There are four types of Java access modifiers:
• Private: The access level of a private modifier is only within the class.
• It cannot be accessed from outside the class.
• Default: The access level of a default modifier is only within the package.
• It cannot be accessed from outside the package.
• If you do not specify any access level, it will be the default.
• Protected: The access level of a protected modifier is within the package and
outside the package through child class.
• If you do not make the child class, it cannot be accessed from outside the
package.
• Public: The access level of a public modifier is everywhere.
• It can be accessed from within the class, outside the class, within the
package and outside the package.

Example for private
class Employee
{
private float salary=400;
}
class privatee extends Employee
{
int bonus=100;
public static void main(String args[])
{
privatee p=new privatee();
System.out.println("Programmer salary is:"+p.salary);
System.out.println("Bonus of Programmer is:"+p.bonus);
}
} //compile time error

YOGEESH S Page 5
Object Oriented Programming Using Java 22MCA22

Class member access

having default access modifier are accessible only within the same package.

Using super to call super class constructors


• The super keyword in java is a reference variable that is used to refer
immediate parent class object.
• Whenever you create the instance of subclass, an instance of parent class is
created implicitly i.e. referred by super reference variable.
Usage of java super Keyword
• super is used to refer immediate parent class instance variable.
• super() is used to invoke immediate parent class constructor.
• super is used to invoke immediate parent class method.
Ex:1
class Animal
{
String color="white";
}
class Dog extends Animal
{
String color="black";
void printColor()
{
System.out.println(color); //black
}
}
class TestSuper1
{
public static void main(String args[])
{
Dog d=new Dog();
d.printColor();
}
}

YOGEESH S Page 6
Object Oriented Programming Using Java 22MCA22

Ex:1 Using super (super using access instatnce variable)


class Animal
{
String color="white";
}
class Dog extends Animal
{
String color="black";
void printColor()
{
System.out.println(super.color); //white
}
}
class TestSuper1
{
public static void main(String args[])
{
Dog d=new Dog();
d.printColor();
}
}

EX:2 for constructor


class Animal
{
Animal()
{
System.out.println("BANGALORE");
}
}
class Dog extends Animal
{
Dog()
{
super(); //invoke parent class constructor
System.out.println("HYDERABAD");
}
}
class Bike5
{
public static void main(String args[])
{
Dog d=new Dog();
}
}

Example3 for super method


class Animal
{
void eat()
{
System.out.println("delhi");
}
}

YOGEESH S Page 7
Object Oriented Programming Using Java 22MCA22

class Dog extends Animal


{
void eat()
{
System.out.println("hyderabad");
}
void bark()
{
System.out.println("bangalore");
}
void work()
{
super.eat();
bark();
}
}
class TestSuper2
{
public static void main(String args[])
{
Dog d=new Dog();
d.work();
}
}

Final Keyword In Java


• The final keyword in java is used to restrict the user. The java final keyword
can be used in many context. Final can be:
- variable
- method
- class
- final variable
• If you make any variable as final, you cannot change the value of final
variable(It will be constant).

final method
• If you make any method as final, you cannot override it.

final class
• If you make any class as final, you cannot extend it.

Example for final variable


class Bike9
{
final int speedlimit=90;
void run()
{
speedlimit=400;
System.out.println(speedlimit);
}
public static void main(String args[])
{
Bike9 obj=new Bike9();

YOGEESH S Page 8
Object Oriented Programming Using Java 22MCA22

obj.run();
}
}
//compile time error

Example for final method


class Bike
{
final void run()
{
System.out.println("running");
}
}
class Honda10 extends Bike
{
void run()
{
System.out.println("running safely with 100kmph");
}
}
class Honda10
{
public static void main(String args[])
{
mca a= new mca();
a.run();
}
}
//compile time error

Example for final class


final class Bike
{
int a=10;
}
class Honda1 extends Bike
{
int b;
}
class finalc
{
public static void main(String args[])
{
Honda1 a= new Honda1();
a.b=25;
}
}

//compile time error

YOGEESH S Page 9
Object Oriented Programming Using Java 22MCA22

Object class in Java


• The Object class is the parent class of all the classes in java by default. In
other words, it is the topmost class of java.
• Object class is present in java.lang package.
• Every class in Java is directly or indirectly derived from the Object class.
• If a class does not extend any other class then it is a direct child class
of Object and if extends another class then it is indirectly derived.
• Therefore the Object class methods are available to all Java classes.
class Vehicle
{
//body of class Vehicle
}
• Here we can see that the class Vehicle is not inheriting any class, but it
inherits the Object class. It is an example of the direct inheritance of object
class.
class Vehicle
{
//body of class Vehicle
}
class Car extends Vehicle
{
//body of class Car
}
• Here we can see that the Car class directly inherits the Vehicle class. the Car
indirectly inherits the Object class.

YOGEESH S Page 10
Object Oriented Programming Using Java 22MCA22

Object Class Methods


• The Object class provides multiple methods which are as follows:
o toString() method
o hashCode() method
o equals(Object obj) method
o finalize() method
o getClass() method
o clone() method
o wait(), notify() notifyAll() methods

toString() method
• If you want to represent any object as a string, toString() method comes into
existence.
• The toString() method returns the String representation of the object.
• If you print any object, Java compiler internally invokes the toString()
method on the object. So overriding the toString() method, returns the
desired output, it can be the state of an object etc. depending on your
implementation.

Example

class Student12
{
int rollno;
String name;
String city;
Student12(int rollno, String name, String city)
{
this.rollno=rollno;
this.name=name;
this.city=city;
}
public String toString()
{
return rollno+" "+name+" "+city;
}

public static void main(String args[])


{
Student12 s1=new Student12(101,"Raj","lucknow");
Student12 s2=new Student12(102,"Vijay",“Delhi");
System.out.println(s1);
System.out.println(s2);
}

YOGEESH S Page 11
Object Oriented Programming Using Java 22MCA22

hashCode() Method
• The hashCode() method is a Java Integer class method which returns the
hash code for the given inputs.

public class Hash


{
public static void main(String[] args)
{

Integer i = new Integer("12");


int b = i.hashCode();
System.out.println("Hash code Value for object is: " + b);
}
}

equals(Object obj) method


equals(Object obj) is the method of Object class. This method is used to

compare the given objects.
Syntax
public boolean equals(Object obj)

It returns true if this object is same as the obj argument else it returns false
otherwise.

class kiran
{
int a=25;
}
class bangaluru
{
public static void main(String[] args)
{
kiran s1 = new kiran();
kiran s2 = new kiran();
System.out.println(s1.equals(s2)); //false
kiran s3=s1;
System.out.println(s1.equals(s3)); //true
}
}

getClass() Method
• getClass() is the method of Object class. This method returns the runtime
class of this object.
public class Objectget
{
public static void main(String[] args)
{
Object obj = new String("23");
Class a = obj.getClass();
System.out.println("Class of Object obj is : " + a.getName());
}
}
Output: Class of Object obj is : java.lang.String

YOGEESH S Page 12
Object Oriented Programming Using Java 22MCA22

Polymorphism in Java
• Polymorphism in Java is a concept by which we can perform a single action
in different ways.
• Polymorphism is derived from 2 Greek words: poly and morphs. The word
"poly" means many and "morphs" means forms. So polymorphism means
many forms.
• There are two types of polymorphism in Java: compile-time polymorphism
and runtime polymorphism. We can perform polymorphism in java by
method overloading and method overriding.
• If you overload a static method in Java, it is the example of compile time
polymorphism. Here, we will focus on runtime polymorphism in java.
Runtime Polymorphism in Java
• Runtime polymorphism or Dynamic Method Dispatch is a process in which a
call to an overridden method is resolved at runtime rather than compile-
time.
• In this process, an overridden method is called through the reference
variable of a superclass.
• The determination of the method to be called is based on the object being
referred to by the reference variable.
Upcasting
• If the reference variable of Parent class refers to the object of Child class, it
is known as upcasting.
Example
class Bike
{
void run()
{
System.out.println("running");
}
}
class Splendor extends Bike
{
void run()
{
System.out.println(“RNSIT");
}
public static void main(String args[])
{
Bike b = new Splendor(); //upcasting
b.run();
}
}

Method overriding
• If subclass (child class) has the same method as declared in the parent
class, it is known as method overriding in java.
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
• method must have same parameter as in the parent class.

YOGEESH S Page 13
Object Oriented Programming Using Java 22MCA22

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

EX:2
class A
{
int i, j;
A(int a, int b)
{
i = a;
j = b;
}
void show()
{
System.out.println("i and j: " + i + " " + j);
}
}
class B extends A
{
int k;
B(int a, int b, int c)
{
super(a, b);
k = c;
}
void show()
{
System.out.println("k: " + k);
}
}
class Override
{
public static void main(String args[])
{
B sub = new B(1, 2, 3);
sub.show();

YOGEESH S Page 14
Object Oriented Programming Using Java 22MCA22

}
}
EX:3
class Animal
{
void move()
{
System.out.println("Animals can move");
}
}
class Dog extends Animal
{
void move()
{
super.move();
System.out.println("Dogs can walk and run");
}
}
public class TestDog
{
public static void main(String args[])
{
Animal b = new Dog(); // Animal reference but Dog object
b.move(); // runs the method in Dog class
}
}

Difference between method overloading and method overriding in java

Method Overloading Method Overriding

Method overloading is used to increase Method overriding is used to provide


the readability of the program. the specific implementation of the
method that is already provided by its
super class.
Method overloading is performed within Method overriding occurs in two
class. classes.

In case of method overloading, In case of method overriding,


parameter must be different parameter must be same.

Method overloading is the example of Method overriding is the example of run


compile time polymorphism. time polymorphism.

Return type can be same or different Return type must be same

YOGEESH S Page 15
Object Oriented Programming Using Java 22MCA22

Abstract classes
• A class that is declared with abstract keyword, is known as abstract class in
java. It can have abstract and non-abstract methods (method with body).
• Before learning java abstract class, let's understand the abstraction in java
first.
• Abstraction is a process of hiding the implementation details and showing
only functionality to the user.
• Another way, it shows only important things to the user and hides the
internal details.
• A method that is declared as abstract and does not have implementation is
known as abstract method.
Ex:1
abstract class Bike
{
abstract void run();
}
class Honda4 extends Bike
{
void run()
{
System.out.println("running safely..");
}
public static void main(String args[])
{
Bike obj = new Honda4();
obj.run();
}
}

Ex: 2
abstract class Shape
{
abstract void draw();
}
class Rectangle extends Shape
{
void draw()
{
System.out.println("drawing rectangle");
}
}
class Circle1 extends Shape
{
void draw()
{
System.out.println("drawing circle");
}
}
class TestAbstraction1
{
public static void main(String args[])
{
Shape s=new Circle1();

YOGEESH S Page 16
Object Oriented Programming Using Java 22MCA22

s.draw();
}
}

Example of abstract class that have method body


abstract class Bike
{
Bike()
{
System.out.println("bike is created");
}
abstract void run();
void changeGear()
{
System.out.println("gear changed");
}
}
class Honda extends Bike
{
void run()
{
System.out.println("running safely..");
}
}
class TestAbstraction3
{
public static void main(String args[])
{
Bike obj = new Honda();
obj.run();
obj.changeGear();
}
}

String class in Java


• String is a sequence of characters.
• In java, objects of String are immutable which means a constant and cannot
be changed once created.
• Creating a String
• There are two ways to create string in Java:
• String literal
String s = “RNSIT”;
• Using new keyword
String s = new String (“BANGALORE);

String class has a variety of methods for string manipulation.


1. charAt(int index)
• This method requires an integer argument that indicates the position of
the character that the method returns.
• This method returns the character located at the String's specified index.
Example: //stringg.java
String x = "airplane";
System.out.println( x.charAt(2) ); // output is 'r'

YOGEESH S Page 17
Object Oriented Programming Using Java 22MCA22

2.concat(String s)
• This method returns a String with the value of the String passed in to the
method appended to the end of the String used to invoke the method.
Example
String x = "book";
System.out.println( x.concat("author") );
// output is "bookauthor"
The overloaded + and += operators perform functions similar to the
concat()method
Example,
String x = "library";
System.out.println( x + " card");
// output is "library card"
String x = "United";
x += " States”
System.out.println( x );
// output is "United States"

3.equalsIgnoreCase(String s)
• This method returns a boolean value (true or false) depending on whether
the value of the String in the argument is the same as the value of the String
used to invoke the method.
Example
String x = "Exit"; System.out.println(x.equalsIgnoreCase("EXIT")); // is "true"
System.out.println(x.equalsIgnoreCase("tixe")); // is "false"

4. length()
• This method returns the length of the String used to invoke the method.
Example,
String x = "01234567";
System.out.println( x.length() ); // returns "8“

5. replace(char old, char new)


• This method returns a String whose value is that of the String used to
invoke the method, updated so that any occurrence of the char in the first
argument is replaced by the char in the second argument
Example
class stringg
{
public static void main(String args[])
{
String x = "RNSNT";
System.out.println( x.replace('N', 'n') );
}
}

Output
RnSnT

YOGEESH S Page 18
Object Oriented Programming Using Java 22MCA22

5. String substring(int begin)


Syntax
substring(int begin, int end)
• The substring() method is used to return a part (or substring) of the String
used to invoke the method.
• The first argument represents the starting location (zero-based) of the
substring. If the call has only one argument, the substring returned will
include the characters to the end of the original String.
• If the call has two arguments, the substring returned will end with the
character located in the nth position of the original String where n is the
second argument.
Example
class SubStr
{
public static void main(String[] args)
{
String orgstr = "RNSIT BANGALORE";
String k= orgstr.substring(3); //IT BANGALORE
String substr = orgstr.substring(7,11); //ANGA
System.out.println(k);
System.out.println("substr: " + substr);
}
}

6. toLowerCase()
• This method returns a String whose value is the String used to invoke the
method, but with any uppercase characters converted to lowercase.
Example,
String x = "A New Java Book";
System.out.println( x.toLowerCase() );
// output is "a new java book"

7. toUpperCase()
• This method returns a String whose value is the String used to invoke the
method, but with any lowercase characters converted touppercase.
Example,
String x = "A New Java Book"; System.out.println( x.toUpperCase());
// output is"A NEW JAVA BOOK"

8. trim() method
• The String class trim() method eliminates white spaces before and after the
String.
Example
class Stringoperation2
{
public static void main(String ar[])
{
String s=" Sachin ";
System.out.println(s.trim());//Sachin
}
}

YOGEESH S Page 19
Object Oriented Programming Using Java 22MCA22

9. char[ ] toCharArray( )
• This method will produce an array of characters from characters of String
object.
Example
String s = “Java”;
Char [] mca = s.toCharArray();

10. boolean contains(“searchString”)


• This method returns true of target String is containing search String
provided in the argument.
Example-
String x = “Java is programming language”;
System.out.println(x.contains(“Amit”)); // false
System.out.println(x.contains(“Java”)); // true
Complete program
StringMethodsDemo.java

Parameter Passing
• People usually take the pass by value and pass by reference terms together.
• It is really confusing and overhear questions in interviews, Is java pass by
value or passes by reference, or both? So the answer to this question is Java
is strictly pass by value.
• There is no pass by reference in Java.
• People usually take the pass by value and pass by reference terms together.
• It is really confusing and overhear questions in interviews, Is java pass by
value or passes by reference, or both? So the answer to this question is Java
is strictly pass by value.
• There is no pass by reference in Java.
• Pass by Value: In the pass by value concept, the method is called by passing
a value.
• So, it is called pass by value. It does not affect the original parameter.
• Pass by Reference: In the pass by reference concept, the method is called
using an alias or reference of the actual parameter.
• So, it is called pass by reference. It forwards the unique identifier of the
object to the method.
• If we made changes to the parameter's instance member, it would affect the
original value.
Example1:
class Test
{
void display(int i, int j)
{
i *= 2;
j += 2;
}
}

class CallByValue
{
public static void main(String args[])
{
Test ob = new Test();
int a = 15, b = 20;

YOGEESH S Page 20
Object Oriented Programming Using Java 22MCA22

System.out.println("a and b before call: " +a + " " + b);


ob.display(a, b);
System.out.println("a and b after call: " +a + " " + b);
}
}
Output
a and b before call: 15 20
a and b after call: 15 20

Example2:
class Test
{
int a, b;
Test(int i, int j)
{
a = i;
b = j;
}
void Display(Test o)
{
o.a *= 2;
o.b /= 2;
}
}
class CallByRef
{
public static void main(String args[])
{
Test ob = new Test(15, 10);
System.out.println("ob.a and ob.b before call: " + ob.a+ " " + ob.b);
ob.Display(ob);
System.out.println("ob.a and ob.b after call: " +ob.a + " " + ob.b);
}
}
Output
ob.a and ob.b before call: 15 10
ob.a and ob.b after call: 30 5

ENUMERATION:
• Enumeration is a list of named constants that define a new data type.
• An object of an enumeration type can hold only the values that are defined
by the list.
• Thus , an enumeration gives you a way to precisely define a new type of data
that has a fixed number of valid values.
• An enumeration is created using the enum keyword.
Ex:
enum Transport
{
CAR, TRUNK, TRAIN, BUS
}
• The identifiers CAR, TRUNK and so on are called enumeration constants or
enum constants.
• Each is implicitly declared as a public, static member of Transport.

YOGEESH S Page 21
Object Oriented Programming Using Java 22MCA22

• Once you have declared an enumeration, you can create a variable of that
type.
• Even though enumerations define a class type, you do not instantiate an
enum using new.
Ex:
Transport tp;
• Because tp is of type of Transport, the only values that it can be assigned
are those constants defined by the enumeration or null.
Ex:
tp= Transport.BUS;
• Here BUS is assiged to tp.
• Two enumeration constant can be compared for equality by using the ==
relational operator.
Ex:
if(tp==Transport.CAR)
• Here this statement compares the value in tp with the CAR.
• An enumeration value can also be used to control a switch statement.

Example for switch


class MCA
{
enum Day { SUNDAY, MONDAY, TUESDAY, WEDNESDAY }
public static void main(String args[])
{
Day a=Day.MONDAY;
switch(a)
{
case SUNDAY:
System.out.println(“hello");
break;
case MONDAY:
System.out.println(“hello java");
break;
default: System.out.println("other day");
}
}
}
• The enum can be defined within or outside the class because it is similar to
a class.

enum Season
{
WINTER, SPRING, SUMMER, FALL
}
class EnumExample2
{
public static void main(String[] args)
{
Season s=Season.WINTER;
System.out.println(s);
}
}

YOGEESH S Page 22
Object Oriented Programming Using Java 22MCA22

Example
enum NAMES
{
RAGHU, PRASAD, DEVA, SHIVA,KIRAN
}
class EnumExample3
{
public static void main(String[] args)
{
NAMES s=NAMES.RAJ;
System.out.println(s);
}
}
D:\raghu java practice>javac EnumExample3.java
EnumExample3.java:9: cannot find symbol
symbol : variable RAJ
location: class NAMES
NAMES s=NAMES.RAJ;
^
1 error

The values() AND valueOf() methods OR the built-in enumeration methods:


• All enumerations automatically have two predefined methods:
values()
valuesOf()
• Their general forms are
public static enum-type[] values()
public static enum-type valueOf(String str)
• The java compiler internally adds the values() method when it creates an
enum.
• The values() method returns an array containing all the values of the enum.
• The valuesOf() returns the enumeration value associated with the name of
the constant represented as a string.

Example for values():

class hello{
public enum Season
{
WINTER, SPRING, SUMMER, FALL
}
public static void main(String[] args)
{
for (Season s : Season.values())
System.out.println(s);
}
}

YOGEESH S Page 23
Object Oriented Programming Using Java 22MCA22

Example for valuesOf():

class EnumExample1{
public enum Season {
WINTER,
SPRING,
SUMMER,
FALL
}
public static void main(String[] args)
{
for (Season s : Season.values())
System.out.println(s);
Season a = Season.valueOf("SUMMER");
System.out.println("the value of a is");
System.out.println(a);
}
}

OUTPUT WINTER
SPRING
SUMMER
FALL
the value of a is
SUMMER

YOGEESH S Page 24

You might also like