0% found this document useful (0 votes)
111 views99 pages

Unit - 2 Introduction To Object-Oriented Programming

The document provides an overview of key concepts in object-oriented programming including classes, objects, encapsulation, inheritance, polymorphism, and more. It defines a class called Car with attributes like color and brand and methods like accelerate and brake. It then discusses core OOP concepts like abstraction, encapsulation, inheritance and polymorphism providing examples for each. It also covers other topics like constructors, accessing class members, setter and getter methods, and provides exercises to apply the concepts.

Uploaded by

hitesh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
111 views99 pages

Unit - 2 Introduction To Object-Oriented Programming

The document provides an overview of key concepts in object-oriented programming including classes, objects, encapsulation, inheritance, polymorphism, and more. It defines a class called Car with attributes like color and brand and methods like accelerate and brake. It then discusses core OOP concepts like abstraction, encapsulation, inheritance and polymorphism providing examples for each. It also covers other topics like constructors, accessing class members, setter and getter methods, and provides exercises to apply the concepts.

Uploaded by

hitesh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 99

Unit – II Introduction to Object-oriented

Programming
• Basic concepts of object-oriented programming
• Classes, instances, methods
• Static and non-static members

P
• Packages


PP
Inheritance and polymorphism, method overriding
Final and abstract classes, abstract methods
• Interfaces
• Generics, enumeration
• Inner classes and anonymous classes
• Class loaders, class path
• Class
Basic Concepts of OOP
– A blueprint/template that describes the behavior/state that
the object of its type support.
– E.g. A class Car that has
• State (Attributes) :: Color, Brand, Weight, Model
• Behaviors (Methods) :: Break, Accelerate, Slow Down, Gear Change

P
– This is just a blueprint, it does not represent any Car, however
using this we can create Car objects (or instances) that represents
the car.
• Object
PP
– It is an instance of class.
– When the objects are created, they inherit all the variables and
methods from the class.
E.g.
– Objects : Audi, Toyota, Volvo, Maruti, Honda
• Class
Basic
: Fruit
Concepts of OOP
• Objects : Orange, Mango, Banana etc.

• Class : Shape
• Objects : Square, Rectangle, Triangle, Circle etc.

P
• Class : Pen
• Objects PP
: Reynold, Parker , Camlin, Luxor etc.

• Class : Bicycle
• Objects : SportsBicycle, MountainBicycle , TouringBicycle etc.

• Class : Department
• Objects : Sales , Purchase, Finance, HR etc.
class Car {
Basic Concepts of OOP
String color;
String brand;
int weight;
String model;
void break() {
//Write code here

P
}
void accelerate() {

}
//Write code herePP
void slow_Down() {
//Write code here
}
void gear_change() {
//Write code here
}
}
Basic Concepts of OOP
• Abstraction
– A process where you show only “relevant” data and “hide”
unnecessary details of an object from the user.
– E.g. The person only knows that pressing the accelerators
will increase the speed of car or applying brakes will stop
the car, but he/she does not know about the inner

P
mechanism of the accelerator, brakes etc in the car.
PP
– E.g. When you login to your bank account online, you
enter your user_id and password and press login, what
happens when you press login, how the input data sent to
server, how it gets verified is all abstracted away from the
you
– In Java, we use abstract class and interface to achieve
abstraction.
Basic Concepts of OOP
• Encapsulation
– Binding object state(fields / attributes) and
behavior(methods) together.
– E.g.
• A Class is an example of encapsulation.

P
• Inform what the object does instead of how it does.
• Keep data and methods safe from outside
PP
interference or misuse.
• Inheritance
Basic Concepts of OOP
– The process by which one class acquires the properties and
functionalities of another class is called inheritance.
– Inheritance provides the idea of reusability of code and each sub
class defines only those features that are unique to it, rest of the
features can be inherited from the parent class.

P
– E.g. A parent class Teacher and a child class MathTeacher. In the
MathTeacher class we need not to write the same code which is
PP
already present in the parent class.
– E.g. In Class Teacher methods are Teacher_Info, Attendance_Info,
Classwork_Video etc.
– E.g. In Class MathTeacher methods are Word_Problems, Patterns.
Basic Concepts of OOP
• Polymorphism
– It allows us to perform a single action in different ways.

– E.g. Addition of two numbers.


Both numbers may be int, float, double etc.

P
PP
– E.g. Area of 2D shape :
Formula is different for Rectangle, Square, Triangle

– In Java, we use method overloading and method


overriding to achieve polymorphism.
General form of a class definition
class class-name
{
dat type variable 1;
dat type variable 2;
…………………………………………….
dat type variable N;

P
data type method-name 1 ( parameter –list 1 ) { body of method }
PP
data type method-name 2 ( parameter –list 1 ) { body of method }
……………………………………………………………………………………………………..

data type method-name N ( parameter –list 1 ) { body of method }


}
Instance of a Class

class-name instance-name = new class-name( )

P
E.g.
PP
Integer obj1 = new Integer();
Scanner sc = new Scanner(System.in);
String str1 = new String();
Example of Garbage Collection
Integer obj1 = new Integer (5);

System.out.println(obj1);

P
obj1 = new Integer(6);
PP
System.out.println(“ Integer (5) can be recycled”);
Constructor
•Special method that create and initialize an object of particular
class.

•It has the same name as its class & may accepts arguments.

P
•It does not have return type.

PP
•If you do not declare explicit constructor, Java compiler
automatically generate a default constructor that has no
arguments.

•It does not call directly, it is invoked via the new operator.

•Class may have multiple constructor it is called constructor


overloading.
Default Constructor

class Point2D {
double x ;
double y ;

P
PP
point2D ( ) {
x = 0;
y = 0;
}
}
Parameterized Constructor

class Point2D {
double x ;
double y ;

P
PP
point2D ( double ax , double ay ) {
x = ax ;
y = ay ;
}
}
Constructor Overloaded
class Point2D {
double x ;
double y ;

point2D ( ) {

P
x = 0;
y = 0;
}
PP
point2D ( double ax , double ay ) {
x = ax ;
y = ay ;
}
}
class Point2D {
double x ; Example of
double y ;
Constructor Overloaded
point2D ( ) {
x = 0;
y = 0;
}

point2D ( double ax , double ay ) {

P
x = ax ;
y = ay ;
}
PP
displayPointCoordinates ( ) {
System.out.println ( “ X co-ordinate value is :: “ + x ) ;
System.out.println ( “ Y co-ordinate value is :: “ + y ) ;
}
}

Class point2DConstructor {
public static void main ( String args [ ] ) {
Point2D p1 = new Point2D (); p1.displayPointCoordinates()
Point2D p2 = new Point2D ( 3 , 4 ); p2.displayPointCoordinates() ;
}
}
Access Class Member Variables
class Product{
int prod_no;
String prod_name ; }

public class Test {


public static void main ( String args[] ) {
Product p1 = new Product();

P
p1.prod_no = 1;
p1.prod_name="Mouse";
PP
System.out.println("P1 object Product No. ::" + p1.prod_no);
System.out.println("P1 object Product Name. ::" + p1.prod_name);

Product p2 = new Product();


p2.prod_no = 2;
p2.prod_name="Printer";
System.out.println("P2 object Product No. ::" + p2.prod_no);
System.out.println("P2 object Product Name ::" + p2.prod_name);
}
Set Data & Get Data Method in Class
class Product {
int prod_no;
String prod_name ;

// Set data
void set_data(int p , String p_name) {

P
prod_no = p;
prod_name = p_name;
}

// Get Data
PP
void get_data(){
System.out.println("Product No. : " + prod_no);
System.out.println("Product Name : " + prod_name);
}
}
Set Data & Get Data Method in Class
class Test {
public static void main ( String args[] )
{
Product p1 = new Product();
p1.set_data(1,"Mousse");

P
p1.get_data();

PP
Product p2 = new Product();
p2.set_data(2,"Printer");
p2.get_data();
}

}
Exercise
1. Write a java program to create a class named Rectangle
having member variable length and breadth. Define
various constructors with and without arguments. Also
create two methods area and perimeter.
(Formulas : Area = length * breadth &
Perimeter = 2 * ( length + breadth)

P
PP
2. Write a java program to create a class named Square
having member variable length. Define constructor with
and without arguments. Also create two methods area
and perimeter.
(Formulas : Area = length * length
Perimeter = 4 * ( length )
Exercise
3. Write a java program to create a class named circle having
member variable radius. Also create two methods area
and circumference. Initialize the radius value by
constructor or setRadius() method.
(Formulas : Area = PI * radius * radus &
Circumference = 2 * PI * radius)

P
4. Define a Sphere class with two constructors and one
PP
method. The first form of constructor accepts no
arguments. The second form of constructor accepts only
radius of the sphere. The method is to find the area of
sphere. (Formula: Area of sphere = 4* PI * radius * radius)
5. Declare a three class rectangle, square and triangle. Each
class having two methods perimeter and area. Create an
object of each class & find its area and perimeter. Use
constructor overloading concepts in each classes.
Exercise
6. Write a program to accept two integer numbers and one
operator from the user and according to input data apply
the operation on numbers and display the result. (Hint:
Make a class MathOp having methods for addition,
subtraction, division and multiplication.)
7. Write a program to create a class Employee having two

P
member variables emp_id and emp_name. Also methods
PP
to store input data & retrieve output data. Accepts data
of 5 employees from the user & display in proper format.
8. Write a program to create a class for MathFun having
methods even_odd_check, prime_no_check,
palindrome_check, armstrong_check. Create an object of
class, accept one integer number from the user and list
menu for the above methods and according to user choice
display the proper output.
Exercise
9. Write a program to Arr_operation having two methos
sort_data and search_element. Accept N numbers from
the user and choice of operation.
10. Write a program to create a class MatrixOperation having
three methods Mat_Add, Mat_Sub & Mat_Mul. Accepts

P
two matrice from the user and choice of operation.
PP
11. Create a class of student to store the roll_no, stud_name
and marks of 3 subjects. Accepts the data of 5 students
from the user and display the marksheet in proper format.
12. Create a class of product to store product id, product
name, product price and product quantity. Accepts the
data of N products from the user. Also fetch product
details by passing product id or product price.
Exercise
13. Calculate the net salary of an employee by considering the
parameters called HRA(House rent allowance),
DA(Dearness allowance), GS (Gross salary) and income
tax. Let us assume some parameters.
HRA = 10% of basic salary

P
DA = 73% of basic salary
GS =PP
Income tax =
basic salary + DA + HRA
30% of gross salary
net salary = GS - income tax
Take the input from the user N employees name, id and basic
salary and display output in proper format
Access Modifiers in Java
• There are two types of modifiers in Java: access
modifiers and non-access modifiers.

• The access modifiers in Java specifies the accessibility or


scope of a field, method, constructor, or class.

P
• There are four types of Java access modifiers:
PP
o Private
o Default
o Protected
o Public

• There are many non-access modifiers, such as


static, abstract, synchronized, native, volatile,
transient, etc.
Access Modifiers in Java
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.

P
PP
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.
Access Modifiers in Java

P
PP
Access Modifiers in Java
1) Private
The private access modifier is accessible only within the class.
E.g. Two classes A and Test.
A class contains private data member and private method.
Accessing these private members from outside the class, so there is a
compile-time error.

P
class A {
private int data=40;

}
PP
private void msg(){System.out.println("Hello java");}

public class Test {


public static void main(String args[]) {
A obj=new A();
System.out.println(obj.data); //Compile Time Error
obj.msg(); //Compile Time Error
}
}
Access Modifiers in Java
Role of Private Constructor
If you make any class constructor private, you cannot create the
instance of that class from outside the class. So constructor is never a
private.
E.g. :
class A {

P
private A() { } //private constructor
void msg( ) { System.out.println("Hello java"); }
} PP
public class Test{
public static void main(String args[]) {
A obj=new A(); //Compile Time Error
}
}
Access Modifiers in Java
2) Default

•If you don't use any modifier, it is treated as default by


default.

P
•The default modifier is accessible only within package.
PP
•It cannot be accessed from outside the package.

•It provides more accessibility than private. But, it is more


restrictive than protected, and public.
Access Modifiers in Java
E.g. Two packages pack and mypack.
Accessing the A class from outside its package, since A class is not
public, so it cannot be accessed from outside the package.
//save by A.java
package pack;
class A{

P
void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
PP
class B{
public static void main(String args[]){
A obj = new A();//Compile Time Error
obj.msg();//Compile Time Error
}
}
Access Modifiers in Java
3) Protected
•The protected access modifier is accessible within package and outside
the package but through inheritance only.
•The protected access modifier can be applied on the data member,
method and constructor. It can't be applied on the class.
•It provides more accessibility than the default access modifer.

P
E.g.
PP
•Two packages pack and mypack.
•The A class of pack package is public, so can be accessed from outside
the package.
•msg method of this package is declared as protected, so it can be
accessed from outside the class only through inheritance.
Access Modifiers in Java
//save by A.java
package pack;
public class A{
protected void msg(){System.out.println("Hello");}
}

P
//save by B.java
package mypack;
import pack.*;
PP
class B extends A{
public static void main(String args[]){
B obj = new B();
obj.msg();
}
}
Access Modifiers in Java
4) Public
•The public access modifier is accessible everywhere.
•It has the widest scope among all other modifiers.
E.g.
//save by A.java
package pack;

P
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
PP
import pack.*;

class B{
public static void main(String args[]){
A obj = new A();
obj.msg(); } }
Non Access Modifiers:
Java provides a number of non-access modifiers to achieve
many other functionality.

•The static modifier for creating class methods and variables.

P
•The final modifier for finalizing the implementations of
PP
classes, methods, and variables.

•The abstract modifier for creating abstract classes and


methods.

•The synchronized modifiers, which are used for threads.


Static Methods & Variables
Static methods in java belong to the class (not an instance of it)

To call a static methods or variable

classname.methodname(args);

classname.variablename;

P
PP
Static Variables & Methods of Integer Class

MIN_VALUE
MAX_VALUE

P
static
static
PP
Integer
String
valueOf ( String s )
toBinaryString ( int i )
static String toOctalString (int i )
static String toHexString (int i)

static int parseInt ( String s )


Example of Static Methods & Variable
E.g. :: To find area & circumference of a circle.
class AreaCircumference {
public static void main (String args[]) {
double radius=15;
// double area = Math.PI * radius * radius;

P
double area = Math.PI * Math.pow (radius,2)
PP
double cf = 2 * Math.PI * radius;

System.out.println("Radius is : \t" + radius);


System.out.println("Area is : \t" + area);
System.out.println("Circumfernce is : \t" + cf);
} }
Instance Methods & Variables
Method or Variable defined in a class which is only accessible through
the Object of the class

E.g. To access methods of Byte, Short, Integer, Long, Float, Double, Char,
String Class, the object of corresponding class is needed.

P
PP
PP
P
PP
P
class Rectangle Example of Instance Methods
{
private double length = 10.50;
private double width = 20.70;

void setData( double l, double w) {


length = l;
width = w;
}

P
void displayData () {

}
PP
System.out.println("Length : "+ length);
System.out.println("Width : "+ width);

public static void main (String args[]) {


Rectangle r = new Rectangle();
r. displayData();
r.setData(11.25,33.77);
r. displayData();
}
}
Wrapper Classes
• Wrapper classes provide a way to use primitive data types (int,
boolean, etc..) as objects.

• Wrapper classes for each of the eight simple types.


• Byte, Short, Integer, Long, Float, Double, Character, Boolean

P
• Common static variables in all classes are MIN_VALUE, MAX_VALUE
PP
• Static methods of wrapper classes are used to represent the data in
various format as below.
E.g. toBinaryString ( datatype var)
toBinaryString ( int i )
toOctalString ( double i )
toHexString ( long i )
Wrapper Classes
E.g. To get the value of an Integer Object the intValue() method is used.

• Same way for other objects we may use corresponding methods as


below to get its values.

P
byte byteValue ( )
short shortValue ( )
int
PP
intValue ( )
long longValue ( )
float floatValue ( )
double doubleValue ( )
String toString ( )
Wrapper Classes
Example
class Wrap {
public static void main(String args[]) {
Integer iOb = new Integer(100);

P
//Conversion from wrapper class type to primary data type
int i = iOb.intValue();
PP
System.out.println(" Value of i ::" + i);

//Conversion from primary data type to wrapper class type


iOb = i;
}
}
Output: Value of i :: 100
Autoboxing & Auto-unboxing
Autoboxing is the process by which a primitive type is
automatically encapsulated (boxed) into its equivalent type
wrapper whenever an object of that type is needed.

Auto-unboxing is the process by which the value of a boxed

P
object is automatically extracted (unboxed) from a type
PP
wrapper when its value is needed.

Integer iOb = 100; // autobox an int

int i = iOb; // auto-unbox


StringBuffer Class
• StringBuffer is a peer class of String that provides much
of the functionality of strings.
• The string represents fixed-length, immutable character
sequences while StringBuffer represents growable and
writable character sequences.

P
• Allow to change the character sequence after string
object created.
PP
• Also provides methods to append or insert characters.
Constructor
StringBuffer( ) : Default capacity is 16 chars.
StringBuffer ( int size ) : Capacity to size of chars.
StringBuffer ( String s ): Capacity is size of s plus 16 chars.
StringBuffer Class
Instance Methods

StringBuffer append ( char ch )


StringBuffer append ( String str )

P
int capacity( )
int length ( ) PP
StringBuffer reverse ( )
char charAt ( int i )
StringBuffer insert ( int i, String str )
StringBuilder Class
StringBuilder:
•The StringBuilder in Java represents a mutable sequence of characters.
•Since the String Class in Java creates an immutable sequence of
characters, the StringBuilder class provides an alternate to String Class,
as it creates a mutable sequence of characters.
•Syntax:

P
StringBuilder str = new StringBuilder();
str.append("GFG");
PP
Difference between String,
Stringbuffer and Stringbuilder
• Immutable objects are instances whose state doesn't change after it
has been initialized.
• The String class is an immutable class whereas StringBuffer and
StringBuilder classes are mutable.

P
E.g.
// concatenate two strings with String
PP
String fullName = firstName.concat(" ").concat(lastName);

The concatenation does not modify firstname or lastname string,


rather create a new object which will be referenced by fullName.

//Concate two string with Stringbuffer


sb.append("How r u?");
System.out.println(sb);
Difference Between Stringbuffer and Stringbuilder
StringBuffer StringBuilder

StringBuffer operations are thread- StringBuilder operations are not


safe and synchronized thread-safe & are not-synchronized

P
StringBuffer is to used when StringBuilder is used in a single-
multiple threads are working on threaded environment.
the same String
PP
StringBuffer performance is slower StringBuilder performance is faster
when compared to StringBuilder when compared to StringBuffer

Syntax: Syntax:
StringBuffer var = new StringBuffer(str); StringBuilder var = new StringBuilder(str);
‘this’ Keyword

•It refers to object that is currently executing.


• Access instance variable with
• this.varName

P
•Allows one constructor to explicitly invoke another
PP
constructor in the same class.
• this (args)
Example of ‘this’ keyword

class Point2D {
double x ;

P
double y ;
PP
point2D ( double x , double y ) {
this.x = x ;
this.y = y ;
}
}
Example of ‘this’ keyword

class Point2D {
double x ;
double y ;

P
point2D ( ) {

}
PP
this ( 0 , 0 );

point2D ( double x , double y ) {


this.x = x ;
this.y = y ;
}
}
class Rectangle
{ Example of ‘this’ keyword
private double length = 10;
private double width = 20;

void setData( double l, double w) {


this.length = l;
this.width = w;
}
void displayData () {

P
System.out.println("Length : "+ this.length);
System.out.println("Width : "+ this.width);

}
this.area();

void area() {
PP
System.out.println("Area of rectangle : "+ this.length * this.width);
}
public static void main (String args[]) {
Rectangle r = new Rectangle();
r. displayData();
r.setData(11,2.5);
r. displayData();
}
}
Inheritance
• Inheritance allows a software developer to derive a new
class from an existing one
• The existing class is called the parent class, or superclass, or

P
base class
• The derived class is called the child class or subclass.
PP
• As the name implies, the child inherits characteristics of the
parent
• That is, the child class inherits the methods and data
defined for the parent class
• It provides the reusability.
56
Types of Inheritance
• Simple Inheritance

• Multilevel Inheritance

P
• Hierarchical Inheritance
PP
• Multiple Inheritance

57
Defining a Subclass
• Syntax:
– Class subclass-name extends superclass-name

P
{
PP
Body of the class

58
Simple Inheritance

P
Base / Super / Parent Class
PP
Derived / Sub / Child Class
class A1 {
Example of Inheritance
int i , j;
void show() { System.out.println("Value of i and j is :" + i + "," + j); }
}
class B1 extends A1 {
int k;
void display() { System.out.println("Value of k is :" + k); }

P
void sum() { System.out.println("i+j+k" +" " + "is" + " :" + (i+j+k)); }
}
public class Test {
PP
public static void main(String S[]) {
A1 a = new A1(); B1 b = new B1();
a.i = 10; a.j = 20; a.show();
b.i = 5; b.j = 10; b.k = 15; b.show(); b.sum();
}
}
Example of Inheritance
// Child class can not access the members of base class which are defined as private.
class A {
int i; // public by default
private int j; // private to A
void setij(int x, int y) {
i = x;
j = y;
}

P
}

class B extends A {
int total;
void sum() {
PP
total = i + j; // ERROR, j is not accessible here
}
}
class PrivateInh {
public static void main(String args[]) {
B subOb = new B();
subOb.setij(10, 12);
subOb.sum();
System.out.println("Total is " + subOb.total);
} }
Multilevel Inheritance
• When a subclass is derived form a derived
class than this mechanism is known as
Multilevel Inheritance.
• Multilevel can go up to the any number of

P
levels.
PP Supar Class
Derived Class
Derived of Derived Class
class A { Example of Multilevel Inheritance
int i,j; // var declaration
void show() // method declaration {
System.out.println("Inside Class A....");
System.out.println("Value of i is :" + i);
System.out.println("Value of j is :" + j);
}
}

P
class B extends A{
int k;
void display() {
PP
System.out.println("Inside Class B....");
System.out.println("Value of i is :" + i);
System.out.println("Value of j is :" + j);
System.out.println("Value of k is :" + k);
}
void sum() {
System.out.println("i+j+k" +" " + "is" + " :" + (i+j+k));
}
}
Example of Multilevel Inheritance
class C extends B
{
int l;

void view()
{

P
System.out.println("Inside Class C....");
System.out.println("Value of i is :" + i);

PP
System.out.println("Value of j is :" + j);
System.out.println("Value of k is :" + k);
System.out.println("Value of l is :" + l);
}

void add()
{
System.out.println("i+j+k+l" +" " + "is" + " :" + (i+j+k+l));
}
}
public class Test { Example of Multilevel Inheritance
public static void main(String S[]) {
A a = new A();
B b = new B();
C c = new C();

a.i = 10; a.j = 20;


a.show();

P
b.i = 5; b.j = 10; b.k = 15;
b.display();
b.sum();
PP
c.i = 30; c.j = 40; c.k = 50; c.l = 60;
c.view();
c.add();

}
}
Hierarchical Inheritance

P
PP
Example of Hirarchical Inheritance
class A3
{
int i,j; // var declaration
void show() // method declaration
{
System.out.println("Inside Class A....");
System.out.println("Value of i is :" + i);

P
System.out.println("Value of j is :" + j);
}

}
PP
class B3 extends A3 Example of Hirarchical Inheritance (Cont.)
{
int k;
void display()
{
System.out.println("Inside Class B....");
System.out.println("Value of i is :" + i);

P
System.out.println("Value of j is :" + j);
System.out.println("Value of k is :" + k);
}

void sum()
PP
{
System.out.println("i+j+k" +" " + "is" + " :" + (i+j+k));
}
}
class C3 extends A3 Example of Hirarchical Inheritance (Cont.)
{
int l;

void view()
{
System.out.println("Inside Class C....");

P
System.out.println("Value of i is :" + i);
System.out.println("Value of j is :" + j);

}
PP
System.out.println("Value of l is :" + l);

void add()
{
System.out.println("i+j+l" +" " + "is" + " :" + (i+j+l));
}
}
public class Hierarchical {
public static void main(String S[]) Example of Hirarchical
{ Inheritance (Cont.)
A3 a=new A3();
B3 b=new B3();
C3 c=new C3();

a.i=10; a.j=20;

P
a.show();

b.i=5;
b.display();
PP b.j=10; b.k=15;

b.sum();

c.i=30; c.j=40; c.l=60;


c.view();
c.add();
}
}
Multiple Inheritance
• The mechanism of inheriting the features of more than one
base class into a single class is knows as multiple
inheritance.

• Java does not support multiple Inheritance.

P
PP
• In java multiple inheritance is achieved through the use of
interfaces.

• A class can implement more than one interfaces.


‘super’ Keyword
• super keyword is used to access the members of the
super class.
• Super must always be the first statement executed
inside a subclass constructor.

P
• It used for following two purpose:
– To call super class constructor
PP
– To access a member of the super class that has been
hidden by a member of a subclass
Example of ‘super’ Keyword
class A {
private double l = 10 ;
private double b = 20 ; }

Class B extends A
{

P
double area ()
{ double ans = super.l * super.b; }
}
class Test {
PP
public static void main(String args[]) {
B b1 = new B();
System.out.println(“Area :: " + b1.area();
}
}
Polymorphism
• Allows to define one interface and have
multiple implementation.

P
• Types of polymorphism
PP
1) Method Overloading
2) Method Overriding
Method Overloading
• Two or more methods of same name in a class, provided that
there argument list or parameters are different. This concept
is known as Method Overloading.

• When Java encounters a call to an overloaded method, it

P
simply executes the version of the method whose parameters
match the arguments used in the call.
PP
• The parameters may differ in their type or number, or in both.

• They may have the same or different return types.

• It is also known as compile time polymorphism.


class Overload {
void demo (int a) {
System.out.println ("a: " + a); }

void demo (int a, int b) {


System.out.println ("a and b: " + a + "," + b); }

P
double demo(double a) {
System.out.println("double a: " + a); return a*a; }
} PP
class MethodOverloading {
public static void main (String args []) {
Overload Obj = new Overload();
double result;
Obj.demo(10);
Obj.demo(10, 20);
result = Obj.demo(5.5);
System.out.println("O/P : " + result); } }
Method Overriding
• Child class has the same method as of base class.
In such cases child class overrides the parent
class method. This feature is known as method
overriding.

P
PP
• Applies only to inherited methods
• Object type (NOT reference variable type)
determines which overridden method will be
used at runtime
public class BaseClass {
public void methodToOverride() {
System.out.println ("I'm the method of BaseClass"); }
}

public class DerivedClass extends BaseClass {


public void methodToOverride() {

P
System.out.println ("I'm the method of DerivedClass"); }
}
PP
public class Test {
public static void main (String args []) {
BaseClass obj1 = new BaseClass();
BaseClass obj2 = new DerivedClass();
obj1.methodToOverride();
obj2.methodToOverride(); }
}
Abstract Class
• Abstract class is used to declare functtionality that
is implemented by one or more subclasses.

• It specify what functionality is provided but not

P
how that functionality is provided.
PP
• Abstract class can not be instantiated but you can
declare as an object type.

• The methods in abstract have often empty bodies.


You may define the concrete methods in abstract
class.
abstract class T { Example of Abstract Class
// Method with empty body. Implementation in derived class.
abstract void emptymethod();

// Concrete methods are still allowed in abstract classes


void concretemethod() {
System.out.println("This is a concrete method."); }

P
}
class S extends T {
void emptymethod() {

}
PP
System.out.println(“ Implementation of emptymethod.");

}
class Test {
public static void main(String args[]) {
T b = new S();
b. emptymethod();
b. concretemethod();
} }
Example of Abstract Class
Create an abstract class Shape with constructor
to display the object name. It has two abstract
methods area() and perimeter(). Also one non-
abstract method moveTo (x , y) to move object at
specific co-ordinate. Create a class Rectangle

P
with constructor having three parameters length,
PP
width and name. Also it overrides method area()
and perimeter(). Create another class Circle with
constructor having two parameters radius and
name. Also it overrides method area() and
perimeter().
Final Class
• Final class cannot be extended.

• Methods implemented by this class can not be

P
overridden.
PP
• The compiler gives an error if you attempt to extend a
final class.

• E.g. Math Class and Its Methods.


• Math.pow , Math.abs, Math.max, Math.round etc.
Interface
• It provides the multiple inheritance. (Derived class
may inherit multiple Interfaces.)

P
• It is group of constants and method declaration.
PP
• An interface can be used as type of variable. The
variable can then reference any object that implements
that interface.

• Interface may extend another interface.


Interface Syntax
intfModifier interface intName {
varModifier1 type1 varName1 = value1;
………………
varModifierN typeN varNameN = valueN;

P
mathModifier1 type1 mthName1(params 1);
………………….
PP
mathModifierN typeN mthNameN(params N);
}

• Implicitly var. modifier is public, static and final.

• If method Modifier is not specify than interface is limited to the


code in same package.

• If method Modifier is public than other package may use interface.


Difference Between Abstract Class and Interface
• The abstract keyword is used to declare abstract class.
The interface keyword is used to declare interface.

• Abstract CLASS contains


• General methods

P
• Abstract methods
PP
Interface contains
• Only abstract methods.

• An abstract class can be extended using keyword


"extends".
An interface can be implemented using keyword
"implements".
Difference Between Abstract Class and Interface
• Abstract class doesn't support multiple inheritance.
Interface supports multiple inheritance.

• In abstract by defaults methods are not abstract. It may be


public, private, protected.

P
In Interface all methods are public & abstract & variable are
PP
public static final.

• Abstract class can provide the implementation of


interface.
Interface can't provide the implementation of abstract
class.
Difference Between Abstract Class and Interface
• Class can extend only one abstract class.
A class can implement more than one interface.

• An abstract class can extend another Java class and


implement multiple Java interfaces.

P
An interface can extend another Java interface only.
PP
• Example of abstract class:
public abstract class Shape {
public abstract void perimeter(); }
Example of interface
public interface Shape {
void perimeter(); }
Generics
• Introduce in JDK 5.
• It is possible to create classes, interfaces and methods
that will work in a type-safe manner with various kinds
of data.
E.g. The mechanism that supports a stack is the same

P
whether that stack is storing items of type Integer, Float,
PP
Double, String, Object or Thread.
• With generic you can define an algorithm once,
independently of any specific type of data, and than
apply that algorithm to a wide variety of data type
without any additional effort.
• With generics, all casts are automatic and implicit,
which expands the ability to reuse code and easily.
Java Generic Type
• Usually type parameter names are single, uppercase
letters to make it easily distinguishable from java
variables. The most commonly used type parameter
names are:
• E – Element

P
• K – Key
• N – Number PP
• T – Type
• V – Value
• S,U,V etc. – 2nd, 3rd, 4th types
Generic Method Example
// A Simple Java program to make a program of generic
classes
// We use < > to specify Parameter type
class Gclass <T> {
// An object of type T is declared

P
T obj;
PP
Gclass ( T obj ) {
this.obj = obj; }

public T getObject() {
return this.obj; }
}
Generic Method Example
public class Test {
public static void main (String[] args) {
// instance of Integer type

P
Gclass <Integer> iObj = new Gclass<Integer>(15);
System.out.println( iObj.getObject() );
PP
// instance of String type
Gclass <String> sObj = new Gclass<String>("GeeksForGeeks");
System.out.println( sObj.getObject() );}
}
Generic Method Example
E.g. Print an array of different type using a single
Generic method
public class GenericMethodTest {
// generic method printArray

P
public static < E > void printArray( E[] inputArray ) {
PP
// Display array elements
for(E element : inputArray) {
System.out.printf("%s ", element);
}
System.out.println();
}
Generic Method Example
public static void main(String args[]) {
// Create arrays of Integer, Double and Character
Integer[] intArray = { 1, 2, 3, 4, 5 };
Double[] doubleArray = { 1.1, 2.2, 3.3, 4.4 };
Character[] charArray = { 'H', 'E', 'L', 'L', 'O' };

P
System.out.println("Array integerArray contains:");
PP
printArray(intArray); // pass an Integer array

System.out.println("\nArray doubleArray contains:");


printArray(doubleArray); // pass a Double array

System.out.println("\nArray characterArray contains:");


printArray(charArray); // pass a Character array } }
Enumeration
• It is a list of named constants.
• An enumeration define a class type.

P
• An enumeration can have constructors,
PP
methods and instance variable.
• Methods
– public static enum-type [ ] values ()
– public static enum-type valueOf (String str)
Example of Enumeration
class EnumExample1{
//defining enum within class
public enum Season { WINTER, SPRING, SUMMER, FALL }
//creating the main method
public static void main(String[] args) {

P
//printing all enum
for (Season s : Season.values()){
PP
System.out.println(s); }
System.out.println("Value of WINTER is: "+Season.valueOf("WINTER"));
System.out.println("Index of WINTER is:
"+Season.valueOf("WINTER").ordinal());
System.out.println("Index of SUMMER is:
"+Season.valueOf("SUMMER").ordinal()); } }
Inner class
• Inner class or nested class is a class which is declared
within a class.
• It is used to logically group classes and interfaces in one
place so that it can be more readable and maintainable.
class Test{

P
private int data=30;
PP
class Inner {
void msg(){System.out.println("data is "+data); } }
public static void main(String args[]){
Test obj = new Test();
Test.Inner in = obj.new Inner();
in.msg(); } }
ClassLoader in Java
• The Java ClassLoader is a part of the Java Runtime
Environment that dynamically loads Java classes into
the Java Virtual Machine.
• Java classes aren’t loaded into memory all at once, but
when required by an application.

P
• At this point, the Java ClassLoader is called by the JRE and
these ClassLoaders load classes into memory dynamically.
PP
• Depending on the type of class and the path of class, the
ClassLoader that loads that particular class is decided.
• To know the ClassLoader that loads a class the
getClassLoader() method is used.
• All classes are loaded based on their names and if any of
these classes are not found then it returns a
NoClassDefFoundError or ClassNotFoundException.
Class Path in Java
• We don't need to set PATH and CLASSPATH to compile and
run java program while using IDE like Netbeans.
• These environment variables are required
to compile and run java program using CMD (Command
prompt)

P
• System will understand java command with the help of
PATH variable and find class using CLASSPATH variable to
run it. PP
Set Path Variable
To compile & run java program in any directory the path of java bin
directory set into the path environment variable as below.

P
Windows
Select Start, select Control Panel. double click System
PP
Select the Advanced tab.
Click Environment Variables.
In the section System Variables, find the PATH environment variable &
Select it. Click Edit.
At the end of line add path of Bin Directory.

You might also like