0% found this document useful (0 votes)
5 views

class and object

The document provides an overview of object-oriented programming concepts in Java, including classes, objects, fields, methods, and constructors. It illustrates these concepts with examples, such as creating classes for Mobile and Human, demonstrating method overloading, and explaining the use of 'this' keyword. Additionally, it covers different types of constructors, including default, parameterized, and copy constructors, along with their rules and usage.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

class and object

The document provides an overview of object-oriented programming concepts in Java, including classes, objects, fields, methods, and constructors. It illustrates these concepts with examples, such as creating classes for Mobile and Human, demonstrating method overloading, and explaining the use of 'this' keyword. Additionally, it covers different types of constructors, including default, parameterized, and copy constructors, along with their rules and usage.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 74

class : is a blueprint or template.

It is having the properties (fields) and behaviors


(methods).

Fields: nothing but static variables and instance variables

Methods :nothing but static and non static methods(instance).

Object: object is an instance of a class and inorder access the fields and methods we need to create
an object for the class.

Ex:1 Mobile class (Assigning the values directly in class)


class Mobile {
public String brand = "Samsung";
public String model = "Galaxy S23";
public double price = 799.99;
public int batteryCapacity = 4500;

public void makeCall(String phoneNumber) {


System.out.println("Calling " + phoneNumber + " from " + brand + " " + model);
}

public void sendMessage(String phoneNumber, String message) {


System.out.println("Sending message to " + phoneNumber + ": " + message);
}

/*public void displayDetails() {


System.out.println("Brand: " + brand);
System.out.println("Model: " + model);
System.out.println("Price: $" + price);
System.out.println("Battery Capacity: " + batteryCapacity + "mAh");
}*/
public static void main(String[] args) {
Mobile myPhone = new Mobile();
myPhone.makeCall("987-654-3210");
myPhone.sendMessage("987-654-3210", "Hi there! How are you?");
//myPhone.displayDetails();
}
}

EX:2 Reading the values from the user input


import java.util.Scanner;

class Mobile {
public String brand;
public String model;
public double price;
public static int batteryCapacity;

public static void makeCall(String phoneNumber, String brand) {


System.out.println("Calling to " + phoneNumber + " from " + brand);
}

public void sendMessage(String phoneNumber, String brand) {


System.out.println("Sending message to " + phoneNumber +" from " + brand);
}

public void displayDetails() {


System.out.println("Brand: " + brand);
System.out.println("Model: " + model);
System.out.println("Price: $" + price);
System.out.println("Battery Capacity: " + batteryCapacity + "mAh");
}

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);
Mobile myPhone = new Mobile();
// Read values from the user
System.out.print("Enter the brand: ");
myPhone.brand = sc.nextLine();

System.out.print("Enter the model: ");


myPhone.model = sc.nextLine();

System.out.print("Enter the price: ");


myPhone.price = sc.nextDouble();

System.out.print("Enter the battery capacity (mAh): ");


batteryCapacity = sc.nextInt();

sc.nextLine(); // Consume newline left-over from nextInt()

System.out.print("Enter the phone number :");


String phoneNumber = sc.nextLine();

// Use static method


makeCall(phoneNumber,myPhone.brand);

// Use instance method


myPhone.sendMessage(phoneNumber, myPhone.brand);

System.out.println("\nMobile Details:");
myPhone.displayDetails();

sc.close(); // Close the scanner


}
}
EX: 3:Creating multiple objects

class Mobile {
public String brand;
public String model;
public double price;
public static int batteryCapacity;

public static void makeCall(String phoneNumber, String brand) {


System.out.println("Calling " + phoneNumber + " from " + brand);
}

public void sendMessage(String phoneNumber, String brand) {


System.out.println("Sending message to " + phoneNumber + " from " + brand);
}

public void displayDetails() {


System.out.println("Brand: " + brand);
System.out.println("Model: " + model);
System.out.println("Price: $" + price);
System.out.println("Battery Capacity: " + batteryCapacity + "mAh");
}

public static void main(String[] args) {


// Create and assign values to the first phone
Mobile phone1 = new Mobile();
phone1.brand = "Samsung";
phone1.model = "Galaxy S23";
phone1.price = 899.99;
batteryCapacity = 4500; // Static variable

// Create and assign values to the second phone


Mobile phone2 = new Mobile();
phone2.brand = "Apple";
phone2.model = "iPhone 14";
phone2.price = 1099.99;
batteryCapacity = 4000; // Static variable

// Create and assign values to the third phone


Mobile phone3 = new Mobile();
phone3.brand = "OnePlus";
phone3.model = "OnePlus 11";
phone3.price = 699.99;
batteryCapacity = 5000; // Static variable

// Use the first phone


System.out.println("\nUsing the first phone:");
Mobile.makeCall("123-456-7890", phone1.brand);
phone1.sendMessage("123-456-7890", phone1.brand);
phone1.displayDetails();

// Use the second phone


System.out.println("\nUsing the second phone:");
Mobile.makeCall("987-654-3210", phone2.brand);
phone2.sendMessage("987-654-3210", phone2.brand);
phone2.displayDetails();

// Use the third phone


System.out.println("\nUsing the third phone:");
Mobile.makeCall("555-123-4567", phone3.brand);
phone3.sendMessage("555-123-4567", phone3.brand);
phone3.displayDetails();
}
}

Example:Human
class Human {
public String name;
public int age;
public String gender;

// Method to print individual details


public void printDetails() {
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Gender: " + gender);
}

// Method to print activities


public void activities() {
System.out.println(name + "'s Daily Activities:");
System.out.println("- Morning: Wake up, Exercise, Have breakfast");
System.out.println("- Afternoon: Work or study");
System.out.println("- Evening: Spend time with family, Read, or Relax");
System.out.println("--------------------");
}

public static void main(String[] args) {


// Create and assign values to Raju
Human raju = new Human();
raju.name = "Raju";
raju.age = 25;
raju.gender = "Male";

// Create and assign values to Ramesh


Human ramesh = new Human();
ramesh.name = "Ramesh";
ramesh.age = 30;
ramesh.gender = "Male";
// Create and assign values to Suresh
Human suresh = new Human();
suresh.name = "Suresh";
suresh.age = 28;
suresh.gender = "Male";

// Print details and activities of each individual


System.out.println("Individual Details and Activities:");
raju.printDetails();
raju.activities();
ramesh.printDetails();
ramesh.activities();
suresh.printDetails();
suresh.activities();
}
}

Method Overloading :
 It is the process of defining more than one method with the samename for different
purpose
 In Method Overloading Method name must be same, list of arguments should not be
same , return type may or may not be same

Example :1

class Calculator {
int add(int a, int b) {
return a + b;
}
public void add(int a,int b,int c)
{
System.out.println("Addition of three integers is :"+(a+b+c));
}
String add(String a, String b) {
return a + " " + b;
}
double add(double a, double b) {
return a + b;
}

public static void main(String[] args) {


Calculator calc = new Calculator();
System.out.println("Addition of two integers: " + calc.add(5, 10));
calc.add(10,20,30);
System.out.println("Concatenation of two strings: " + calc.add("Hello",
"World"));
System.out.println("Addition of two doubles: " + calc.add(5.5, 10.5));
}
}
-we can also overload static methods

class Test {
static void display(int x) {
System.out.println("Display method with int: " + x);
}
static void display(String s) {
System.out.println("Display method with String: " + s);
}
void display(int x, String s) {
System.out.println("Display method with int and String: " + x + " " + s);
}

public static void main(String[] args) {


Test t=new Test();
display("Hello!");
display(10);
t.display(20, "World!");
}
}

EX:2

class TestIQ {
void method1(byte b) {
System.out.println("byte : " + b);
}

void method1(short s) {
System.out.println("short : " + s);
}

void method1(int i) {
System.out.println("int : " + i);
}

public static void main(String args[]) {


TestIQ t = new TestIQ();
t.method1(10);
t.method1(100);
t.method1(10000);
}
}

EX:3

class TestIQ {
void method1(byte b) {
System.out.println("byte : " + b);
}
void method1(short s) {
System.out.println("short : " + s);
}

void method1(int i) {
System.out.println("int : " + i);
}

public static void main(String args[]) {


TestIQ t = new TestIQ();
t.method1((byte)10);
t.method1((short)100);
t.method1(10000);
}
}

EX:4

class Testing {
void method1(float x) {
System.out.println("Mtd-1 Float : " + x);
}

public static void main(String args[]) {


Testing t = new Testing();
t.method1(12);
t.method1('A');
}
}

O/P->Mtd-1 Float : 12.0

Mtd-1 Float : 65.0

EX:5

class IQ{
public static void main(String args[]) {
System.out.println("Hello Dear");
IQ i = new IQ();
int sq = i.main(5);
System.out.println("Result is : " + sq);
}

public int main(int x) {


int s;
s = x * x;
return s;
}
}

O/pHello Dear

Result is : 25

This :

 “this “ is keyword of reference type


 “this” is existed implicitly in every instance method of the class
 “this” is always used to refer current object by hold its hash code
 Whenever both local and instance fields declare with the same in  order to
make the differentiation between local and instance fields, Then we have
make use “this” for an instance field
 “this” is not supported in the static context

EX:1
class Test
{
int x=111;
public void method1()
{
int x=222;
System.out.println(x);
System.out.println(this.x);

}
public static void main(String[] args) {
Test t=new Test();
t.method1();

}
}

EX:2: copying the data from one object to another obj


class Sample {
int x, y;
void method1(int x, int y) {
this.x = x;
this.y = y;
}
void method2(Sample o) {
this.x = o.x;
this.y = o.y;
}

void display() {
System.out.println("x value is : " + x);
System.out.println("y value is : " + y);
}

public static void main(String args[]) {


Sample s1 = new Sample();
s1.method1(120, 250);

Sample s2 = new Sample();


s2.method2(s1);

System.out.println("Data from s1");


s1.display();

System.out.println("Data from s2");


s2.display();
}
}

Constructor : It is an initializer method , it is used for object instantiation.

Rules Of the Constructor :

 Constructor name and class name must be same


 Constructors can be parameterized
 Constructors can be overloaded
 Constructor can nested [constructor chaining ]
 Execution order of the constructors always from top to bottom
 Constructor never returns any value

Type of Constructors :

 Default constructor
 Parameterized Constructor
 Copy Constructor
Default constructor:

It is a process of defining a constructor with out any arguments called 0


parameterized constructor or parameter less constructor

EX:1
class Rect {
float l, b;
Rect(){
l = 4.0f;
b = 4.0f;
}
float findArea() {
return (l * b);
}

public static void main(String args[]) {


Rect r = new Rect();
float ar = r.findArea();
System.out.println("Area of Rect: " + ar);
}
}

2. Parameterized Constructor:

 Process of defining the constructor with primitive type parameter


 If the class is defined only with parameterized constructor then  it is
mandatory to pass the parameter to that constructor in order initiation of
an Object, otherwise JVM is trying to call default constructor which is not
defined in the class thus it will raise an Error

class Rect {
float l, b;
Rect(float l,float b){
this.l =l;
this.b =b;
}
float findArea() {
return (l * b);
}

public static void main(String args[]) {


Rect r = new Rect(4.0f,4.0f);
float ar = r.findArea();
System.out.println("Area of Rect: " + ar);
}
}

3. Constructor Overloading :

Process of defining more than one constructor for different purpose


class Calculator{
int intResult;
String stringResult;
double doubleResult;
Calculator(int a, int b) {
System.out.println(a+b);
}
Calculator(int a, int b, int c) {
System.out.println(a+b+c);
}
Calculator(String a, String b) {
System.out.println(a+b);
}
Calculator(double a, double b) {
System.out.println(a+b);
}

public static void main(String[] args) {


Calculator calc1 = new Calculator(5, 10);
Calculator calc2 = new Calculator(10, 20, 30);
Calculator calc3 = new Calculator("Hello", "World");
Calculator calc4 = new Calculator(5.5, 10.5);
}
}

4.constructor chaining

 It is process of calling an existed constructor into another constructor of the


same class
 It is possible using “this()”
 Advantages are reusability of code
 Call to this( ) must be the first statement in constructor
class Calculator{
Calculator(int a, int b) {
System.out.println(a+b);
}
Calculator(int a, int b, int c) {
this(10,20);
System.out.println(a+b+c);
}
Calculator(String a, String b) {
this(5,5,5);
System.out.println(a+b);
}
Calculator(double a, double b) {
this("hello","world");
System.out.println(a+b);
}

public static void main(String[] args) {


Calculator calc4 = new Calculator(5.5, 10.5);
}
}

5. Copy Constructor :

 It is the process of defining constructor with reference type parameters


 The main motto of copy constructor is coping the data from one object to
another
 In order to work with copy constructor , then corresponding class must be
defined with either a default constructor or parameterized constructor .
along with copy constructor.

class Sample {
int x, y;
Sample() {
x = 222;
y = 444;
}
Sample(Sample o) {
x = o.x;
y = o.y;
}
void display() {
System.out.println("x val is: " + x);
System.out.println("y val is: " + y);
}

public static void main(String args[]) {


Sample s1 = new Sample();
Sample s2 = new Sample(s1);
s1.display();
System.out.println("Data From s2");
s2.display();
}
}

Note: we should not declare static variable in the constructor , but we can use static variables in the
constructor

Object-Oriented Programming (OOP):


Object-Oriented Programming (OOP) is a programming approach that organizes
code into reusable units called objects, which represent real-world entities. It
focuses on four main principles: encapsulation (hiding data), inheritance (reusing
code), polymorphism (flexible functionality), and abstraction (simplifying
complexity).

Key Concepts of OOP:

1.Class

2.object

3. Inheritance

4. Abstraction

5. Polymorphism

6. Encapsulation

1.Inheritance It is process of creating a new class by taking the properties of an


existed class Advantages are (OR) one class is acquiring the properties of another
class.

 Reusability of the code


 Code optimization
 Memory optimization
 Cost and time of the project will be reduced
 Efficiency of the project will be increased
 A class which producing a new Class called “Superclass” or generalized
class
 A class which is inherited is called “Subclass” or specialized class
 Specialized class have rich set of properties than generalized class
 By creating an object of “superclass” we can access only “properties” of
superclass, but not the subclass.
 By Creating an Object of “subclass” then we can access properties of both
“super” and “subclass”
 It is always better way to create an Object for sub class.

Types Of Inheritance:

1. Single Inheritance: one child class acquiring the properties of only


one parent class(only one child &one parent class).
2. Multilevel Inheritance: more than one parent class and more than
one child class.
3. Hierarchical Inheritance: more than one child classes acquiring the
properties of one parent class(only one parent & more than one
child).
4. Multiple inheritance : one child class acquiring the properties of
more than one parent classes.(only one child & more than one
parent)
5. Hybrid Inheritance : combination of multiple inheritance and other
inheritances(sig,multi,hierar).
Note: In order to access the properties from one class to another the
corresponding classes need to have some relation ship.

In Java we have to two types of relation ships are Existed

1.HAS-A Relation ship

o Has-a relationship is the process of creating an object of the super class into
subclass
o By the reference of the super class we can access the properties of the
super into sub class

2.IS-A Relation Ship

o It is the process of the creating the sub class by extending properties of


super class
o In this process we have to make use “extends” keyword

EX:Has A
class Superclass {
int x = 100;

public void display() {


System.out.println("Display method from Superclass");
}
}
class Subclass {
Superclass sa = new Superclass();
int y = 200;

public void display() {


System.out.println("Display method from Subclass");
}
}

class AnotherClass {
public static void main(String args[]) {
Subclass sb = new Subclass();
System.out.println("y val is: " + sb.y);
System.out.println("x val is: " + sb.sa.x);

sb.display();
sb.sa.display();
}
}

EX:is A
class SuperA {
private int x = 111;
int y = 222;
static int z = 333;

public void display1() {


System.out.println("Display method from SuperA");
}
}

class SubB extends SuperA {


public void display2() {
System.out.println("Display method from SubB");
}
}
class AnotherClass {
public static void main(String args[]) {
SubB sb = new SubB();
System.out.println("y val is: " + sb.y);
System.out.println("z val is: " + SubB.z); //we cant call static by using obj
ref here
System.out.println("z val is: " + SuperA.z);
System.out.println("z val is: " + sb.z);
sb.display1();
sb.display2();
System.out.println("x val is : "+sb.x); //CE

}
}

EX:2 :mlutilevel

class Parent {
int x = 10;
int y = 20;
static int z = 30;

public void display1() {


System.out.println("Display method from Parent class");
}
}
class child1 extends Parent {
int a=100;
int b=200;
public void display2() {
System.out.println("Display method from child1");
}
}
class child2 extends child1 {
int c=101;
int d=201;
public void display3() {
System.out.println("Display method from child2");
}
public static void main(String args[]) {
child2 c1= new child2();
System.out.println("x val is: " + c1.x);
System.out.println("y val is: " + c1.y);
System.out.println("z val is: " + c1.z);
System.out.println("a val is: " + c1.a);
System.out.println("b val is: " + c1.b);
System.out.println("c val is: " + c1.c);
System.out.println("d val is: " + c1.d);
c1.display1();
c1.display2();
c1.display3();

}
}
3.Hierarchical Inheritance
class Parent {
int x = 10;
int y = 20;
static int z = 30;

public void display1() {


System.out.println("Display method from Parent class");
}
}
class child1 extends Parent {
int a=100;
int b=200;
public void display2() {
System.out.println("Display method from child1");
}
}
class child2 extends Parent {
int c=101;
int d=201;
public void display3() {
System.out.println("Display method from child2");
}
}
public class Main{
public static void main(String args[]) {
child1 c1=new child1();
child2 c2= new child2();
System.out.println("x val is: " + c1.x);
System.out.println("y val is: " + c2.y);
System.out.println("z val is: " + Parent.z);
System.out.println("a val is: " + c1.a);
System.out.println("b val is: " + c1.b);
System.out.println("c val is: " + c2.c);
System.out.println("d val is: " + c2.d);
c1.display1();
c1.display2();
c2.display3();

}
}
EX:multiple
public class Parent{
int x = 10;
int y = 20;
static int z = 30;

public void display1() {


System.out.println("Display method from Parent class");
}
}
class child1{
int a=100;
int b=200;
public void display2() {
System.out.println("Display method from child1");
}
}
class child2 extends child1,Parent{
int c=101;
int d=201;
public void display3() {
System.out.println("Display method from child2");
}
}
public static void main(String args[]) {
child1 c1=new child1();
child2 c2= new child2();
//System.out.println("x val is: " + c1.x);
//System.out.println("y val is: " + c2.y);
System.out.println("z val is: " + Parent.z);
System.out.println("a val is: " + c1.a);
System.out.println("b val is: " + c1.b);
//System.out.println("c val is: " + c2.c);
//System.out.println("d val is: " + c2.d);
//c1.display1();
c1.display2();
c2.display3();

EX:Hybrid
class Parent {
int x = 10;
int y = 20;
static int z = 30;

public void display1() {


System.out.println("Display method from Parent class");
}
}
class child1 extends Parent {
int a=100;
int b=200;
public void display2() {
System.out.println("Display method from child1");
}
}
class child2 extends Parent {
int c=101;
int d=201;
public void display3() {
System.out.println("Display method from child2");
}
}
class child3 extends child1,child2 {
int e=1001;
int f=2001;
public void display3() {
System.out.println("Display method from child2");
}
}

public class Main{


public static void main(String args[]) {
child1 c1=new child1();
child2 c2= new child2();
System.out.println("x val is: " + c1.x);
System.out.println("y val is: " + c2.y);
System.out.println("z val is: " + Parent.z);
System.out.println("a val is: " + c1.a);
System.out.println("b val is: " + c1.b);
System.out.println("c val is: " + c2.c);
System.out.println("d val is: " + c2.d);
c1.display1();
c1.display2();
c2.display3();

}
}
Note: “Java doesn’t support multiple and its related combinations using through
classes but, it is possible by using through interfaces.

Super: is a key word of reference type

 If both instance field of the sub and super class are declared with the same
name the priority is given to instance field of the “subclass”. If you want
access instance field of the “superclass” then we have to make use of
“super” keyword
 is not supported in the static context.

class SuperA {
int x = 111;
}

class SubB extends SuperA {


int x = 222;

void method1() {
int x = 333;
System.out.println("local var " + x);
System.out.println("Instance var of SubB : " + this.x);
System.out.println("Instance var of SuperA : " + super.x);
}
}

class Main{
public static void main(String[] args) {
SubB sb = new SubB();
sb.method1();
}
}

EX:
class A {
int x = 10;
}

class B extends A {
int x = 20;

int getSuperX() {
return super.x;
}
}

class C extends B {
int x = 30;

void method1() {
System.out.println("x in C (Current Class): " + this.x);
System.out.println("x in B (Parent): " + super.x);
System.out.println("x in A (Grandparent): " + getSuperX());
}
}
public class Main{
public static void main(String args[]) {
C c = new C();
c.method1();
}
}

EX: Super with methods


class SuperA {
void method1() {
System.out.println("method1 of SuperA");
}
}

class SubB extends SuperA {


void method1() {
super.method1();
System.out.println("method1 of SubB");
}
}

class Main{
public static void main(String args[]) {
SubB sb = new SubB();
sb.method1();
}
}

Rules of the Constructors in the Inheritance :


 the default constructor of the super class will be invoked by the default
constructor of the sub class implicitly
 If the Super Class is defined with both default and parameterized
constructor ,In this is case also the default constructor of super class will be
invoked by the default constructor of the Subclass implicitly . If you want
invoke the parameterized constructor of the super class by the default
constructor of subclass then we have make to use of “super()”

 If Super class and Sub class both are defined with the parameterized
constructors ,then we must call the parameterized constructor of the super
class by the parameterized constructor of subclass explicitly. Other wise
parameterized constructor of the sub class is trying to call default
constructor of the super

EX 1:first point
class SuperA {
SuperA() {
System.out.println("Def const of SuperA");
}
}

class SubB extends SuperA {


SubB() {
System.out.println("Def const of SubB");
}
}

class Main{
public static void main(String args[]) {
SubB sb=new SubB();
}
}

O/P Def const of SuperA

Def const of SubB

EX:2 point 2
class SuperA {
SuperA() {
System.out.println("Def const of SuperA"); //1
}

SuperA(int x) {
this();
System.out.println("Para const of SuperA X val : " + x); //2
}
}

class SubB extends SuperA {


SubB() {
super(123); //2
System.out.println("Def const of SubB"); //3
}
}

class Main{
public static void main(String args[]) {
SubB sb = new SubB();
}
}

EX 3: point 3
class SuperA {
SuperA() {
System.out.println("Def const of SuperA");
}
SuperA(int x) {
System.out.println("Para const of SA " + x);
}
}

class SubB extends SuperA {


SubB(int x) {
//super(145);
System.out.println("Para const of SB : " + x);
}
}

class Main{
public static void main(String args[]) {
SubB sb = new SubB(123);
}
}
Note : If you call either default or parameterized constructor of the subclass
then internally JVM will call “Default constructor “ of the Super class only

Note: this( ) vs super( )

o if you want call an existed constructor inside of another constructor of the same
class then we have to make user of “this( )”

o If you want call an existed constructor of the super class into another
constructor of the sub class then we have to make use of “super( )”

Polymorphism:
 Poly means many
 Morphism means forms or behaviors

“Polymorphism” is the process of exhibiting more than one form. Or ability to


generate more than one form.

 For an Example an operator “+” in java is polymorphic natured operator. i.e


the behavior of the operator is getting varying in different situations.
 If we pass two integers as an operands then internally it will perform an
addition and produce the sum Eg: 10+20 -> 30
 If we pass two strings as an operands then internally it will  perform
concatenation and produce the concatenated output. [“sai”+”baba” –>
“saibaba”]

Polymorphism is classified into 2 Types

o Compile-time Polymorphism

o Run-Time Polymorphism

Compile-Time Polymorphism:

 In compile time polymorphism memory decision will done at that time of


compilation .
Example : method overloading
 compile time polymorphism always takes place based on reference of the
Object and decision is made based on the number and type of parameters.

Run-time Polymorphism:

 In Runtime polymorphism the decision will be done at that time of


execution Example: Method Overriding.
 In Runtime polymorphism always takes place based on object we are
passing to the reference

What is difference between overloading and Overriding ?

Overloading :

 It is the process of defining more than one method with the same name
for different purpose
 In method overloading , method name must be same, list of argument
should not be same,return type may or may not be same
 Overloading can be done either in the same class or in its inherited class

Overriding :

 It is the process of defining sub class method same as super class method
 In overriding method name must be same, list of arguments must be same
and return type must be same
 Overriding is possible only in its inherited class [is-a relationship]

When do we go for overriding ?

Whenever you want use super class method in the sub class with different
implementation , then will go for overriding

EX:compile time
class Parent {
void method1(int a,int b) {
System.out.println("the sum of two integers is " + (a+b));
}
}

class Child extends Parent {


void method1(String a,String b) {
System.out.println("the concatenation of two strings :" +(a+b));
}

void method1(int a, String b) {


System.out.println("the concatenation of one integer and string :" +(a+b));
}
}

public class Main{


public static void main(String[] args) {
Child c = new Child(); //if we use Parent c=new Child()-->we cant access
the properties of child
c.method1(10,20);
c.method1("Hello","world");
c.method1(10, "World");
}
}

EX :Method overriding no need


class Parent {
void method1(int a,int b) {
System.out.println("the sum of two integers in Parent class :" + (a+b));
}
}

class Child extends Parent {


void method1(int a,int b) {
System.out.println("the sum of two integers in Child class :" +(a+b));
}

public class Main{


public static void main(String[] args) {
Parent c = new Child();
c.method1(10,20);
c.method1(30,40);
}
}

EX: Method overriding


class Parent {
void method1(int a,int b) {
int res=a+b;
System.out.println("the sum of two integers in Parent: " +res);
}
/*void method1(int a,int b) {
int res=a+b;
System.out.println("the sum of two integers is :" +res);
}*/
}

class Child1 extends Parent {


void method1(int a,int b) {
int res=a-b;
System.out.println("the subtraction of two numbers in Child1: " +res);
}
}
class Child2 extends Child1{
void method1(int a,int b) {
int res=a*b;
System.out.println("the product of two integers in Child2: " +res);
}
}

public class Main{


public static void main(String[] args) {
Parent c = new Child2();
c.method1(10,20);
c=new Child1();
c.method1(10,20);
c=new Parent();
c.method1(10,20);
}
}

 The super class reference variable can hold the same class object.and it can
also hold any of it’s subclass Object implicitly called upcasting or
generalization.

class SuperA {
void displaySuperA() {
System.out.println("This is SuperA");
}
}

class SubB extends SuperA {


void displaySubB() {
System.out.println("This is SubB");
}
}

class Main {
public static void main(String[] args) {
SuperA a = new SuperA();
SubB b = new SubB();

a = b; // Upcasting SubB object to SuperA reference


a.displaySuperA();
//a.displaySubB(); // This would result in a compile-time error
}
}

A SubClass reference variable can hold the object of same class . but it can’t hold
the object of it’s super class implicitly. But we can make it possible explicitly using
“downcasting” or specialization.

EX:1

class SuperA {
void displaySuperA() {
System.out.println("This is SuperA");
}
}

class SubB extends SuperA {


void displaySubB() {
System.out.println("This is SubB");
}
}

class Main {
public static void main(String[] args) {
SuperA a=new SubB(); //and SubB class
SubB b = new SubB(); // SubB is having the object of SuperA only
//b=a; CE
b=(SubB)a;
}
}

 SuperA class ref var is having the objects of both


SuperA and SubB class
 SubB class ref var is having the object of SuperA
only doesnt have object of SuperA
 SubB class ref var is having the properties of both
SuperA and SubB class
 SuperA is having the properties of SuperA class
only. it doesn't have the properties of SubB class
class SuperA {
void displaySuperA() {
System.out.println("This is SuperA");
}
}

class SubB extends SuperA {


void displaySubB() {
System.out.println("This is SubB");
}
}
class Main {
public static void main(String[] args) {
SuperA a = new SuperA(); // SuperA is having the objects of both SuperA
SuperA b=new SubB(); //and SubB class
SubB c = new SubB(); // SubB is having the object of SuperA only
//SubB d=new SuperA(); //doesnt have object of SuperA CE
//c=(SubB)b
// Call methods
c.displaySuperA(); //SubB is having the properties of both SuperA
c.displaySubB(); //and SubB class
a.displaySuperA(); //SuperA is having the properties of SuperA class only.
//a.displaySubB(); // it doesn't have the properties of SubB class CE

}
}

EX:IQ

import java.lang.Object.*;
class TestIQ {
public static void main(String args[]) {
Object o; // Object reference
Integer i = new Integer(10);
Float f = new Float(3.14f);
String s = new String("Shashi");

// Assigning and downcasting correctly


o = i; // Upcasting to Object
System.out.println(" object type i val is :"+o);
Integer iCast =(Integer)o; // Downcasting to Integer
System.out.println("Integer type i value is :" + iCast);

o = f; // Upcasting to Object
System.out.println(" object type f val is :"+o);
Float fCast = (Float) o; // Downcasting to Float
System.out.println("Float type f value: " + fCast);

o = s; // Upcasting to Object
System.out.println(" object type s val is :"+o);
String sCast = (String) o; // Downcasting to String
System.out.println("String type s value: " + sCast);
}
}

Abstract Methods and Abstract Classes

Abstraction :

Abstraction in Java is the process of hiding implementation of a method by only


showing its method signature.( showing only the essential features of an object to
the outside world)

Abstract Methods:

1.Non abstract method


is method which is having body and implementation

Example:
int sum(int x,int y) //non abstract method
{
int s; s=x+y; retrun s;
}

2.Null body method :

is a method which is having body. But doesn’t have any implementation.every


null body method acts as non abstract method.but non abstract methods is not
null body method

Example:
void sum(int x,int y) //null body method
{}

3.Abstract method
is method which is not having body, just it is a declaration
Example: abstract
void sum(int x,int y);
(*star)In the class we can define only non abstract methods, but not abstract
methods
If we want to work with abstract methods,then we have to declare that abstract
method in Abstract class.

Abstract class:
if we declare any class with abstract key word is called abstract class.

 Abstract class is the collection of both abstract or non abstract methods


 It is not compulsory to have an abstract method in abstract class
 In the abstract class we define only non abstract methods or we  define
only abstract methods or we can define both abstract or non abstract
methods
 We can’t create an object for the abstract classes directly .but by extending
the abstract class by sub class ,we can create an object for abstract class.

Note : Creating an object for an abstract is nothing but creating an object any of
its Concrete class
Concrete class is a class which is overridden all the abstract methods of its
super class
Every Concrete class is subclass , But Every subclass is not Concrete class

When do we abstract methods and Abstract classes ?


Whenever two or more sub classes required to fulfill the same role through
different implementation

EX:we cant create object direcly 4rth point and star point

abstract class SuperA


{
int sum(int x, int y) // non-abstract method
{
int s;
s = x + y;
return s;
}

void sub(int x, int y) // null body method


{ }

abstract void mul(int x, int y); // abstract method


}
public class Main {
public static void main(String[] args) {
SuperA s=new SuperA(); //error

EX: 4 rth again


abstract class SuperA {
void nonAbsract(int x, int y) { // non-abstract method
int s;
s = x + y;
System.out.println("the nonAbsract sum in SuperA class is: "+s);
}

void nullBody(int x, int y) { // null body method


}

abstract void abstractMethod(int x, int y); // abstract method


/*void abstractMethod(int x, int y){
System.out.println("overriden abstract method in SubB class: " + (x + y));
}*/

class SubB extends SuperA {


void abstractMethod(int x, int y){
System.out.println("overriden abstract method in SubB class: " + (x * y));
}
}

public class Main {


public static void main(String[] args) {
SuperA s = new SubB();
s.nonAbsract(10,20);
s.nullBody(5, 3);
s.abstractMethod(5, 3);
}
}

Ex:Shapes Example
abstract class Shapes {
abstract void findArea(float dim1, float dim2);
}
class Triangle extends Shapes {
void findArea(float base, float height) {
float area = 0.5f * base * height;
System.out.println("Area of Triangle: " + area);
}
}
class Rect extends Shapes {
void findArea(float length, float width) {
float area = length * width;
System.out.println("Area of Rectangle: " + area);
}
}
class Circle extends Shapes {
void findArea(float radius, float unused) {
float area = (float) (Math.PI * radius * radius);
System.out.println("Area of Circle: "+ area);
//System.out.printf("Area of Circle: %.2f\n", area);
}
}
class Square extends Shapes {
void findArea(float side, float unused) {
float area = side * side;
System.out.println("Area of Square: " + area);
}
}
public class Main{
public static void main(String[] args) {
Shapes s = new Triangle();
s.findArea(4, 4);
s = new Rect();
s.findArea(5, 5);
s = new Circle();
s.findArea(3,2);
s = new Square();
s.findArea(6,6);
}
}

EX:one banking application small intrest rate project

import java.util.Scanner;
abstract class Bank {
abstract void calculateInterest(String name, String accNum, float depAmt);
}
class SBI extends Bank {
@Override
void calculateInterest(String name, String accNum, float depAmt) {
float rate;
if (depAmt <=20000) {
rate = 3;
} else if (depAmt <= 50000) {
rate = 5;
} else {
rate = 7;
}
float interest = (depAmt * rate) / 100;
float total = depAmt + interest;
System.out.println("SBI Bank - Name: " + name);
System.out.println("Account: " + accNum);
System.out.println("Deposit: " + depAmt);
System.out.println("Total after 1 year: " + total);
}
}
class Axis extends Bank {
@Override
void calculateInterest(String name, String accNum, float depAmt) {
float rate;
if (depAmt <=20000) {
rate = 4;
} else if (depAmt <= 50000) {
rate = 6;
} else {
rate = 7;
}
System.out.println("----------------------------");
float interest = (depAmt * rate) / 100;
float total = depAmt + interest;
System.out.println("\nAxis Bank - Name: " + name);
System.out.println("Account: " + accNum);
System.out.println("Deposit: " + depAmt);
System.out.println("Total after 1 year: " + total);
}
}
class ICICI extends Bank {
@Override
void calculateInterest(String name, String accNum, float depAmt) {
float rate;
if (depAmt <=20000) {
rate = 5;
} else if (depAmt <= 50000) {
rate = 6;
} else {
rate = 7;
}
float interest = (depAmt * rate) / 100;
float total = depAmt + interest;
System.out.println("----------------------------");
System.out.println("ICICI Bank - Name: " + name);
System.out.println("Account: " + accNum);
System.out.println("Deposit: " + depAmt);
System.out.println("Total after 1 year: " + total);
}
}
class HDFC extends Bank {
@Override
void calculateInterest(String name, String accNum, float depAmt) {
float rate;
if (depAmt <=20000) {
rate = 5;
} else if (depAmt <= 50000) {
rate = 7;
} else {
rate = 8;
}
float interest = (depAmt * rate) / 100;
float total = depAmt + interest;
System.out.println("----------------------------");
System.out.println("HDFC Bank - Name: " + name);
System.out.println("Account: " + accNum);
System.out.println("Deposit: " + depAmt);
System.out.println("Total after 1 year: " + total);
}
}

public class Main {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter name:");
String name = sc.nextLine();
System.out.println("Enter account number:");
String accNum = sc.nextLine();
System.out.println("Enter deposit amount:");
float depAmt = sc.nextFloat();
Bank bank;
bank = new SBI();
bank.calculateInterest(name, accNum, depAmt);
bank = new Axis();
bank.calculateInterest(name, accNum, depAmt);
bank = new ICICI();
bank.calculateInterest(name, accNum, depAmt);
bank = new HDFC();
bank.calculateInterest(name, accNum, depAmt);
}
}
Interface :

 Interface is the standard and public ways of defining the classes Interface is
also known as pure abstract class
 A class is collection of non abstract methods
 An abstract class is the collection of both abstract or non abstract methods
 An interface is the collection of abstract methods only
 By default all the variables in the interface “public final static”
 By default all the methods in the interface “public abstract”
EX:interface

interface IntA
{
int x=10; //public static final
void method1(); //public abstract

}
Note: What is difference between interface Functional Interface and Marker
interface ?
An Interface : is collection of abstract methods

Functional interface is an interface which allows us to declare only one


abstract method in it, if you want to define functional interface then we to use
[ @FunctionalInterface.

import org.jcp.xml.dsig.internal.SignerOutputStream;
@FunctionalInterface
interface SuperA
{
void method1(); //by default public abstract
}
class SubB implements SuperA
{
public void method1()
{
System.out.println("overriden method in SubB class");
}
}
class Main{
public static void main(String args[]){
SuperA ia=new SubB();
ia.method1();
}
}

Marker interface is an interface which is not having any abstract methods in it. In
simple word it is an empty interface
o java.lang.Cloneable | java.awt.event.ActionListener
o java.io.Serializable

Note : If any class is implemented by an interface with abstract methods then we


must override all the abstract methods of the interface in the sub class otherwise
we have declare the subclass as “abstract”.

Note:Point1
interface SuperA{

void method1();
}
abstract class SubB implements SuperA
{

}
public class Main {
public static void main(String[] args) {

}
}
Note:Point2

interface SuperA{
void method1();
}
class SubB implements SuperA
{
@Override
public void method1()
{

}
}
class Main{
public static void main(String args[]){
SuperA ia=new SubB();
ia.method1();
}
}

Note: Creating an object for an interface is nothing but creating an object for any
of it’s implemented class.

interface SuperA{
public abstract void method1();
}
class SubB implements SuperA{
@Override
public void method1()
{
System.out.println("Overriden method1 in SubB");
}
}
class Main{
public static void main(String args[]){
SuperA ia=new SubB();
ia.method1();
}
}

---support multiple inheritance

interface IA {
void method1();
}
interface IB {
void method1();
}
class SubB implements IA, IB {
@Override
public void method1() {
System.out.println("Overridden method1 of IA");
}
@Override //we cant achive the overriding in the same class no use
public void method1() {
System.out.println("Overridden method2 of IB");
}
}
class Main {
public static void main(String[] args) {
SubB s=new SubB();
s.method1();
}
}

O/P:
Overridden method1 of IA

---multiple by using classes

class A {
void method1()
{
System.out.println("this is method1 from class A");
}
}
class B {
void method1()
{
System.out.println("this is method1 from class B");
}
}

class C extends A,B {


}

public class Main {


public static void main(String[] args) {
C obj = new C();
obj.method1();
}
}
--By using interfaces variables(multiple)
interface A {
int VALUE = 10;
}

interface B{
int VALUE = 20;
}
class C implements A,B{

}
public class Main {
public static void main(String[] args) {
C obj = new C();
//System.out.println("Value by using obj ref" + obj.VALUE); //confusion
System.out.println("Static method from interface A: "+A.VALUE);
System.out.println("Static method from interface B: "+B.VALUE);
}
}

O/P:
Static method from interface A: 10
Static method from interface B: 20

---by using instance var in class multiple

class A {
int VALUE = 10;
}
class B{
int VALUE = 20;
}
class C implements A,B{

}
public class Main {
public static void main(String[] args) {
C obj = new C();
System.out.println("Value by using obj ref" + obj.VALUE); //confusion
}
}

--- by using static var in class multiple

class A {
public static int VALUE = 10;
}
class B{
public static int VALUE = 20;
}
class C extends A,B{ // this that first case
}
public class Main {
public static void main(String[] args) {
C obj = new C();
//System.out.println("Value by using obj ref" + obj.VALUE); //confusion
System.out.println("Static method from interface A: "+A.VALUE);//while working
with classes first case fails here

System.out.println("Static method from interface B: "+B.VALUE);//that case is


extends A,B

}
}

----some more with var

1.Classes with two Static var

class A {
static int VALUE = 10;
}

class B extends A {
static int VALUE = 20;
}

public class Main {


public static void main(String[] args) {

B objB = new B();


System.out.println("Value from objB as B reference: " + objB.VALUE);
System.out.println(" static VALUE from A : "+A.VALUE);
System.out.println("static VALUE from B : "+B.VALUE);

}
}

//O/P:
Value from objB as B reference: 20
static VALUE from A : 10
static VALUE from B : 20

2.Classes with two instance var

class A {
int value = 10;
}

class B extends A {
int value = 20;
}

public class Main {


public static void main(String[] args) {
B obj= new B();
System.out.println("Value from obj as B reference: " + obj.value);
}
}

O/P: Value from obj as B reference: "20

3.Interface with instance methods //but internally public static final

interface A {
int VALUE = 10;
}

interface B extends A {
int VALUE = 20;
}
class C implements B{

}
public class Main {
public static void main(String[] args) {
C objC = new C();
System.out.println("Value from objC as C reference: " + objC.VALUE);
System.out.println("Static method from interface A: "+A.VALUE);
System.out.println("Static method from interface B: "+B.VALUE);
}
}

O/P: Value from objC as C reference: 20


Static method from interface A: 10
Static method from interface B: 20

EX:IQ
interface IA {
void method1();
}
interface IB {
void method2();
}
class SubB implements IA, IB {
@Override
public void method1() {
System.out.println("Method1 from IA");
}

@Override
public void method2() {
System.out.println("Method2 from IB");
}
}
public class Main {
public static void main(String[] args) {
SubB s=new SubB();
s.method1();
s.method2();

IA ia = new SubB();
ia.method1(); // Valid: IA has method1()
//ia.method2(); // Compile-time error: IA doesn't have method2()

IB ib = new SubB();
ib.method2();// Valid: IB has method2()
//ib.method1(); // Compile-time error: IB doesn't have method1*/
}
}

Default Method In JDK1.8 Interfaces :


 Note: Upto JDK 1.7 the interface will have only abstract methods From
JDK1.8 onwards they added default methods in the interface
 Assume the an interface with one abstract method, Which is implemented
in the its subclass, by chance if we add any abstract methods in the
interface then it will leads an error at implementation classes.
 In order to provide Some new functionalities in the implemented classes
with out disturbing the implemented classes then they added new feature
is called “default methods in interfaces”

EX: for default method in java usage

interface IA {
void existingMethod();
default void newMethod()
{
System.out.println("Default method in interface IA");
}
}
class SubA implements IA {
@Override
public void existingMethod() {
System.out.println("Overridden existingMethod in SubA");
}
/*@Override
public void newMethod() {
System.out.println("Overridden default method in SubA");
}*/
}
class SubB extends SubA {
@Override
public void existingMethod() {
System.out.println("Overridden existingMethod in SubB");
}
/*@Override
public void newMethod() {
System.out.println("Overridden default method in SubB");
}*/
}
public class Main {
public static void main(String[] args) {
IA obj1 = new SubA(); // we can also give SubA s=new SubA();
obj1.existingMethod();
obj1.newMethod(); // Calls overridden version in SubA

IA obj2 = new SubB(); //we can also give SubB s=new SubB();
obj2.existingMethod();
obj2.newMethod(); // Calls overridden version in SubB
}
}

O/P:

Overridden existingMethod in SubA


Default method in interface IA
Overridden existingMethod in Sub
Default method in interface IA

//remove comment for SuperA


Overridden existingMethod in SubA
Overridden default method in SubA
Overridden existingMethod in SubB
Overridden default method in SubA

//remove comment for SubB also


Overridden existingMethod in SubA
Overridden default method in SubA
Overridden existingMethod in SubB
Overridden default method in SubB
JDK1.9 private methods in Interfaces:
 As we know that in JDK1.8 we have default methods in the interfaces,Some
times while developing the real time projects we may required same logic
for more than one default methods , Then that logic is recommended to
define inside of the private methods, we can use it for multiple times, Thus
we can avoid repetition of code , code optimization , memory optimization
and efficiency of the code will be increase.
 Private methods we can use only inside of that interface but  not outside
of the interfaces.
//we have to run this code in jdk 1.9 but iam having JDK 1.8 only then use online
compiler

EX: private method Example

interface IA {
default void method1() {
System.out.println("Executing method1...");
commonLogic();
}

default void method2() {


System.out.println("Executing method2...");
commonLogic();
}

private void commonLogic() {


System.out.println("Common logic executed by both method1 and method2.");
}
}

class SubA implements IA {


// if we want we can implent
}

public class Main {


public static void main(String[] args) {
IA obj = new SubA();
obj.method1(); // Calls method1, which uses commonLogic
obj.method2(); // Calls method2, which also uses commonLogic
}
}

//in online compiler

Executing method1...
Common logic executed by both method1 and method2.
Executing method2...
Common logic executed by both method1 and method2.
EX:IQ

interface IA {
void method1(); // public abstract
}
interface IB extends IA {
void method2();
}
class SubB implements IB {
@Override
public void method1() {
System.out.println("method1 of IA");
}

@Override
public void method2() {
System.out.println("method2 of IB");
}
}
class InterfaceDemo {
public static void main(String args[]) {
IA ia = new SubB();
ia.method1();
// ia.method2(); // CE (Compile-time error)

IB ib = new SubB();
ib.method2();
ib.method1();

SubB s=new SubB();


s.method1();
s.method2();
}
}

A class can be extends by a class


A class can’t be extended by more than one class
A class can be implemented by an interface
A class can be implemented by more than one interface
A class can be extends by class and can be implemented by one or more interface
but in this case extends to be used first

class A{ }
class B{ }
interface C{ }
interface E{ }
1.class D extends A{ } //valid
2.class D extends A,B{ } //invalid
3.class D extends A implements C{ } //valid
4.class D implements C extends A{ } // invalid
5.class D implements C extends A,B{ }//invalid
6.class D implements C,E extends A{ }//invalid
7.class D extends A implements C,E{ }//valid

Q: Why java doesn’t support to create an object for abstract class or an


interface ?
Ans : Just bcz abstract and interface will have abstract methods. Abstract
methods will not have body or implementation
 If we call abstract methods can do nothing that’s way abstract methods
 also known as do nothing method If any class is defined with abstract methods
then those classes are restricted to create an object for them.

Final Modifiers: is non access modifier

In c and c++ in order to make any variable value as constant then we have to
make use of “const” keyword

const int x=10;


x=x+10; //Error In Java there is not keyword “const”

rather we have to use “final”

 final int X=10;


X=X+10; //Error

EX: final modifier

class A{
final int VALUE = 100; // Declare final variable

void changeValue() {
// Attempting to modify the final variable
//VALUE = 200; // This line will cause a compilation error
}

public static void main(String[] args) {


A obj = new A();
System.out.println("Initial VALUE: " + obj.VALUE);
//obj.VALUE = 200;
obj.changeValue();
}
}

Final Methods :

if we define any method with final modifier then those methods are not
overridden ,but those are inherited.

EX:not overridden but inherited

class Parent {
final void display() {
System.out.println("This is a final method in the Parent class.");
}
}

class Child extends Parent {


// Attempt to override the final method

/*@Override
void display() {
System.out.println("Trying to override the final method in Child class.");
}*/

public class Main {


public static void main(String[] args) {
Child child = new Child();
child.display(); // Calls the inherited display() method from Parent
}
}

O/P:1
If you ovverride
Main.java:11: error: display() in Child cannot override display() in Parent
void display() {
^
overridden method is final
1 error

O/P:2 if you wont override

This is a final method in the Parent class.

Final Classes:
Defining a class with “final” modifier. Final classes are not inherited . but we can
create an Object and we access the members of the classes using object ref
possible .

final class FinalClass {


int number = 100;

void display() {
System.out.println("This is a method in a final class.");
}
}
class SubClass extends FinalClass {
// point 1:This will throw a compilation error because FinalClass is final
}
public class Main {
public static void main(String[] args) {
// Point 2: Creating an object of the final class and accessing its members
FinalClass obj = new FinalClass();
System.out.println("Number: " + obj.number); SSYSO mand
obj.display();
}
}

Main.java:10: error: cannot inherit from final FinalClass


class SubClass extends FinalClass {
^
1 error
Encapsulation in Java is the principle of wrapping data (variables) and methods
(functions) into a single unit (class) while restricting direct access to the data to
maintain control over it. This is achieved through access modifiers (private,
protected, public) and getter/setter methods to enforce controlled data access
and modification.

 outside of the class also we can access directly with out any restriction.(for
instance by using objref.varname).

 But in this encapsulation it is providing setter and getter methods to


manipulate data and restricting the direct access

Feature Normal Class Encapsulated Class


Data Access Direct access to variables. Variables are private, accessed via methods.
Data Security No data protection. Data is protected and controlled.
Anyone can change the data
Modification Data can only be modified through methods.
directly.
private String name; with getName() and
Example public String name;
setName().

EX: using var names directly outside of the class(no security)

class Customer {
int cID;
String cName;
long cNum;
public Customer(int cID, String cName, long cNum) {
this.cID = cID;
this.cName = cName;
this.cNum = cNum;
}
}
public class Main{
public static void main(String[] args) {
Customer c = new Customer(1, "Rohit", 9915245L);
/*c.cID=2; //update fileds directly
c.cName="venkatesh";
c.cNum=1233444;*/
System.out.println(c.cID); //acessing details outside out side of class
System.out.println(c.cName); //no security
System.out.println(c.cNum); //here we are using var names outside of the
class
}
}

EX:providing security by using encapsulation (private ,setter and getter):


instance methods are classified into 2 types
1.Mutable Methods > The methods which are used to change the values of the
fields are called mutable methods or setter
2.Immutable Methods > The methods which doesn’t change the value of the
fields or The methods which are used read the values from the fields called
immutable methods or getter methods or inspectors

EX: different var names in local and instance


class Customer {
private int cID;
private String cName;
private long cNum;
public void setData(int x, String y, long z) {
cID = x;
cName =y;
cNum = z;
}
public int getcID() {
return cID;
}
public String getcName() {
return cName;
}
public long getcNum() {
return cNum;
}
}
public class Main{
public static void main(String[] args) {
Customer c = new Customer();
c.setData(1, "Rohit", 9876534234L);
//c.setData(2, "venkatesh",1234567890);
System.out.println(c.getcID());
System.out.println(c.getcName());
System.out.println(c.getcNum());
}
}

EX:same var names for local and instance


class Customer {
private int cID;
private String cName;
private long cNum;
public void setData(int cID, String cName, long cNum) {
this.cID = cID;
this.cName = cName; //just remove this key here what is the output we will
get here
this.cNum = cNum; //0 null 0
}
public int getcID() {
return cID;
}
public String getcName() {
return cName;
}
public long getcNum() {
return cNum;
}
}
public class Main{
public static void main(String[] args) {
Customer c = new Customer();
c.setData(1, "Rohit", 9876534234L);
//c.setData(2, "venkatesh",1234567890);
System.out.println(c.getcID());
System.out.println(c.getcName());
System.out.println(c.getcNum());
}
}

Working with Packages


 Package is collection of types , Where type are referred as classes, Abstract
class ,interface and sub packages (OR) In simple words package is the
collection of .class files
o Advantages of packages :
Reusability of types
Providing Access restriction on the types using Access Modifiers [ private | default
| protected | public ]

Packages are classified into 2 types

1.Pre-defined packages: Packages which are provided by JAVA Compiler [JDK


software] java.lang | java.io | java.util …..

2.User defined Packages: The Packages which are defined by us for our
application requirements Also known as customized packages

Creating a package by using package keyword ;


<package><packagename>

Access Modifiers:

public protected Default private


Same class yes yes Yes yes
Same package yes yes Yes No
Sub class
Same package yes yes Yes No
Non sub class
Different package yes yes No No
Subclass
Different package yes No No No
Non sub class
A.JAVA
Same class

package package_1;
public class A {
private int a = 100;

public static void main(String[] args) {


A obj = new A();
System.out.println("Same Class : "+obj.a);
}

Same package

Sub class

package package_1;
public class B extends A{
public static void main(String[] args) {
B obj = new B();
System.out.println("Same Package Sub Class : "+obj.a);
}

Same package

Non Sub class

package package_1;
public class C {
public static void main(String[] args) {
A obj = new A();
System.out.println("Same Package non Sub Class : "+obj.a);
}
}

Different package

Sub class

package package_2;
import package_1.A;

public class D extends A{


public static void main(String[] args) {
D obj = new D();
System.out.println("different Package Sub Class : "+obj.a);
}
}

Same package

Non Sub class

package package_2;
import package_1.A;
public class E {
public static void main(String[] args) {
A obj = new A();
System.out.println("different Package Non Sub Class : "+obj.a);
}
}

Varargs
 Varargs is nothing but variable length arguments
 Varargs should be taken as formal parameter in method definition
 Varargs can take 0 arguments N.no.of arguments
 Varargs internally works a Single dimensional Array and It is dynamic
 If required we can also pass an array as an argument to the varargs
parameter
 With the help of varargs we can avoid defining methods overloading
whenever you want perform same operation for irrespective
no.of.argument of same type
 Varargs can be also takes along with other type of parameter but in this
case varargs should be last argument.

Method overloading:

class FindSum{
int sum(int a, int b) {
return a + b;
}
int sum(int a, int b, int c) {
return a + b + c;
}
}
class Main
{
public static void main(String[] args)
{
FindSum f=new FindSum();
int a=f.sum(10,20);
System.out.println("first overloaded method sum :"+a);
int b=f.sum(10,20,30);
System.out.println("second overloaded method sum :"+b);
}
}

EX:var args We can pass any no.of arguments(point we can pass array var too)

class FindSum{
int sum(int... x) {
int s = 0;
for (int i : x) {
s = s + i;
}
return s;
}
}
public class Main{
public static void main(String args[]) {
FindSum f = new FindSum();
int s = f.sum(10, 20);
System.out.println("Sum is : " + s);
s = f.sum(10, 20, 30);
System.out.println("Sum is : " + s);
int[] a = {10, 20, 30, 40};
s = f.sum(a);
System.out.println("Sum is : " + s);
}
}

EX:we can pass diff type of arguments in this case var args should be last(point)

class Student {
void findResult(String name, int... m) {
System.out.println("Name is : " + name);
System.out.println("Marks:");
int s = 0;
for (int i : m) {
System.out.println(i);
s = s + i;
}
System.out.println("------------------");
System.out.println("Total is : " + s);
System.out.println("======================");
}
}
public class Main{
public static void main(String args[]) {
Student s = new Student();
s.findResult("Manasa", 40, 50, 60);
s.findResult("Mamatha", 40, 50);
s.findResult("Cnu", 30);
s.findResult("Anu");
}
}

Command Line Arguments :


 It is the process of passing the values to the program by the time of
execution
 The values which we passing through command line those values will be 
stored in the “args* +” of main( )
 “args[ ]” is SDA and it is dynamic The size of “args* +” will be increased
based on the values which we are passing by the time of execution java
program
 We can pass N no.of arguments and any type of arguments but JVM treat
them as “String” Only
 We can pass N no.of arguments but each argument should be separated by
a space While passing strings recommended to have them into “ “ marks

EX:by default String

public class Main{


public static void main(String args[]) {
System.out.println("total cmd line args : " + args.length);
System.out.println("First : " + args[0]); //10
System.out.println("Second : " + args[1]); //20
System.out.println("First : " + (args[0]+args[1])); // 1020
System.out.println("third :"+args[2]); //Ravi

}
}

EX:2 -By using loops for N no of values


public class Main{
public static void main(String args[]) {
System.out.println("By using normal for loop");
for (int i = 0; i < args.length; i++) {
System.out.println(args[i]);
}
System.out.println("By using enhanced for loop");
for (String j : args) {
System.out.println(j);
}
}
}

EX: 3- We can’t convert string type values to any primitive type using ordinary
typecasting approach but we can achieve by using parsing methods from Wrapper
classes

public class Main{


public static void main(String args[]) {
int x = (int) args[0];
int y = (int) args[1];
int sum=x+y;
System.out.println(“the sum is: “+sum);
}
}

Main.java:3: error: incompatible types: String cannot be converted to int


int x = (int) args[0];
^
Main.java:4: error: incompatible types: String cannot be converted to int
int y = (int) args[1];
^
2 errors
EX:by using parsing methods

public class Main{


public static void main(String args[]) {
int x = Integer.parseInt(args[0]);
int y = Integer.parseInt(args[1]);
int s = x + y;
System.out.println("Sum is : " + s);
}
}

Named and Nameless Objects:


Named Object :
 Creating an Object using an Object reference is called named Object
 Whenever you want access any method of class and N. no.of. times then it
is recommended to created named Object
Nameless object
 is the process of creating an object of the class without using any reference
Nameless Object
 it is recommended whenever you want access only method of the class for
only one time

EX:

class Test {
void method1() {
System.out.println("Mtd-1 of Test");
}
void method2() {
System.out.println("Mtd-2 of Test");
}
}
public class Main {
public static void main(String args[]) {
Test t = new Test(); // Named Object
t.method1();
t.method2();
new Test().method1(); // Nameless object
new Test().method2();
}
}

String is from java.lang


StringTokenzier Class
 StringTokenizer is the predefined class from java.util package o It is used to
divide the String Object into tokens [small piece] at the specified delimiter
 Default delimiter is space
Constructor:
StringTokenizer(String):

 Eg:StringTokenizer st= new StringTokenizer(“welcome to java”);


 It will divide the given string into tokens at the default delimiter and those
token can manipulated from StringTokenizer
StringTokenizer(String data,String delimiter):
StringTokenizer st=new StringTokenizer(“welcome,to,java” , ”,”);

Methods: java.util.StringTokenizer

1.public int countTokens( ):


 It will return no.of.Tokens are existed in the StringTokenizer Collection

2.public boolean hasMoreTokens():


 It will returns true if the StringTokenizer collection has tokens otherwise it
will return false
3.public String nextToken():
 It will return next Token from the StringTokenizer Collection.
EX:String tockenizer with methods

import java.util.StringTokenizer;

class Main{
public static void main(String args[]) {
StringTokenizer st = new StringTokenizer("welcome to java programming");
int nt = st.countTokens();
System.out.println("No.of.Tokens are : " + nt);

while (st.hasMoreTokens()) {
String token = st.nextToken();
System.out.println(token.toUpperCase() + " .... " + token.length());
}
}
}

Exception Handling:

 Exception is a typically an “error” it will occur at the time of execution at


any point of time.
 If any exceptions are occur then normal flow of the program will get
disturbed and program will be terminated abnormally or unsuccessfully

Some possible reasons for the Exceptions are


 Invalid Number of Inputs
 Invalid Input types
 Any logical Error Occur

EX:invalid number of inputs

public class Main {


public static int add(int a, int b) {
return a + b;
}

public static void main(String[] args) {


System.out.println(add(5)); // Error: add(int, int) needs 2 arguments, but 1
was given
}
}

EX:invalid input types


public class Main {
public static int multiply(int a, int b) {
return a * b;
}

public static void main(String[] args) {


System.out.println(multiply(5, "hello")); // Error: incompatible types: String
cannot be converted to int
}
}

EX:logical error

public class Main {


public static int divide(int a, int b) {
return a / b; // This will throw ArithmeticException if b is 0
}

public static void main(String[] args) {


int result = divide(10, 0);

System.out.println("Result: " + result); // This line will not execute due to


exception
}
}

Benefits Of Handling Exceptions are :


1.Making the program to terminate Successfully
2.Separating Error Logic with Normal Logic

Default Exception handler is the JVM


 During Executing the Java Programs if at any where any thing goes wrong ,
then JVM will recognize the corresponding “ExceptionClassName” Based on
the context.
 It will print Exception Class Name , Description of the Exception
 StackTrace of the Exception [Name of class | method name | program
name and line number ] where the exception is got raised and finally
making the program to terminate abnormally or unsuccessfully.

Keywords Related to Handle the Exception:


 try | catch | throw | throws | finally
 in the try block is always recommended to write the lines which are
possible for only exceptions
 catch is the most immediate block to try.In the catch block is always
recommend to write the logic related to handle the Exception | Solutions of
the Exception
 During executing the statements of try block if at all any thing goes wrong ,
then JVM will recognize the corresponding Exception class name based on
the context. It will create an object of the corresponding “Exception Class”
and it will throw to the Exception handler
 The catch block the exception handler , it will receive the Exception class
object . Handle the Exception and finally making the program to terminate
successfully.
 Note: The argument of catch block should be same as the Object which
thrown by the catch block.

EX:Handling exception

import java.util.Scanner;
public class Main{
public static void main(String[] args){
Scanner scan = new Scanner(System.in);

try {
System.out.println("Enter the numerator");
int a = scan.nextInt();
System.out.println("Enter the denominator");
int b = scan.nextInt();
int c = a / b; // May throw ArithmeticException if b is 0

System.out.println("Result: " + c);


}
catch (ArithmeticException e) {
System.out.println("provide non-zero denominator");
}
}
}

Exceptions are classified into 2 types


1.Predefined Exceptions [Predefined Exception classes]
2.User defined Exceptions [Use defined Exception Classes]
All the Exceptions are the classes only
1.Pre-defined exceptions are the classes which are provided by JDK Software. All
the predefined Exceptions are well known the JVM thus JVM will take
responsibility in [raising the Exception] Based on the context
2.User defined Exception are the classes which are defined by us based on our
application requirements , User defined exceptions are unknown to the JVM thus
JVM doesn’t cares about invoking the user defined Exception, thus it is our
responsibility to raise that exception based the application required | context

EX:

import java.util.Scanner;

class Main{
public static void main(String args[]) {
Scanner s = new Scanner(System.in);
System.out.println("Enter 2 numbers ");
int x = s.nextInt();
int y = s.nextInt();

try {
int z = x / y;
System.out.println("Result is : " + z);
} catch (ArithmeticException a) {
System.out.println("Sorry V R N D By Zero ..");
System.out.println("Enter 2nd value ");
y = s.nextInt();
int z = x / y;
System.out.println("Result is : " + z);
}
}
}

3.“throw” : is keyword which can be used to raise the user defined exception.

Syn: throw new <Exception class name>([list of args]);

import java.util.Scanner;

class MyLoginException extends RuntimeException {


MyLoginException(String s) {
super(s);
}
}

class Main{
public static void main(String args[]) {
Scanner scanner = new Scanner(System.in);

System.out.print("Enter username: ");


String username = scanner.nextLine();

System.out.print("Enter password: ");


String password = scanner.nextLine();

if (username.equals("Rahul") && password.equals("Rahul@567")) {


System.out.println("Valid User ");
} else {
try {
throw new MyLoginException("Invalid UN|PW ");
}
catch (MyLoginException me) {
System.out.println("Sorry Unable to continue.....");
System.out.println("Reason : " + me);
}
}

scanner.close();
}
}
4.throws:

public class Example {

public static void mayThrowIOException() throws java.io.IOException {


java.io.FileReader file = new java.io.FileReader("nonexistentfile.txt");
}

public static void main(String[] args) {


try {
mayThrowIOException();
} catch (java.io.IOException e) {
System.out.println("Caught IOException: " + e.getMessage());
}
}
}

5.finally

import java.util.Scanner;

public class Main {


public static void main(String[] args) {
Scanner scan = new Scanner(System.in);

try {
System.out.println("Enter the numerator");
int a = scan.nextInt();
System.out.println("Enter the denominator");
int b = scan.nextInt();
int c = a / b;

System.out.println("Result: " + c);


}
finally {
System.out.println("This will always execute, regardless of exception.");
scan.close();
}
}
}

Multi-Threading:

 Thread is nothing but smallest part of the process


 Multi Threading is the process of executing more than one functionality of
the process simultaneously.
In-Order to achieve “Multi-Thread” in Java we have to Approaches By using

1.java.lang.Thread©
2.By using java.lang.Runnable(i)

java.lang.Thread
predefined constant variable of Thread class
public final static int NORM_PRIORITY (5)
public final static int MIN_PRIORITY (1)
public final static int MAX_PRIORITY (10)

Constructor: Thread() Eg: Thread t=new Thread();


 it is default constructor of Thread class.
 It will create a thread class object with their default names [ Thread-
0 | Thread-1 | Thread-2......

Thread(String):
Thread t=new Thread("Shashi");
 It will create thread object with specified name Thread(Runnable)
 Thread t=new Thread(st); > It is a copy constructor it will create thread
object by taking the properties of Runnable Interface Objec

Methods : java.lang.Thread

1. public void run( ):


 Whatever the logic you want execute as a thread then corrospoding
logic must be define in the "run()" of the Thread class
 run ( ) of Thread class should not be called explicitly rather "run( )" of
thread class will be executed "start( )" of java.lang.Thread

import java.lang.Thread;

class A extends Thread {


public void run() {
for (int i = 1; i <=5; i++) {
System.out.println("A ... : " + i);
}
}
}

class B extends Thread {

public void run() {


for (int i =10; i <= 15; i++) {
System.out.println("B ... : " + i);
}
}
}

class Main{
public static void main(String args[]) {
A a = new A();
B b = new B();
a.start();
b.start();

for (int i =20; i <=25; i++) {


System.out.println("Main ... : " + i);
}
}
}

Note : we should not call "run()" of Thread class .By chance if we call "run()" of
Thread then execution will be sequence.

import java.lang.Thread;

class A extends Thread {


public void run() {
for (int i = 1; i <= 5; i++) {
System.out.println("A ... : " + i);
}
}
}
class B extends Thread {
public void run() {
for (int i = 10; i <= 15; i++) {
System.out.println("B ... : " + i);
}
}
}
class Main {
public static void main(String args[]) {
A a = new A();
B b = new B();
// Calling run() directly, instead of start()
a.run();
b.run();
// Main thread's loop
for (int i = 20; i <= 25; i++) {
System.out.println("Main ... : " + i);
}
}
}

java.lang.Thread
1.public String getName(); - It will return name of the Thread Object
2. public void setName(String): - Used to Set the name of an existed Thread

import java.lang.Thread;
class Child extends Thread {
@Override
public void run() {
System.out.println("Child-Thread ...");
}
}
class Main{
public static void main(String args[]) {
Child c = new Child(); // Child <-- Thread Object
String tname = c.getName();
System.out.println("Thread Name is : " + tname);
c.setName("Child");
tname = c.getName();
System.out.println("Thread Name is : " + tname);
}
}

 Whenever we define any thread by default every thread is created with


“NORM_PRIORITY”.Thus we are not guarantee in execution order of
threads
 Based On Our Application requirements we can also set Priority of  thread
by using “
public void setPriority(int newPriority)”
 If you want get Priority of thread then we have use:
public int getPriority( )

import java.lang.Thread;

class A extends Thread {


@Override
public void run() {
// Thread A's logic can go here (if needed)
}
}

class B extends Thread {


@Override
public void run() {
// Thread B's logic can go here (if needed)
}
}

class Main{
public static void main(String args[]) {
A a = new A();
B b = new B();

int ap = a.getPriority(); // Default priority is 5


int bp = b.getPriority(); // Default priority is 5
System.out.println("Priority of A : " + ap);
System.out.println("Priority of B : " + bp);

Thread cwt = new Thread();


int mp = cwt.getPriority(); // Default priority of main thread is 5
System.out.println("Priority of Main : " + mp);

b.setPriority(Thread.MAX_PRIORITY); // Set B's priority to maximum (10)


bp = b.getPriority();
System.out.println("Priority of B after change: " + bp);
}
}

Note: the Thread which is having MAX_PRIORITY will be executed First. The
Thread Which is having MIN_PRIORITY then that thread will be executed at last
and the Threads which are having same priorities will be execute simultaneously.

Note: Based on our application requirements we can also delay the execution of
thread based on the particular period of type. Then we have to use the following
overloaded methods
//java.lang.Thread
//public static void sleep(long ms) ----throws InterruptedException
//public static void sleep(long ms,int ns)

import java.lang.Thread;

class A extends Thread {


@Override
public void run() {
try {
sleep(20000, 40);
}
catch (InterruptedException e) {
}
for (int i = 1; i <= 5; i++) {
System.out.println("A - Thread ... : " + i);
}
}
}
class Main{
public static void main(String args[]) {
A a = new A(); // Create an instance of A thread
a.start(); // Start the A thread

for (int i =10; i <= 15; i++) {


System.out.println("Main - Thread ... : " + i);
}
}
}

Note: Based the application requirements we also delay the execution of the
thread till another thread execution process is “completed”. Using “join()”

public void join( )


public void join(long ms)
public void join(long ms,int ns)

import java.lang.Thread;

class A extends Thread {


@Override
public void run() {
for (int i = 1; i <= 5; i++) {
try {
sleep(2000); // Sleep for 2 seconds
}
catch (InterruptedException j) {
}
System.out.println("A - Thread ... : " + i);
}
}
}
class Main{
public static void main(String args[]) throws InterruptedException {
A a = new A(); // Create an instance of thread A
a.start(); // Start thread A

a.join(); // Main thread will wait for thread A to finish before continuing
for (int i = 10; i <= 15; i++) { // Main thread prints numbers 20 to 30 after
A finishes
System.out.println("Main Thread ... : " + i);
}
}
}

What is synchronization ?

 It is the process of restrict more than one thread to perform the operations
on the same functionality simultaneously
 We can achieve thread safety by using “synchronized” keyword
 Advantages are avoiding data inconsistency
 Disadvantages are delaying the execution of the program

import java.lang.Thread;
class ATM {
// Synchronized method to handle withdrawals
public synchronized void wd(String s) {
for (int i = 1; i <= 5; i++) {
try {
Thread.sleep(1000); // Sleep for 1 second
} catch (InterruptedException ie) {
ie.printStackTrace();
}
System.out.println("WD by Mr|Mrs ... : " + s);
}
}
}
class Thread1 extends Thread {
ATM a;

Thread1(ATM a) {
this.a = a;
}

@Override
public void run() {
a.wd("Sai"); // Sai is withdrawing money
}
}
class Thread2 extends Thread {
ATM a;

Thread2(ATM a) {
this.a = a;
}
@Override
public void run() {
a.wd("Balu"); // Balu is withdrawing money
}
}

class Main{
public static void main(String args[]) {
ATM a = new ATM(); // Create ATM object
Thread1 t1 = new Thread1(a); // Create Thread1 (Sai)
Thread2 t2 = new Thread2(a); // Create Thread2 (Balu)

t1.start(); // Start Thread1 (Sai)


t2.start(); // Start Thread2 (Balu)
}
}

Example application using java.lang.Runnable(i)


 Runnable(i) predefined interface to achieve multi-threading
 While working multi-Threading then we must override “public abstract
void run() of Runnable interface

import java.lang.Runnable;
import java.lang.Thread;

class A implements Runnable {


@Override
public void run() {
for (int i = 1; i <= 5; i++) {
System.out.println("A - Thread ... " + i);
}
}
}

class Main{
public static void main(String args[]) {
A a = new A(); // Create an instance of A (Runnable)
Thread t = new Thread(a); // Create a new Thread with A as the Runnable target
t.start(); // Start the A thread

for (int i =10; i <=15; i++) { // Main thread prints numbers from 20 to 30
System.out.println("Main-Thread ... " + i);
}
}
}

You might also like