Java Part2
Java Part2
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
- Anything which is present in the real world and physically existing can be termed as an Object.
Ex: Car,laptop,Tv etc…….
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……
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….
*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.
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.
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
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.
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.
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
String name="Allen";
long accno=98765432102L;
double balance=0.0;
String ifsc="SBI0067";
String branch="mgraod";
static String bankName="SBI";
}
}
Reference 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
String name="Allen";
long accno=98765432102L;
double balance=0.0;
String ifsc="SBI0067";
String branch="mgraod";
static String bankName="SBI";
[Link](a);
[Link]();
[Link](500);
[Link](200);
Account a2=new Account();
[Link](1000);
[Link](100);
}
}
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).
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
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.
[Link](a);
[Link](b);
}
test();
}
}
--------------------------------------------------------
public class GlobalVariable //Member
{
static int a;
double b;
}
public static void main(String[] args) {
[Link](a);
➢ Member static variable and local variable can be differentiated from static method by using
[Link].
//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.
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.
[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.
int b=10;
[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 {
}
-------------------------------------------------------------
double marks=45.6;
/*diffrentiate non static global and local variable having same name */
[Link](new Test1().marks);//45.6
}
------------------------------------------------------------
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);
}
[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
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
Application of Constructor.
Constructors are used to Intialize the data members of the class.
Packages:
A java package is group of classes and interfaces which are related to one single module in the given
project.
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 members
[Link](b);
m2();
//default members
[Link](c);
m3();
//private members
[Link](d);
m4();
}
}
package [Link];
//public members
[Link](Sample.a);
Sample.m1();
//protected members
[Link](Sample.b);
Sample.m2();
//default members
[Link](Sample.c);
Sample.m3();
package [Link];
import [Link];
public class Run {
//different package access
public static void main(String[] args) {
//public members
[Link](Sample.a);
Sample.m1();
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");
}
package [Link];
public class Student {
int id;
String name;
String email;
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));
}
}
Class diagram
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
Types of Inheritance
1. Single Level Inheritance
2. Multi-Level Inheritance
3. Hierarchical Inheritance
4. Multiple Inheritance
5. Hybrid Inheritance
int a=10;
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
//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 {
1b
package [Link];
public class WhatsAppV3 extends WhatsAppV2{
1d
package [Link];
public class MainClass {
public static void main(String[] args) {
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");
}
}
}
package [Link];
public class Student {
int id;
String name;
String email;
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 .
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
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.
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];
// long l=75656748L;
// return l;
float f=856.665F;
return f;
}
[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 {
m2(new Bird());
m2(new Parrot());
m5(new Parrot());
}
}
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
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.
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
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.
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.
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{
}
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.
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.
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.
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…
[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;
2b.
package [Link];
public class Employee {
int id;
String name;
double salary;
Address add;
[Link]();
}
}
2c.
package [Link];
public class EmployeeMain {
public static void main(String[] args) {