0% found this document useful (0 votes)
4 views56 pages

Java Part2

The document outlines the syllabus and concepts of Object Oriented Programming (OOP) in Java, covering topics such as classes, objects, static and non-static members, constructors, inheritance, and polymorphism. It explains the definitions and functionalities of classes and objects, including how to access static and non-static members, and the importance of member and local variables. Additionally, it discusses default values for variables, memory allocation, and the use of the 'this' keyword to differentiate between member and local variables.

Uploaded by

vigguviggu33
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views56 pages

Java Part2

The document outlines the syllabus and concepts of Object Oriented Programming (OOP) in Java, covering topics such as classes, objects, static and non-static members, constructors, inheritance, and polymorphism. It explains the definitions and functionalities of classes and objects, including how to access static and non-static members, and the importance of member and local variables. Additionally, it discusses default values for variables, memory allocation, and the use of the 'this' keyword to differentiate between member and local variables.

Uploaded by

vigguviggu33
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Part-2

Syllabus

⚫ Objects
⚫ Static and non static members
⚫ Reference variable,local variable and member/class variable
⚫ Constructor
⚫ Constructor Overloading and Method Overloading
⚫ Class diagram & RelationShip
⚫ Inheritance and types
⚫ Method Overriding
⚫ Derived Casting
⚫ Polymorphism
⚫ Abstraction
⚫ Encapsulation
⚫ Singleton class

Object Oriented Programming

Object
- Anything which is present in the real world and physically existing can be termed as an Object.
Ex: Car,laptop,Tv etc…….

- The Properties of every object is categorized into 2 types:


 States
 Behaviours

- States are the properties used to store some data.


- Behaviour are the properties to perform some task.

Note:
✓ Every object will have its own properties & behaviours.
✓ Since the states & behaviours belongs to one particular object , If I need to store all these things we
need one dedicated memory location(Container). But we don’t have any predefined datatype which
helps to create such container. Hence we can design our own datatype with the help of a class,
Which can be used as non-primitive datatype.

class:
- class is a blue print of an object.
- It’s a platform to store states and behaviors of an object.
- class has to be declared using class keyword.
- class can also act as datatype.
-It is used to design a user defined non-primitive datatype to store the details of object.
-We need class for execution of program.
-In a class we can create members like methods( to store behaviors of an object) as well as variable(to
store the states of object).
-Every class-name can be a Non-primitive datatype.
-The java language also comes up with lot of built-in classes i.e, String, System, Scanner etc……

Ex: class Employee


{
// design variables to store states.
// design methods to store behaviors.
}

Note:
*The non-primitive datatype will have default values i.e null.

Members of Class:

Anything which is declared within class block is known as members of the class.
Ex: Methods, Variables, Constructors etc….

A class will have 2 types of members


 Data members
 Function members

*Data members are those variables which are declared within the body of the class.
*Function members are those methods/functions which are declared within the body of the class.

The members of the class can be classified into 2 Types..


1.) Static Members of class.
2.) Non-Static Members of class.

Static Members of class:


Any members of the class which is prefixed with static modifier is known as static member of class.
In java we have Following static members.
i) Static Method
ii) Static Variable

i) Static Methods:
-A method which is prefixed with static modifier is known as static methods.
-A block which belongs to a static member is known as Static Context.

ii) Static Variable:


-A variable which is prefixed with static modifier / keyword is known as Static Variable.
-It should be declared inside class block.

How to use a static members of one class inside static context of same class ?
Static member present in same class can be accessed just by using memberName.

How to use a static members of one class inside static context of another class ?
Static member present in different class can be accessed by using class name with member name.
Ex : [Link]

Access Operator(.) :
*) It is a Binary Operator.
*) It is used to access a member present in another class.
Note:
The Class Loader loads all the static properties inside a memory location called as Class Area or Static
Pool.
Static properties are loaded only once, therefore they will have a single copy.

1a.
package com;
/* Accessing static properties within the same class */
public class Student
{
static int age = 20;
public static void study()
{
[Link]("Student is Studying");
}
public static void main(String[] args)
{
[Link]();
[Link]("------------");
[Link](age);
}
}

o/p:
Student is Studying
------------
20

2a.
package com;
class Employee {
public static int id = 101;
public static void work() {
[Link]("Employee is Working");
}
}

2b.
package com;
/* Accessing static properties in another class */
public class Test {
public static void main(String[] args) {
[Link]([Link]);
[Link]();
}
}

o/p:
101
Employee is Working

[Link]-Static Members of class:


-Any member declared inside class block without prefixing static modifier is known as Non-static
member of a class.
-In java we have following Non-static members
i) Non-static Variable.
ii) Non-static Method.
iii) Constructor.

Note:
-The non-static members gets their memory allocated inside object.
-If we need to access any non-static members…. The first thing we must do is create an object.

What is Object?
-An object is a block of memory created during in runtime inside heap area.
-The object also known as Instance Of A Class.
-The process of creating an object is known as INSTANCIATION.

Syntax to create an object: new ClassName();

new:
-new is a keyword.
-It is a unary operator.
-It is used to create an object along with constructor of the class.
-new will create a block of memory inside heap area and it will return the address of it.
-The type of address generated for the object will always be specific to its class.

How to use a non-static members inside static context of same/different class ?


Non-Static member present in a class can be accessed within a static method only by creating the object
of the class.

1.
/*
Accessing Non-Static Variables inside same class
*/

class Student
{
// NON-STATIC VARIABLES
int age = 20;
String name = "Dinga";
public static void main(String[] args)
{
[Link]("start");
[Link](new Student().age);
[Link](new Student().name);
[Link]("------------------------ -");
[Link]("Age: "+new Student().age);
[Link]("Name: "+new Student().name);
[Link]("------------------------ -");
[Link](new Student().name+" is "+new Student().age+" years old");
[Link]("*****");
[Link]("end");
}
}

o/p
start
*****
20
Dinga
-------------------------
Age: 20
Name: Dinga
-------------------------
Dinga is 20 years old
*****
end

2a.
class Employee
{
int id = 101;
String name = "Tom";
double salary = 123.45;
}

2b.
/*
Accessing Non-Static Variables in another class
*/
class Test
{
public static void main(String[] args)
{
[Link](new Employee().id);
[Link](new Employee().name);
[Link](new Employee().salary);
}
}

o/p:
101
Tom
123.45

When to declare member as static?


-Static members will have only one copy in the memory.
-If the value of a data member in a class is not changing from object other object then those data
members should be declared as static.
-If a function member / method in a class is using only static members of the class then those function
member / method should be declared as static.
When to declare member as non-static?
-Non-Static members will have multiple copy in the memory.
-If the value of a data member in a class is changing from object other object then those data members
should be declared as non-static.
-If a function member / method in a class is using at least one non-static members of the class then those
function member / method should be declared as non-static.

//Draw memory allocation for both Account and MainAccount class


public class Account {

String name="Allen";
long accno=98765432102L;
double balance=0.0;
String ifsc="SBI0067";
String branch="mgraod";
static String bankName="SBI";

public void showDetails(){


[Link](name);
[Link](accno);
[Link](ifsc);
[Link](branch);
}
public static void showBankName(){
[Link](bankName);
}
public void deposit(double amount){
balance=balance+amount;
[Link]("Balance is "+balance);
}
}

public class MainAccount {


public static void main(String[] args) {
[Link]();
new Account().showDetails();
new Account().deposit(500);
new Account().deposit(1000);

}
}

Reference Variable

◼ It is a type of variable which is used to store address of an object.


◼ Within a reference variables we can’t store primitive values.
◼ Within a primitive variables we can’t store store address of an object.
◼ Within one reference variables we can store ONLY ONE OBJECT ADDRESS.
◼ Multiple reference variables can point to same object.
Syntax: ClassName ref-variable;

1.
/*
Accessing Non-Static Variables inside same class
*/

class Student
{
// NON-STATIC VARIABLES
int age = 20;
String name = "Dinga";
public static void main(String[] args)
{
[Link]("start");
[Link]("*****");
Student s = new Student();
// OBJECT CREATION
[Link]([Link]);
[Link]([Link]);
[Link]("------------------------ -");
[Link]("Age: "+[Link]);
[Link]("Name: "+[Link]);
[Link]("------------------------ -");
[Link]([Link]+" is "+[Link]+" years old");
[Link]("*****");
[Link]("end");
}
}

o/p
start
*****
20
Dinga
-------------------------
Age: 20
Name: Dinga
-------------------------
Dinga is 20 years old
*****
end

2a.
class Employee
{
int id = 101;
String name = "Tom";
double salary = 123.45;
}

2b.
/*
Accessing Non-Static Variables in another class
*/
class Test
{
public static void main(String[] args)
{
Employee emp = new Employee();
[Link]([Link]);
[Link]([Link]);
[Link]([Link]);
}
}
o/p:
101Tom
123.45

public class Account {

String name="Allen";
long accno=98765432102L;
double balance=0.0;
String ifsc="SBI0067";
String branch="mgraod";
static String bankName="SBI";

public void showDetails(){


[Link](name);
[Link](accno);
[Link](ifsc);
[Link](branch);
}

public static void showBankName(){


[Link](bankName);
}

public void deposit(double amount){


balance=balance+amount;
[Link]("Balance is "+balance);
}

public void withdraw(double amount){


balance=balance-amount;
[Link]("Balance is "+balance);
}
}

public class MainAccount {


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

Account a=new Account();

[Link](a);
[Link]();
[Link](500);
[Link](200);
Account a2=new Account();
[Link](1000);
[Link](100);

Account a3=new Account();

//create 5 account object and perform deposit and withdraw operation

}
}

Default Value
- If a variable is declared and not initialized to any value, then the compiler will automatically initialize
to its default value.
- Default values are applicable only for Member Variables (Static and Non-Static Variables).

Default values are as follows


byte, short, int, long ----> 0
float, double ----> 0.0
char ----> '/u0000' (Unicode value) Java does not understand empty white space( )
boolean ----> false
String ----> null

1.
package com;
class DefaultValuesDemo {
int a;
double b;
char c;
boolean d;
String e;
public static void main(String[] args) {
DefaultValuesDemo dvd = new DefaultValuesDemo();
[Link](dvd.a);
[Link](dvd.b);
[Link](dvd.c);
[Link](dvd.d);
[Link](dvd.e);
}
}
o/p:
0
0.0

2.
package com;
class Car {
int cost = 10;
public static void main(String[] args) {
Car c1 = new Car();
Car c2 = new Car();
[Link]([Link]+" "+[Link]);
[Link] = 15;
[Link] = 23;
[Link]([Link]+" "+[Link]);
}
}
o/p:
10 10
15 23

3.
package com;
class Student {
String name;
int marks;
public static void main(String[] args) {
Student s1 = new Student();
Student s2 = new Student();
[Link]([Link]+" "+[Link]);
[Link]([Link]+" "+[Link]);
[Link]("------------------- ");
[Link] = "Tom";
[Link] = 36;
[Link] = "Jerry";
[Link] = 40;
[Link]([Link]+" "+[Link]);
[Link]([Link]+" "+[Link]);
[Link]("------------------- ");
[Link]([Link]+" has scored "+[Link]+" marks in Java");
[Link]([Link]+" has scored "+[Link]+" marks in Java");
}
}
o/p:
null 0
null 0
-------------------
Tom 36
Jerry 40
-------------------
Tom has scored 36 marks in Java
Jerry has scored 40 marks in Java

Member Variable and Local variable


1. Member variables are those variables which are declared in the class limit/Scope.
2. They can be accessed globally ie. throughout the class.
3. Member variables are categorized into
a. static
b. Non-static
4. Local Variables are those variables which are declared within a specific scope or limit such as
method, constructor, etc.
5. Local variables are accessible within that specific scope.
6. Default Values are applicable only for Member Variables.
this keyword
1. In java, we can have both member and local variable names same, then always the local variables will
dominate the member variables.
2. In order to avoid the dominating part we make use of "this" keyword.
3. this is keyword which is used to point to the current object/instance.
[Link] is a non-static variable which can be used only inside non-static context.

How to differentiate member and local variable having same name under different situations.

➢ If both member variable and local variable have same name then ,if we want to execute member
variable from same method ,priority is always given for local variable.

public class TypesOfVariable {


//member/class variable
static int a;

public static void test(){


//local variable
int b=20;

[Link](a);
[Link](b);
}

public static void main(String[] args) {


[Link](a);//0
// [Link](b);

test();
}
}
--------------------------------------------------------
public class GlobalVariable //Member
{

static int a;
double b;

public static void test(){


[Link](a);
GlobalVariable g1=new GlobalVariable();
[Link](g1.b);

}
public static void main(String[] args) {
[Link](a);

GlobalVariable g=new GlobalVariable();


[Link](g.b);
}
}
-------------------------------------------------
public class LocalVariable {
public static void run(){
int a=20;
[Link](a);
}

public static void main(String[] args) {


run();
}
}

➢ Member static variable and local variable can be differentiated from static method by using
[Link].

public class Demo3 {

static int a=20;


public static void run(){
int a=30;//high priority
[Link](a);//30

//how to differentiate static mem vari & local var with same name?
//Classname
[Link](Demo3.a);//20
}
public static void main(String[] args) {
// [Link](a);//20
run();
}
}

➢ Member non static variable and local variable can be differentiated from static method by creating
object of the class.

public class Demo4 {

int b=10;
public static void m2(){
int b=30;
[Link](b);//30
[Link](new Demo4().b);//10
}
public static void main(String[] args) {
m2();
}
}

➢ Member static variable and local variable can be differentiated from a non static method by using
[Link] or object creation or this keyword.

public class Demo3 {

static int a=20;


public void play(){
int a=10;
[Link](a);//10

[Link](Demo3.a);//20
[Link](new Demo3().a);//20
[Link](this.a);//20
}
public static void main(String[] args) {
// [Link](a);//20
Demo3 d=new Demo3();
[Link]();
}
}

➢ Member non static variable and local variable can be differentiated from non static method by using
this keyword or object creation.

public class Demo4 {

int b=10;

public void m1(){


int b=20;
[Link](b);//20

[Link](new Demo4().b);//10
//this keyword---point to current object
//it has to be used only inside non static context
[Link](this.b);//10
}
public static void main(String[] args) {
Demo4 d=new Demo4();
d.m1();
}

---------------------------------------------------------------
public class Test {

static int age=23;//mem/global variable

public static void m1(){


int age=30;//local variable highest priority
[Link](age);//30
//differentiate static global and local variable having same name
//using [Link]
[Link]([Link]);//23
}

public static void main(String[] args) {


m1();
// [Link](age);//23
}

}
-------------------------------------------------------------

public class Test1 {

double marks=45.6;

public void m2(){


double marks=50.3;
[Link](marks);//50.3

/*diffrentiate non static global and local variable having same name */
[Link](new Test1().marks);//45.6

//this keyword--point to current object


/*rule
has to used only within non static block */
[Link]([Link]);
}
public static void main(String[] args) {
new Test1().m2();
}

}
------------------------------------------------------------
public class Test2 {
static int a=20;
public void m3(){
int a=30;
[Link](a);
[Link](Test2.a);
//not good pratice
[Link](new Test2().a);
[Link](this.a);
}

public static void main(String[] args) {


Test2 t=new Test2();
t.m3();
}

public class MainTest {


public static void main(String[] args) {
[Link](Test2.a);

Test2 t=new Test2();


[Link](t.a);//not good pratice
}
}
Constructor

[Link] are special type of methods which have same name as the class name.
2. Constructor Name and Class Name should always be same.
3. Constructors will not have return type.
4. Constructors will get executed at the time of object creation.
[Link] class must and should have Constructor.
[Link] the programmer do not write any constructor, then compiler will write default constructor implicitly.
[Link] cannot be declared as static or final.
[Link] you specify return type for the constructor, then it will be considered as a normal method.
[Link] the programmer writes any constructor explicitly, then complier will not write any constructor
implicitly.
10. Constructors are categorized into 2 types:
a. Default Constructor
b. Custom/User-Defined Constructor

syntax: AccessSpecifier ClassName(optional arguments)


{
// Set of Instructions
}

Note:
Constructor is a special non-static members which is used to load all the non-static members of a class
into the object.

Default Constructor
1. If a constructor is not explicitly present in a class, then the compiler will automatically generate a
constructor and those constructors are called as Default Constructor.
2. Default constructor neither accepts any arguments nor has any implementation.

Custom/User-Defined Constructor
1. If a constructor is explicitly defined inside a class by the user or the programmer, then we refer it as
custom/user-defined constructor.
2. They are further categorized into 2 types:
i. Non-Parameterized Custom Constructor
ii. Parameterized Custom Constructor

NOTE: WHEN THERE IS DEFAULT CONSTRUCTOR, THEN CUSTOM CONSTRUCTOR


CANNOT BE PRESENT AND VICE VERSA.

Application of Constructor.
Constructors are used to Intialize the data members of the class.

public class Employee2 {


int id;//102
String name;//Priya
double salary;//6.0
static String comapanyName="Abc";
public Employee2(int id,String name,double salary)//a=102,b="Priya",c=6.0
{
// [Link](a);
// [Link](b);
// [Link](c);
[Link]=id;
[Link]=name;
[Link]=salary;
}

public void showDetails(){


[Link](id);
[Link](name);
[Link](salary);
}

public static void showCompanyName(){


[Link](comapanyName);
}

public void updateSalary(double newSalary){


salary=newSalary;
[Link]("new salary is "+salary);
}
public static void main(String[] args) {
showCompanyName();
Employee2 e1=new Employee2(101, "Ben", 6.2);
[Link]();
[Link]("------------------------");
Employee2 e2=new Employee2(102, "Priya", 6.0);
[Link]();
[Link](6.5);
}

Packages:
A java package is group of classes and interfaces which are related to one single module in the given
project.

Package naming convention


package name is always written in all-lowercase.
package names are always written in reverse order of domain
convention : [Link]
Ex: [Link]

Access Specifier

Access specifiers are used to provide security for the classes and its members by controlling the
visibility.
public :
if you declare any entity as public, then it can be accessed by the classes present in same or different
package.
public entities will have highest visibility and lowest security.

protected :
If you declare any entity as protected, then it can be accessed by the classes present in same package.
protected entity can be accessed by other class present in different package through inheritance and
creating the object of SUBCLASS ONLY.

pkg-level(default) :
if you declare any entity without using any access specifier keyword then it is considered as pkg-level
member(default member).
if you declare any entity as pkg-level(default), then it can be STRCITLY accessed ONLY by the classes
present in SAME package.

private :
if you declare any entity as private, then it can be accesses ONLY by the class within which they are
declared.
private entities will have highest security and lowest visibility.

package [Link];
public class Sample {
//same class access
public static int a=10;
public static void m1() {
[Link]("public m1 method");
}

protected static int b=20;


protected static void m2() {
[Link]("protected m2 method");
}

static int c=30;


static void m3() {
[Link]("default m3 method");
}

private static int d=40;


private static void m4() {
[Link]("private m4 method");
}

public static void main(String [] args) {


//public members
[Link](a);
m1();

//protected members
[Link](b);
m2();

//default members
[Link](c);
m3();

//private members
[Link](d);
m4();

}
}

package [Link];

public class Test {


//different class access
public static void main(String[] args) {

//public members
[Link](Sample.a);
Sample.m1();

//protected members
[Link](Sample.b);
Sample.m2();

//default members
[Link](Sample.c);
Sample.m3();

//private members---cannot access


[Link](Sample.d);
Sample.m4();
}
}

package [Link];
import [Link];
public class Run {
//different package access
public static void main(String[] args) {
//public members
[Link](Sample.a);
Sample.m1();

//protected members-------can be accessed only with inheritance


[Link](Sample.b);
Sample.m2();

//default members---cannot access


[Link](Sample.c);
Sample.m3();

Constructor Overloading

The Process of having multiple constructors in the same class but difference in arguments.

In order to achieve Constructor Overloading we have to either follow 1 of the following rules.
a. There should be a change in the (length)No of Arguments.
b. There should be a change in the Datatype of the Arguments.
c. There should be a change in the Sequence/Order of Datatype.

package [Link];
public class Demo {

public Demo() {
[Link]("zero arg");
}
public Demo(int a) {
[Link]("int arg");
}

public Demo(String a) {
[Link]("String arg");
}

public Demo(int a,double b) {


[Link]("int double arg");
}

public Demo(double a,int b) {


[Link]("double int arg");
}

public static void main(String[] args) {


Demo d=new Demo();
Demo d1=new Demo(5);
Demo d2=new Demo("Hello");
Demo d3=new Demo(2,4.5);
Demo d4=new Demo(4.5,6);
}
}

package [Link];
public class Student {
int id;
String name;
String email;

public Student(int id,String name) {


[Link]=id;
[Link]=name;
}

public Student(int id,String name,String email) {


[Link]=id;
[Link]=name;
[Link]=email;
}

public void printDetails() {


[Link](id);
[Link](name);
[Link](email);
}
public static void main(String[] args) {
Student s1=new Student(1, "allen", "a@[Link]");
[Link]();
[Link]("------------------------------");
Student s2=new Student(2,"ford");
[Link]();
}
}

Method Overloading
In a class having multiple methods with the same name,but difference in arguments is called as Method
Overloading.

In order to achieve method overloading we need to satisfy either 1 of the following 3 rules.
1. There should be a change in the No of Arguments.
2. There should be a change in the Datatype of the Arguments.
3. There should be a change in the order/sequence of the Datatypes.

Note:
1. Both Static and Non-Static methods can be Overloaded.
2. returntype might be same or different.

Advantage:
It is easy to remember One method which may perform similar operation with different arguments.

package [Link];
public class Calculate {
public static void add(int a,int b)
{
[Link]("1--"+(a+b));
}

public static void add(int a,double b)


{
[Link]("2--"+(a+b));
}
public static void add(double a,double b)
{
[Link]("3--"+(a+b));
}

public static void add(int a,int b,int c)


{
[Link]("4--"+(a+b+c));
}

public static void main(String[] args) {


add(3,4);
add(4,6.7);
add(5.6,7.8);
add(2,3,4);
}

}
Class diagram

A Class diagram is pictorial representation of class.


Class diagrams helps understanding the relations between classes in much better way.

Relationship:

* One object is having some association/connection between another object is known as relationship.
* Relationship has been classified into 2 types
1. is-a relationship
2. has-a relationship

is-relationship:
the relationship between 2 objects similar to parent and child is known as is-a relationship
* how to achieve is-a relationship
in java is-a relationship is achieved using inheritance.

INHERITANCE

1. Inheritance is a process of one class acquiring the properties of another class.


2. A class which gives or shares the properties are called as Super , Base or Parent Class.
3. A class which acquires or accepts the properties are called as Sub , Derived or Child Class.
4. In java, we achieve inheritance with the help of 'extends' keyword.
5. Inheritance is also referred as "IS-A" Relationship.
[Link] superclass object we can access ONLY properties of superclass
[Link] subclass object we can access properties of both subclass and superclass.
8. In java, Only Variables and methods are inherited where constructors are not INHERITED.
[Link] data members and function members of the class CANNOT be inherited
[Link] subclass object we can access both static and non-static properties of both subclass
and superclass

Types of Inheritance
1. Single Level Inheritance
2. Multi-Level Inheritance
3. Hierarchical Inheritance
4. Multiple Inheritance
5. Hybrid Inheritance

Single Level Inheritance


one Sub class inheriting from one Single Super class is called as Single level Inheritance.
1a
package [Link];
//super class
public class Sample {

int a=10;

public void count() {


[Link]("Sample class count method");
}

static int c=30;


public static void test() {
[Link]("static method of sample class");
}

1b
package [Link];
//sub class
public class Demo extends Sample
{
double b=3.6;
public void display() {
[Link]("Demo class display method");
}
}

1c
package [Link];
public class MainClass {
public static void main(String[] args) {
//create object of super class

Sample s=new Sample();


//super properties
[Link](s.a);
[Link]();

//child properties cannot be accesed


// [Link](s.b);
// [Link]();
[Link]("--------------------------------");
//create object of subclass
Demo d=new Demo();

//super
[Link](d.a);
[Link]();

//subclass
[Link](d.b);
[Link]();

[Link]("============================");

[Link](Sample.c);
[Link]();
[Link]("-----------------");
[Link](Demo.c);
[Link]();
}
}

2a.
package singlelevel;
public class Father
{
int age = 40;
}

2b.
package singlelevel;
public class Son extends Father
{
String name = "Tom";
}

2c.
package singlelevel;
public class Test {
public static void main(String[] args) {
Son s = new Son();
[Link]([Link]);
[Link]([Link]);
}
}
o/p:
40
Tom

Multi-Level Inheritance

Subclass inheriting the properties of superclass and that superclass inheriting the properties from
another superclass is called as Multilevel inheritance.

1a
package [Link];
public class WhatsAppV1 {

public void sendMsg() {


[Link]("message");
}

1b
package [Link];
public class WhatsAppV3 extends WhatsAppV2{

public void sendVideoCall() {


[Link]("video call");
}
}
1c
package [Link];
public class WhatsAppV2 extends WhatsAppV1{

public void sendVoiceMsg() {


[Link]("voice message");
}
}

1d
package [Link];
public class MainClass {
public static void main(String[] args) {

WhatsAppV1 v1=new WhatsAppV1();


[Link]();

WhatsAppV2 v2=new WhatsAppV2();


[Link]();
[Link]();

WhatsAppV3 v3=new WhatsAppV3();


[Link]();
[Link]();
[Link]();
}
}

2a.
package multilevel;
public class University {
String universityName = "VTU";
void conductExams() {
[Link]("VTU is conducting Exams");
}
}
2b.
package multilevel;
public class College extends University {
String collegeName = "Jspiders";
void providePlacements() {
[Link]("Jspiders Provides Placement");
}
}
2c.
package multilevel;
public class Department extends College {
String departmentName = "Computer Science";
void fest() {
[Link]("CS Department had a Fest called as Equinox");
}
}
2d.
package multilevel;
public class Student {
public static void main(String[] args) {
Department d = new Department();
[Link]("University Name: "+[Link]);
[Link]("College Name: "+[Link]);
[Link]("Department Name: "+[Link]);
[Link]("-----------------");
[Link]();
[Link]();
[Link]();
}
}
o/p:
University Name: VTU
College Name: Jspiders
Department Name: Computer Science
-----------------
VTU is conducting Exams
CS Department had a Fest called as Equinox
Jspiders Provides Placement

Generalization
Declaring common methods and variables of all subclasses in one common superclass.

Specialization
Declaring methods and variables specifically for one subclass.

Multiple inheritance
Subclass inheriting the properties from 2 or more superclass is called as Multiple inheritance.
Java don't support Multiple inheritance.
Multiple inhertiance can be achieved with the concept called as interface.

package [Link];

class Account{
//Generalization
String name;
long accno;
double balance;
public void deposit(double amount) {
balance+=amount;
[Link]("Balance after Deposition:"+balance);
}
public void withdaw(double amount) {
balance-=amount;
[Link]("Balance after withdraw:"+balance);
}
public void checkBalance() {
[Link]("Current Balance is:"+balance);
}
}
class Saving extends Account{
//rate of interest--Specialization
double roi=0.005;
public void calculateRoi() {
balance=balance+(balance*roi);
[Link]("Balance after roi:"+balance);
}
}
class Current extends Account{
//minimum balance
double minBalance=5000.0;
public void showMinimumBalance() {
[Link]("Min Balance is:"+minBalance);
}
}
public class HierarchialExample {
public static void main(String[] args) {
Saving s1=new Saving();
[Link]="tom";
[Link]=9874563211254L;
[Link](2000.0);
[Link](300.0);
[Link]();
[Link]();

// [Link]();//cannot access
}

}
Hybrid Inheritance
It is the combination of Different types inheritance.

CONSTRUCTOR CHAINING
1. The Process of one constructor calling another constructor is called as constructor chaining.
2. Constructor Chaining can be achieved only in case of constructor overloading.
3. Constructor Chaining in same class can be achieved using this calling statement ie. this().

Note:
1. this() should always be the first executable line within the constructor.
2. Recursive Chaining is not possible, Therefore if there are 'n' constructors we can have a maximum of
'n-1' calling statements.

package [Link];
public class Demo {

public Demo() {
this(7);
[Link]("zero arg");
}
public Demo(int a) {
this("hello");
[Link]("int arg");
}

public Demo(String a) {
this(2,4.3);
[Link]("String arg");
}

public Demo(int a,double b) {


this(3.4,5);
[Link]("int double arg");
}

public Demo(double a,int b) {


[Link]("double int arg");
}

public static void main(String[] args) {


Demo d=new Demo();

}
}

package [Link];
public class Student {
int id;
String name;
String email;

public Student(int id,String name) {


[Link]=id;
[Link]=name;
}

public Student(int id,String name,String email) {


this(id,name);
[Link]=email;
}

public void printDetails() {


[Link](id);
[Link](name);
[Link](email);
}
public static void main(String[] args) {
Student s1=new Student(1, "allen", "a@[Link]");
[Link]();
[Link]("------------------------------");
Student s2=new Student(2,"ford");
[Link]();
}
}
Global Constructor chaining:
It is the process of sub class constructor calling super class constructor is known as global constructor
chaining.
Constructor chaining can be achieved by super(): super call statement
• super(); can be written explicitly by the programmer or implicitly by the compiler at the compile
time.
• If the superclass contains only parameterized constructors then the programmer should write
super(); explicitly and pass the required arguments.
• super(); must be written ONLY within the constructor body.
• super(); should be always written at the first line of constructor body.
• Multiple super(); within the same constructor body is NOT allowed.

super() can be used in 2 ways:


i. implicitly
When we create an object of a class, and if that class has a super class, and if that super class has a
nonparameterized constructor, then the sub class constructor will invoke the super class constructor
implicitly.

1a.
package com;
class Father
{
Father()
{
[Link](1);
}
}

1b.
package com;
class Son extends Father
{
Son()
{
// implicitly super();
[Link](2);
}
}

1c.
package com;
public class Test {
public static void main(String[] args) {
Son s = new Son();
}
}

o/p:
1
2
ii. explicitly
When we create an object of a class, and if that class has a super class, and if that super class has a
parameterized constructor, then the sub class constructor should invoke the super class constructor
explicitly, otherwise we get compile time error.

1a.
package com;
class Father
{
Father(int a)
{
[Link](1);
}
}

1b.
package com;
class Son extends Father
{
Son()
{
super(10);
[Link](2);
}
}

1c.
package com;
public class Test {
public static void main(String[] args) {
Son s = new Son();
}
}

o/p:
1
2

2a.
package com;
class Vehicle
{
Vehicle(String brand)
{
[Link]("brand: "+brand);
}
}

2b.
package com;
class Bike extends Vehicle
{
Bike(int cost)
{
super("BMW");
[Link]("cost: "+cost);
}
}

2c.
package com;
public class Solution {
public static void main(String[] args) {
Bike b = new Bike(200);
}
}
o/p:
brand: BMW
cost: 200

Method Overriding
1. The process of Inheriting the method and changing the implementation/Definition of the inherited
method is called as method overriding.
2. In order to achieve method overriding, we have to follow the below rules:
i. Method Name must be same.
ii. Arguments should be same
iii. returntype should also be same.

Note:
1. Access Specifier should be same or of Higher Visibility.
2. While Overriding a method we can optionally use annotation ie. @Override
3. annotation was introduced from JDK 1.5 .

⚫ Inheritance is mandatory for method Overriding.


⚫ @ -> annotation
⚫ @Override (Override annotation) it compares the given method declaration of subclass with every
other method declaration present in superclass and throws an error if there is no matching
declaration found.
⚫ Final, Private and Static methods cannot be Overridden.

1a.
package com;
class Father
{
void bike()
{
[Link]("Old Fashioned Father's Bike!");
}
}

1b.
package com;
class Son extends Father
{
@Override
void bike()
{
[Link]("New Modified Son's Bike");
}
public static void main(String[] args)
{
Son s = new Son();
[Link]();
}
}
o/p:
New Modified Son's Bike

2a.
package com;
public class Vehicle {
void start() {
[Link]("Vehicle Started");
}
}

2b.
package com;
public class Car extends Vehicle {
@Override
void start()
{
[Link]("Car Started");
}
}

2c.
package com;
public class Test {
public static void main(String[] args) {
Car c = new Car();
[Link]();
}
}

o/p:
Car Started

3a.
package com;
public class WhatsApp1 {
void display() {
[Link]("Single Ticks Supported");
}
}

3b.
package com;
public class WhatsApp2 extends WhatsApp1 {
@Override
void display() {
[Link]("Double Ticks Supported");
}
void call() {
[Link]("Voice Call Supported");
}
}

3c.
package com;
public class WhatsApp3 extends WhatsApp2 {
@Override
void display() {
[Link]("Blue Ticks Supported");
}
@Override
void call() {
[Link]("Video Call Supported");
}
void story() {
[Link]("Can Upload Images as Story");
}
}

3d.
package com;
public class User {
public static void main(String[] args) {
WhatsApp3 w3 = new WhatsApp3();
[Link]();
[Link]("-----------------");
[Link]();
[Link]("-----------------");
[Link]();
}
}

final keyword
- final keyword can be used with a variable, method, and class.
- final variable acts as a constant, whose value cannot be re-initialized.
- final methods can be inherited but cannot be Overridden.
- final class cannot be Inherited.

4.
package com;
public class Demo {
public static void main(String[] args) {
final double PI = 3.14;
// PI = 3.4;
int a = 10;
a = 20;
a = 30;
}
}

5a.
package com;
class Father
{
final void bike()
{
[Link]("Old Fashioned Father's Bike!");
}
}
5b.
package com;
class Son extends Father
{
/*
@Override
void bike()
{
[Link]("New Modified Son's Bike");
}
*/
public static void main(String[] args)
{
Son s = new Son();
[Link]();
}
}

6a.
package com;
final class Father
{
}
6b.
package com;
class Son extends Father
{

TYPE CASTING

Non-Primitive Casting or Derived Casting:


1. Non-Primitive Casting or Derived Casting or Class Type Casting can be divided into 2 types:
i. Up-Casting
ii. Down-Casting

Up-casting
1. Creating an object of sub class, and storing it's address into a reference of type Superclass.
2. With Upcasted Reference we can access only superclass Members/Properties.
3. In order to achieve upcasting, IS-A Relationship mandatory.
4. Upcasting will have implicitly/Automatically.
5. Superclass reference, subclass object.

Down-Casting
1. The process of converting the upcasted reference back to Subclass type reference is called as Down-
casting.
2. With the Subclass/Down-casted reference we can access both superclass and subclass members
properties.
3. In order to achieve down-casting, upcasting is mandatory.
4. Down-casting has to be done explicitly.

syntax: (SubClassName) SuperClassReference;

1a.
package nonprimitive;
public class Father
{
int age = 45;
}

1b.
package nonprimitive;
public class Son extends Father
{
String name = "Dinga";
}

1c.
package nonprimitive;
public class Test {
public static void main(String[] args) {
/* UPCASTING */
Father f = new Son();
[Link]([Link]); //[Link] will give error

/* DOWNCASTING */
Son s = (Son) f;
[Link]([Link]+" "+[Link]);
/*Son s = new Son();
Father f = s;*/
}
}

o/p:
45
45 Dinga

2a.
package nonprimitive;
public class Vehicle {
String brand = "BMW";
void start() {
[Link]("Vehicle Started");
}
}

2b.
package nonprimitive;
public class Car extends Vehicle {
String fuel = "Petrol";
void stop() {
[Link]("Car Stopped");
}
}

2c.
package nonprimitive;
public class Demo {
public static void main(String[] args) {
Vehicle v = new Car();
[Link]([Link]);
[Link]();
[Link]("-------------");
Car c = (Car) v;
[Link]([Link]+" "+[Link]);
[Link]();
[Link]();
}
}

o/p:
BMW
Vehicle Started
-------------
BMW Petrol
Vehicle Started
Car Stopped

Important points
⚫ If a method is having Primitive data type argument then for the same method we can pass values
which are lower data type compared to given method argument
⚫ If there are 2 overloaded methods one with lower data type argument and other with higher data
type argument, if you pass a lower data type value and call the method , compiler will always
choose method with lower data type argument
⚫ Even though int and float have same capacity the data is represented in a different format.
⚫ Compared to float and int , float is higher data type and int is lower data type
⚫ Even though long and double have same capacity the data is represented in a different format.
⚫ Compared to double and long , double is higher data type and long is lower data type.
⚫ If you store a character value within an integer variable then its unicode value will be stored in the
given integer variable.
⚫ If a method is having NonPrimitive data type argument then for the same method we can pass
object of same class or subclass object to given method argument.
⚫ If there are 2 overloaded methods one with subclass type argument and other with parent type
argument, if you pass a subclass object and call the method , compiler will always choose method
with subclass type argument

package [Link];

public class Demo {


//formal & actual argument
public static void m1(int a) {
[Link]("m1 method");
}

public static void m2(double b)


{
[Link]("m2 method");
}

//return type & return statement


public static int m3() {
//return 10;//same
//return 'c';//char
// byte b=3;
// return b;//byte
short s=45;
return s;

public static double m4() {


//return 2.3;//same
//return 3;//int
//return 'f';//char
// byte b=3;
// return b;
// short s=4;
// return s;

// long l=75656748L;
// return l;

float f=856.665F;
return f;
}

public static void m5(int a) {


[Link]("m5 with int arg");
}
public static void m5(double b) {
[Link]("m5 with double arg");
}
public static void main(String[] args) {
m5(10);

[Link]("-----------------");
m1(10);
m1('a');//widening
byte b=1;
m1(b);
short s=34;
m1(s);

m2(3.4);
m2(3);//widening
m2('h');//widening
m2(b);
m2(s);
long l=4555L;
m2(l);
float f=45.7f;
m2(f);
}
}

package [Link];
//super class
class Bird{

}
//sub class
class Parrot extends Bird{

}
public class Sample {

public static void m1(Parrot p) //new Parrot();


{
[Link]("m1 method");
}

public static void m2(Bird b) //new Bird();


//Bird b=new Parrot();----upcasting
{
[Link]("m2 method");
}

public static Parrot m3() {


return new Parrot();
}
public static Bird m4() {
//return new Bird();
return new Parrot();
}
public static void m5(Parrot p) {
[Link]("m5 with parrot");
}
public static void m5(Bird b) {
[Link]("m5 with bird");
}

public static void main(String[] args) {


m1(new Parrot());

m2(new Bird());
m2(new Parrot());

m5(new Parrot());

}
}

Polymorphism

1. Polymorphism means many forms.


2. The ability of a method to behave differently, when different objects are acting upon it.
3. The ability of a method to exhibit different forms, when different objects are acting upon it.
4. Different types of polymorphism are as follows:
i. Compile time polymorphism.
ii. Run time polymorphism.

**************************************************************
Compile time Polymorphism

1. Binding the method declaration to method definition by the compiler at the compile time based on
the arguments is called as compile time Polymorphism.
2. Since the binding is done before the execution it is called as early binding.
3. Once the binding is done it cannot be changed at the Runtime and hence it is also called as Static
Binding.
4. Method Overloading & Constructor Overloading is the best example for Compile time
Polymorphism.
5. Out of so many overloaded methods, which method implementation should get executed is decided
by the compiler during compile time based on arguments.

1a.
package compiletime;
public class Myntra {
void purchase(int cost)
{
[Link]("Cost: Rs."+cost);
}
void purchase(String brand, String product)
{
[Link]("Brand: "+brand+" Product "+product);
}
void purchase(String paymentGateway)
{
[Link]("Payment Gateway: "+paymentGateway);
}
void purchase(String product, int cost)
{
[Link]("Product: "+product+" Cost: "+cost);
}
void purchase(int cost, String product)
{
[Link]("Cost: "+cost+" Product: "+product);
}
}

1b.
package compiletime;
public class Customer {
public static void main(String[] args) {
Myntra m = new Myntra();
[Link]("GooglePay");
[Link](2500);
[Link]("Shoe", 3000);
[Link](15000, "Mobile");
[Link]("Adidas", "T-Shirt");
}
}

o/p:
Payment Gateway: GooglePay
Cost: Rs.2500
Product: Shoe Cost: 3000
Cost: 15000 Product: Mobile
Brand: Adidas Product T-Shirt

Run time Polymorphism


1. Run time Polymorphism is achieved with the help of
i. Inheritance (IS-A Relationship)
ii. Method Overriding
iii. Upcasting
2. When we call an Overridden method on the superclass reference, the method implementation which
gets executed is dependent on the subclass acting upon it.
3. Out of so many Overridden method, which method implementation should get executed is decided by
the JVM at runtime based on object creation.
4. Runtime Polymorphism is also called as Late Binding, Dynamic Binding.
[Link] the method declaration to method definition by the JVM at the run time based on the objects
is called as run time Polymorphism.
[Link] the binding is done during the execution it is called as late binding.
[Link] the binding is done it can be changed at the Runtime and hence it is also called as dynamic
Binding.
[Link] Overriding is the best example for Run time Polymorphism

Note:
If we call an overridden method on the superclass reference, always the overridden method
implementation only gets executed. This is called as Golden Java Rule.

1a.
package runtime;
public class Employee {
void work() {
[Link]("Working");
}
}

1b.
package runtime;
public class Developer extends Employee {
@Override
void work() {
[Link]("Developer is " + "developing an application");
}
}

1c.
package runtime;
public class Tester extends Employee {
@Override
void work() {
[Link]("Tester is " + "testing an application");
}
}

1d.
package runtime;
public class Test {
public static void main(String[] args) {
Employee e = new Developer();
[Link]();
Employee emp = new Tester();
[Link]();
}
}

o/p:
Developer is developing an application
Tester is testing an application

2a.
package compiletime;
public class Vehicle
{
void start()
{
[Link]("Vehicle Started");
}
}

2b.
package compiletime;
public class Car extends Vehicle // 1
{
@Override
void start() // 2
{
[Link]("Car Started");
}
}

2c.
package compiletime;
public class Bike extends Vehicle { // 1
@Override
void start() { // 2
[Link]("Bike Started");
}
}

2d.
package compiletime;
public class Test {
public static void main(String[] args) {
Vehicle v1 = new Car();
[Link]();
Vehicle v2 = new Bike();
[Link]();
}
}

o/p:
Car Started
Bike Started

2e.
package compiletime;
public class Demo {
void invokeStart(Vehicle v) // Vehicle obj = new Car(); -> Vehicle obj = new Bike();
{
[Link]();
}
public static void main(String[] args)
{
Demo d = new Demo();
[Link](new Car());
[Link](new Bike());
}
}
o/p:
Car Started
Bike Started

package runtime;
public class MainClass
{
static void invokeWork(Employee emp)
{
[Link]();
}
public static void main(String[] args)
{
invokeWork(new Tester());
invokeWork(new Developer());
[Link]("-------------");
Tester t = new Tester();
invokeWork(t);
Developer d = new Developer();
invokeWork(d);
}
}

Abstraction

1. The process of Hiding the Implementation details and showing only the functionalities (Behaviour) to
the user with the help of an abstract class or interface is called as Abstraction.
2. The process of Hiding the Implementation and showing only the functionality is called as Abstraction.
3. Abstraction can be achieved by following the below
rules:
i. Abstract class or Interface.
ii. Is-A (Inheritance).
iii. Method Overriding.
iv. Upcasting.

abstract
1. abstract is a keyword which can be used with class and method.
2. A class which is not declared using abstract keyword is called as Concrete class.
3. Concrete class can allow only concrete methods.
4. A class which is declared using abstract keyword is called as Abstract class.
5. Abstract class can allow both abstract and concrete methods.
6. Concrete method has both declaration and implementation/definition.
7. Abstract method has only declaration but no implementation.
8. All Abstract methods should be declared using abstract keyword.

Contract of Abstract or What should we do when a class extends abstract class:


1. When a class Inherits an abstract class, override all the abstract methods.
2. When a class Inherits an abstract class and if we do not want to override the inherited abstract method,
then make the sub class as abstract class.

Can abstract class have constructors?


Yes. But we cannot invoke indirectly, it has to be invoked by the sub class constructor either implicitly
or explicitly using super().
----------------------------------------------------
NOTE:
1. Can a class inherit an abstract class? -> YES
2. We cannot create an object of abstract class.
3. Abstract methods cannot be private.
4. Abstract methods cannot be static.
5. Abstract methods cannot be final.

1a.
package com;
public abstract class Person
{
abstract void work();
}

1b.
package com;
public class Employee extends Person {
@Override
void work() {
[Link]("Working");
}
public static void main(String[] args) {
Employee e = new Employee();
[Link]();
}
}

o/p:
Working

2a.
package com;
public abstract class Vehicle {
abstract void start();
void shiftGears() {
[Link]("Shifting Gears!");
}
}

2b.
package com;
public abstract class Car extends Vehicle
{
abstract void stop();
// start() and shiftGears();
}

2c.
package com;
public class User extends Car {
@Override
void stop() {
[Link]("Car Stopped");
}
@Override
void start() {
[Link]("Car Started");
}
// optionally override shiftGears() as well
public static void main(String[] args) {
User u = new User();
[Link]();
[Link]();
[Link]();
}
}

o/p:
Car Started
Shifting Gears!
Car Stopped

Constructors in Abstract Class.


1a.
package org;
public abstract class Father
{
Father(){
[Link](1);
}
}

1b.
package org;
public class Son extends Father
{
Son()
{
// implicitly super();
[Link](2);
}
}

1c.
package org;
public class Test {
public static void main(String[] args) {
Son s = new Son();
}
}

o/p:
1
2

2a.
package org;
public abstract class Father
{
Father(int a)
{
[Link](1);
}
}

2b.
package org;
public class Son extends Father
{
Son()
{
super(10);
[Link](2);
}
}

2c.
package org;
public class Test {
public static void main(String[] args) {
Son s = new Son();
}
}
o/p:
1
2

1a.
package com;
public abstract class Person {
abstract void work();
}

1b.
package com;
public class Employee extends Person { // implements Person
@Override
public void work() {
[Link]("Employee is Working");
}
}

1c.
package com;
public class Test {
public static void main(String[] args) {
/*Employee e = new Employee(); [Link]();*/
Person p = new Employee();
[Link]();
}
}

o/p:
Employee is Working
interface
1. Interface is a keyword which is used to create interface block.
2. Interface act like blueprint to create a class.

syntax: interface InterfaceName


{
}
3. Interface can have variables, those variables are automatically public, static and final.
4. Interface can allow only abstract methods, and those methods are automatically public and abstract.
5. class can achieve IS-A Relationship with an interface using implements keyword.
6. When a class implements an interface, mandatorily override the abstract method.
7. While Overriding a method, Access Specifier/Modifier should be same or of Higher Visibility.
8. A class can implement any number of Interfaces (Multiple Interfaces).
9. A class can extend 1 class and implement any number of interfaces.
10. Interfaces does not contain Constructors.
11. We cannot create an object of interface.

Programs
1a.
package org;
public interface Person {
int id = 101; // public static final int id = 101;
void eat(); // public abstract void eat();
}

1b.
package org;
public class Dinga implements Person {
@Override
public void eat() {
[Link]("Eating");
}
public static void main(String[] args) {
[Link]([Link]);
Dinga d = new Dinga();
[Link]();
}
}

o/p:
101
Eating

2a.
package org;
public interface ReserveBank
{
void deposit();
}

2b.
package org;
public interface ICICIBank extends ReserveBank
{
void withdraw();
}

2c.
package org;
public class Customer implements ICICIBank {
@Override
public void deposit() {
[Link]("Depositing Amount");
}
@Override
public void withdraw() {
[Link]("Withdrawing Amount");
}
public static void main(String[] args) {
Customer c = new Customer();
[Link]();
[Link]();
}
}

o/p:
Depositing Amount
Withdrawing Amount

3a.
package org;
public interface Jspiders {
void devlop();
}

3b.
package org;
public interface Qspiders {
void test();
}

3c.
package org;
public class TestYantra {
void work() {
[Link]("Working");
}
}

3d.
package org;
public class Emp extends TestYantra implements Qspiders, Jspiders {
@Override
public void devlop() {
[Link]("Developing");
}
@Override
public void test() {
[Link]("Testing");
}
}

3e.
package org;
public class Solution {
public static void main(String[] args) {
Emp u = new Emp();
[Link]();
[Link]();
[Link]();
}
}

o/p:
Developing
Testing
Working

Note:
* Methods inside interface will have public & abstract by default, so we cannot have body for abstract
method.
* We cannot update or reinitialize the variable because by default variable will be prefixed with public
static & final modifiers.
* Without initializing we cannot use final variable , so it is mandatory to initialize variables inside
interface.

Inheritance w.r.t. Interfaces:


* Inheritance between interface & interface can be achieved with the help of extends keyword.
* Inheritance between class & interface can be achieved with the help of implements keyword.

Note:
1. The static methods of interfaces are not inherited.
2. The Abstract methods & the public static final variables will be inherited.

-An Interface cannot inherit more than one interfaces with the help of extends keyword.-
-A class can inherit any number of Interface using implements keyword.

Ex: interface A1
{
}
Class B implements A1
{
}
ii) A class can inherit any number of interfaces.
Ex: interface A1{
}

interface A2{
}

Class B implements A1,A2{


}

-A class can inherit one class & any no. of interfaces.


Ex: interface A1{}
interface A2{}
class A3{}
Class B extends A3 implements A1,A2{}

Note: Whenever a class is inheriting from both the types of members i.e. A class as well as interfaces,
we must always make sure we use extends keyword first & then implements, else we get CTE.
*Interface cannot inherit class, it is not possible in java.

Application of interface :

If we have to develop a class using Two Super Types then we should use interfaces.
Note: Abstract class cannot be used here because, a class cannot extends from Two Different super
classes at the same time.
ENCAPSULATION

-The process of binding both states and behaviours of an object together is known as Encapsulation.
-We can achieve Encapsulation with the help of class.

Data Hiding: The Process of restricting the direct access to the states of the class but providing
controlled access with the help of behaviours of the same class is known as Data Hiding.
-Data Hiding is possible only inside encapsulated class.

Steps to achieve DataHiding:


[Link] the data member with the help of private access modifier.
2. Define the getter & setter method based on Requirement.

Getter Method: It is a Method which is used to print the private members data from different class.
-It returns the data of members which has to be read.

Syntax: Datatype of private_member getPrivateMemberName()


{
return private_member_name;
}

Setter Method: It is a Method which is used to modify the data of private member of different class.
-Setter method must always accept an input , it must have formal arguments.

Syntax: void setPrivateMemberName ( DatatypeofprivateMember identifier)


{
[Link]=identifier;
}

Programs

1a.
package [Link];
public class Person
{
private int age;
public void setAge(int age)
{
[Link] = age;
}
public int getAge()
{
return age; // return [Link];
}
}

1b.
package [Link];
public class TestPerson {
public static void main(String[] args) {
Person p = new Person();
[Link](25);
int age = [Link]();
[Link]("Age: "+age);
[Link]([Link]());
}
}
/*[Link]([Link]);
[Link] = 20;*/

o/p:
Age: 25
25

Has-A Relation
An object being dependent on another object is known as has-a relationship.
Example : Relationship between Car & Engine, Person & Laptop, Student & Book ,Bank &
Account ,Student & Subject etc…

How to achieve has-a relationship in java?


We can design objects such that the depending object is having the reference of dependent object.
To implement hass-a relationship:
1. Create blueprint(class) for dependent and depending Objects.
2. Create a non static reference variable in depending class (Car) of dependent class (Egine) type.
3. Later we can initialize the dependent object.

[Link] [Link];
public class Engine {
int cc;
}

1b.
package [Link];
public class Car {
String model;
Engine eng;
}

1c.
package [Link];
public class CarEngineDriver {
public static void main(String[] args) {
Car car=new Car();

[Link]([Link]);
[Link]([Link]);

[Link]="bmw";
[Link]=new Engine();

[Link]([Link]);
[Link]([Link]);

[Link]([Link]);

[Link]=200;

[Link]([Link]);
}

}
2a.
package [Link];
public class Address {

String area;
String city;
int pincode;

public Address(String area,String city,int pincode) {


[Link]=area;
[Link]=city;
[Link]=pincode;
}

public void displayAddress() {


[Link]("Address is---------------");
[Link](area);
[Link](city);
[Link](pincode);
}
}

2b.
package [Link];
public class Employee {
int id;
String name;
double salary;

Address add;

public Employee(int id,String name,double salary,Address add) {


[Link]=id;
[Link]=name;
[Link]=salary;
[Link]=add;
}

public void showEmpDetails() {


[Link]("Employee details-----------");
[Link](id);
[Link](name);
[Link](salary);

[Link]();
}
}

2c.
package [Link];
public class EmployeeMain {
public static void main(String[] args) {

Address a1=new Address("mgroad", "bangalore", 560015);


Employee e1=new Employee(101, "allen", 5.6, a1);
[Link]();

You might also like