SlideShare a Scribd company logo
Java & JEE Training
Session 8 – OOP with Java Contd.
Page 1Classification: Restricted
Review of last session…
• Object Oriented Concepts
• Introduction to OO Analysis and Design
Page 2Classification: Restricted
Agenda…
• Deep dive into coding OOP with Java… with practical examples.
• How to create a class
• How to create objects
• How to create instance variables
• How to create class variables
• Constructors
Java & JEE Training
Object Oriented Programming with Java
- Basic Class Demo
Page 4Classification: Restricted
Naming Conventions
Name Convention
class name should start with uppercase letter and be a noun e.g.
String, Color, Button, System, Thread etc.
interface name should start with uppercase letter and be an adjective
e.g. Runnable, Remote, ActionListener etc.
method name should start with lowercase letter and be a verb e.g.
actionPerformed(), main(), print(), println() etc.
variable name should start with lowercase letter e.g. firstName,
orderNumber etc.
package name should be in lowercase letter e.g. java, lang, sql, util
etc.
constants name should be in uppercase letter. e.g. RED, YELLOW,
MAX_PRIORITY etc.
Page 5Classification: Restricted
Object and Class in Java - Demo
A basic example of a class:
class Student1{
int id;//data member (also instance variable)
String name;//data member(also instance variable)
public static void main(String args[]){
Student1 s1=new Student1();//creating an object of Student
System.out.println(s1.id);
System.out.println(s1.name);
}
}
Page 6Classification: Restricted
Another Example of Objects and Classes in Java
class Student2{
int rollno;
String name;
void insertRecord(int r, String n){ //method
rollno=r;
name=n;
}
void displayInformation(){System.out.println(rollno+" "+name);}//method
public static void main(String args[]){
Student2 s1=new Student2();
Student2 s2=new Student2();
s1.insertRecord(111,"Karan");
s2.insertRecord(222,"Aryan");
s1.displayInformation();
s2.displayInformation();
}
}
Page 7Classification: Restricted
Memory Allocation
Java & JEE Training
Method Overloading
Page 9Classification: Restricted
Method Overloading
• If a class have multiple methods by same name but different parameters.
• Advantage: Increases readability of the program.
• Two ways:
oBy changing number of arguments
oBy changing the data type
Page 10Classification: Restricted
Method Overloading: Changing number of arguments
class Calculation{
void sum(int a,int b){System.out.println(a+b);}
void sum(int a,int b,int c){System.out.println(a+b+c);}
public static void main(String args[]){
Calculation obj=new Calculation();
obj.sum(10,10,10);
obj.sum(20,20);
}
}
Page 11Classification: Restricted
Method overloading: Changing data type of argument
class Calculation2{
void sum(int a,int b){System.out.println(a+b);}
void sum(double a,double b){System.out.println(a+b);}
public static void main(String args[]){
Calculation2 obj=new Calculation2();
obj.sum(10.5,10.5);
obj.sum(20,20);
}
}
Page 12Classification: Restricted
Method overloading: Can it be done by
changing return type of methods?
class Calculation3{
int sum(int a,int b){System.out.println(a+b);}
double sum(int a,int b){System.out.println(a+b);}
public static void main(String args[]){
Calculation3 obj=new Calculation3();
int result=obj.sum(20,20);
/* Compile Time Error; Here how can java determine which
sum() method should be called */
}
}
//
Page 13Classification: Restricted
Method Overloading: Can we overload main() method?
class Overloading1{
public static void main(int a){
System.out.println(a);
}
public static void main(String args[]){
System.out.println("main() method invoked");
main(10);
}
}
Page 14Classification: Restricted
Method Overloading and Type Promotion
One type is promoted to another implicitly if no matching datatype is found
class OverloadingCalculation1{
void sum(int a,long b){System.out.println(a+b);}
void sum(int a,int b,int c){System.out.println(a+b+c);}
public static void main(String args[]){
OverloadingCalculation1 obj=new OverloadingCalculation1();
obj.sum(20,20);//now second int literal will be promoted to long
obj.sum(20,20,20);
}
}
Page 15Classification: Restricted
Method overloading: Ambiguous code
class OverloadingCalculation3{
void sum(int a,long b){System.out.println("a method invoked");}
void sum(long a,int b){System.out.println("b method invoked");}
public static void main(String args[]){
OverloadingCalculation3 obj=new OverloadingCalculation3();
obj.sum(20,20);//now ambiguity; Compile time error.
}
}
Page 16Classification: Restricted
Constructors
• Constructor in java is a special type of method that is used to initialize the
object.
• Java constructor is invoked at the time of object creation.
• Two rules:
oConstructor name must be same as its class name
oConstructor must have no explicit return type
oIf there is no constructor in a class, compiler automatically creates a
default constructor.
Java & JEE Training
Constructors
Page 18Classification: Restricted
Example of default constructor that displays the default values
class Student3{
int id;
String name;
void display(){
System.out.println(id+" "+name);
}
public static void main(String args[]){
Student3 s1=new Student3();
Student3 s2=new Student3();
s1.display();
s2.display();
}
}
Page 19Classification: Restricted
Example of parameterized constructor
class Student4{
int id;
String name;
Student4(int i,String n){ //Paremeterized Constructor
id = i;
name = n;
}
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
Student4 s1 = new Student4(111,"Karan");
Student4 s2 = new Student4(222,"Aryan");
s1.display();
s2.display();
}
}
Page 20Classification: Restricted
Example of Constructor Overloading
class Student5{
int id;
String name;
int age;
Student5(int i,String n){
id = i;
name = n;
}
Student5(int i,String n,int a){
id = i;
name = n;
age=a;
}
void display(){System.out.println(id+" "+name+" "+age);}
public static void main(String args[]){
Student5 s1 = new Student5(111,"Karan");
Student5 s2 = new Student5(222,"Aryan",25);
s1.display();
s2.display();
}
}
Page 21Classification: Restricted
Constructor vs Method
Java Constructor Java Method
Constructor is used to initialize the
state of an object.
Method is used to expose behaviour
of an object.
Constructor must not have return
type.
Method must have return type.
Constructor is invoked implicitly. Method is invoked explicitly.
The java compiler provides a default
constructor if you don't have any
constructor.
Method is not provided by compiler
in any case.
Constructor name must be same as
the class name.
Method name may or may not be
same as class name.
Page 22Classification: Restricted
Constructor Example: Used for cloning
class Student6{
int id;
String name;
Student6(int i, String n){
id = i;
name = n;
}
Student6(Student6 s){
id = s.id;
name =s.name;
}
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
Student6 s1 = new Student6(111,"Karan");
Student6 s2 = new Student6(s1);
s1.display();
s2.display();
}
}
Page 23Classification: Restricted
Point to ponder…
Does constructor return any value?
Java & JEE Training
”Static”
Page 25Classification: Restricted
Java “Static”
• The static keyword in java is used for memory management mainly.
• We can apply java static keyword with variables, methods, blocks and
nested class.
• The static keyword belongs to the class than instance of the class.
• The static can be:
ovariable (also known as class variable)
omethod (also known as class method)
oblock
onested class
Page 26Classification: Restricted
Java Static Variable
• If you declare any variable as static, it is known static variable.
• The static variable can be used to refer the common property of all objects
(that is not unique for each object) e.g. company name of employees,
college name of students etc.
• The static variable gets memory only once in class area at the time of class
loading.
• Advantage:
It makes your program memory efficient
Page 27Classification: Restricted
Example: Problem without static variable
class Student{
int rollno;
String name;
String college="ITS";
}
Page 28Classification: Restricted
Example: Static Variable solution
class Student8{
int rollno;
String name;
static String college ="ITS";
Student8(int r,String n){
rollno = r;
name = n;
}
void display (){System.out.println(rollno+" "+name+" "+college);}
public static void main(String args[]){
Student8 s1 = new Student8(111,"Karan");
Student8 s2 = new Student8(222,"Aryan");
s1.display();
s2.display();
}
}
Page 29Classification: Restricted
Static Variable Memory Allocation
Page 30Classification: Restricted
Example: Counter with static variable
class Counter2{
static int count=0;//will get memory only once and retain its value
Counter2(){
count++;
System.out.println(count);
}
public static void main(String args[]){
Counter2 c1=new Counter2();
Counter2 c2=new Counter2();
Counter2 c3=new Counter2();
}
}
Page 31Classification: Restricted
Java Static Method
• A static method belongs to the class rather than object of a class.
• A static method can be invoked without the need for creating an instance
of a class.
• static method can access static data member and can change the value of
it.
• There are two main restrictions for the static method. They are:
oThe static method can not use non static data member or call non-static
method directly.
othis and super cannot be used in static context.
Page 32Classification: Restricted
Static Method Example
class Student9{
int rollno;
String name;
static String college = "ITS";
static void change(){
college = "BBDIT";
}
Student9(int r, String n){
rollno = r;
name = n;
}
void display (){System.out.println(rollno+" "+name+" "+college);}
public static void main(String args[]){
Student9.change();
Student9 s1 = new Student9 (111,"Karan");
Student9 s2 = new Student9 (222,"Aryan");
Student9 s3 = new Student9 (333,"Sonoo");
s1.display();
s2.display();
s3.display();
}
}
Page 33Classification: Restricted
Example of static method that performs normal calculation
//Program to get cube of a given number by static method
class Calculate{
static int cube(int x){
return x*x*x;
}
public static void main(String args[]){
int result=Calculate.cube(5);
System.out.println(result);
}
}
Page 34Classification: Restricted
What is the output?
class A{
int a=40;//non static
public static void main(String args[]){
System.out.println(a);
}
}
Page 35Classification: Restricted
Point to ponder
• Why is main() method static?
Page 36Classification: Restricted
Java Static Block
• Is used to initialize the static data member.
• It is executed before main method at the time of classloading.
class A2{
static{System.out.println("static block is invoked");}
public static void main(String args[]){
System.out.println("Hello main");
}
}
Page 37Classification: Restricted
“this” keyword
• In java, this is a reference variable that refers to the current object.
• Uses:
• this keyword can be used to refer current class instance variable.
• this() can be used to invoke current class constructor.
• this keyword can be used to invoke current class method (implicitly)
• this can be passed as an argument in the method call.
• this can be passed as argument in the constructor call.
• this keyword can also be used to return the current class instance.
Page 38Classification: Restricted
What’s the problem with the below code?
class Student10{
int id;
String name;
Student10(int id,String name){
id = id;
name = name;
}
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
Student10 s1 = new Student10(111,"Karan");
Student10 s2 = new Student10(321,"Aryan");
s1.display();
s2.display();
}
}
Page 39Classification: Restricted
Solution:
//example of this keyword
class Student11{
int id;
String name;
Student11(int id,String name){
this.id = id;
this.name = name;
}
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
Student11 s1 = new Student11(111,"Karan");
Student11 s2 = new Student11(222,"Aryan");
s1.display();
s2.display();
}
}
Note: If local variables(formal arguments) and instance variables are different, there is no need to use this
keyword like in the following program:
Page 40Classification: Restricted
this() for invoking current class constructor: Constructor Chaining
//Program of this() constructor call (constructor chaining)
class Student13{
int id;
String name;
Student13(){System.out.println("default constructor is invoked");}
Student13(int id,String name){
this ();//it is used to invoked current class constructor.
this.id = id;
this.name = name;
}
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
Student13 e1 = new Student13(111,"karan");
Student13 e2 = new Student13(222,"Aryan");
e1.display();
e2.display();
}
}
Rule: Call to this() must be the first statement in constructor.
Page 41Classification: Restricted
this keyword can be used to invoke current class method (explicitly)
class S{
void m(){
System.out.println("method is invoked");
}
void n(){
this.m();//no need because compiler does it for you.
}
void p(){
n();//complier will add this to invoke n() method as this.n()
}
public static void main(String args[]){
S s1 = new S();
s1.p();
}
}
Page 42Classification: Restricted
this keyword can be passed as an argument in the method
class S2{
void m(S2 obj){
System.out.println("method is invoked");
}
void p(){
m(this);
}
public static void main(String args[]){
S2 s1 = new S2();
s1.p();
}
}
Page 43Classification: Restricted
What is the output? What does the below code do?
class A5{
void m(){
System.out.println(this);//prints same reference ID
}
public static void main(String args[]){
A5 obj=new A5();
System.out.println(obj);//prints the reference ID
obj.m();
}
}
Page 44Classification: Restricted
Topics to be covered in next session
• Review of last class concepts
• Types of Inheritance and a look at Aggregation
• Polymorphism
• Method overloading
• Method overriding
Page 45Classification: Restricted
Thank you!

More Related Content

PPTX
Session 09 - OOP with Java - Part 3
PPTX
Session 10 - OOP with Java - Abstract Classes and Interfaces
PPSX
OOP with Java - Abstract Classes and Interfaces
PPSX
Exception Handling - Continued
PPSX
OOP with Java - Continued
PPTX
Session 11 - OOP's with Java - Packaging and Access Modifiers
PPSX
Elements of Java Language - Continued
PPSX
Inner Classes
Session 09 - OOP with Java - Part 3
Session 10 - OOP with Java - Abstract Classes and Interfaces
OOP with Java - Abstract Classes and Interfaces
Exception Handling - Continued
OOP with Java - Continued
Session 11 - OOP's with Java - Packaging and Access Modifiers
Elements of Java Language - Continued
Inner Classes

What's hot (20)

PPSX
Arrays in Java
PPSX
Exception Handling - Part 1
PPSX
OOP with Java - Part 3
PPSX
Collections - Sorting, Comparing Basics
PPTX
Statics in java | Constructors | Exceptions in Java | String in java| class 3
PPTX
04. Review OOP with Java
PPTX
Session 05 - Strings in Java
PPTX
OOP with Java - continued
PDF
Java Programming - 04 object oriented in java
PPTX
Session 16 - Collections - Sorting, Comparing Basics
PPT
Java Programming - Polymorphism
PDF
Java Programming - 05 access control in java
PDF
Java OOP Programming language (Part 3) - Class and Object
PDF
Java OOP Programming language (Part 5) - Inheritance
PDF
Java OO Revisited
PPT
Objected-Oriented Programming with Java
PPTX
Collection Framework in Java | Generics | Input-Output in Java | Serializatio...
PPTX
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
PPT
core java
Arrays in Java
Exception Handling - Part 1
OOP with Java - Part 3
Collections - Sorting, Comparing Basics
Statics in java | Constructors | Exceptions in Java | String in java| class 3
04. Review OOP with Java
Session 05 - Strings in Java
OOP with Java - continued
Java Programming - 04 object oriented in java
Session 16 - Collections - Sorting, Comparing Basics
Java Programming - Polymorphism
Java Programming - 05 access control in java
Java OOP Programming language (Part 3) - Class and Object
Java OOP Programming language (Part 5) - Inheritance
Java OO Revisited
Objected-Oriented Programming with Java
Collection Framework in Java | Generics | Input-Output in Java | Serializatio...
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
core java
Ad

Similar to Session 08 - OOP with Java - continued (20)

PPTX
Static keyword ppt
PPTX
constructors.pptx
PPTX
Static keyword.pptx
PPT
Object Oriented Programming with Java
PPT
Oop java
PDF
OOPs Concepts - Android Programming
PPTX
Java Foundations: Objects and Classes
PPTX
11. Java Objects and classes
PPTX
05 Object Oriented Concept Presentation.pptx
PPT
Oop objects_classes
PPTX
6. static keyword
PPTX
Java Programs
PPT
Defining classes-and-objects-1.0
PDF
The Ring programming language version 1.8 book - Part 39 of 202
PPT
classes & objects.ppt
PDF
11.Object Oriented Programming.pdf
PPSX
Java session5
PPTX
Classes-and-Object.pptx
PPT
14. Defining Classes
Static keyword ppt
constructors.pptx
Static keyword.pptx
Object Oriented Programming with Java
Oop java
OOPs Concepts - Android Programming
Java Foundations: Objects and Classes
11. Java Objects and classes
05 Object Oriented Concept Presentation.pptx
Oop objects_classes
6. static keyword
Java Programs
Defining classes-and-objects-1.0
The Ring programming language version 1.8 book - Part 39 of 202
classes & objects.ppt
11.Object Oriented Programming.pdf
Java session5
Classes-and-Object.pptx
14. Defining Classes
Ad

More from PawanMM (20)

PPTX
Session 48 - JS, JSON and AJAX
PPTX
Session 46 - Spring - Part 4 - Spring MVC
PPTX
Session 45 - Spring - Part 3 - AOP
PPTX
Session 44 - Spring - Part 2 - Autowiring, Annotations, Java based Configuration
PPTX
Session 43 - Spring - Part 1 - IoC DI Beans
PPTX
Session 42 - Struts 2 Hibernate Integration
PPTX
Session 41 - Struts 2 Introduction
PPTX
Session 40 - Hibernate - Part 2
PPTX
Session 39 - Hibernate - Part 1
PPTX
Session 38 - Core Java (New Features) - Part 1
PPTX
Session 37 - JSP - Part 2 (final)
PPTX
Session 36 - JSP - Part 1
PPTX
Session 35 - Design Patterns
PPTX
Session 34 - JDBC Best Practices, Introduction to Design Patterns
PPTX
Session 33 - Session Management using other Techniques
PPTX
Session 32 - Session Management using Cookies
PPTX
Session 31 - Session Management, Best Practices, Design Patterns in Web Apps
PPTX
Session 30 - Servlets - Part 6
PPTX
Session 29 - Servlets - Part 5
PPTX
Session 28 - Servlets - Part 4
Session 48 - JS, JSON and AJAX
Session 46 - Spring - Part 4 - Spring MVC
Session 45 - Spring - Part 3 - AOP
Session 44 - Spring - Part 2 - Autowiring, Annotations, Java based Configuration
Session 43 - Spring - Part 1 - IoC DI Beans
Session 42 - Struts 2 Hibernate Integration
Session 41 - Struts 2 Introduction
Session 40 - Hibernate - Part 2
Session 39 - Hibernate - Part 1
Session 38 - Core Java (New Features) - Part 1
Session 37 - JSP - Part 2 (final)
Session 36 - JSP - Part 1
Session 35 - Design Patterns
Session 34 - JDBC Best Practices, Introduction to Design Patterns
Session 33 - Session Management using other Techniques
Session 32 - Session Management using Cookies
Session 31 - Session Management, Best Practices, Design Patterns in Web Apps
Session 30 - Servlets - Part 6
Session 29 - Servlets - Part 5
Session 28 - Servlets - Part 4

Recently uploaded (20)

PPTX
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
PDF
Review of recent advances in non-invasive hemoglobin estimation
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PPTX
Understanding_Digital_Forensics_Presentation.pptx
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PPTX
breach-and-attack-simulation-cybersecurity-india-chennai-defenderrabbit-2025....
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PDF
Empathic Computing: Creating Shared Understanding
PDF
Advanced IT Governance
PDF
Advanced Soft Computing BINUS July 2025.pdf
PDF
madgavkar20181017ppt McKinsey Presentation.pdf
PDF
Electronic commerce courselecture one. Pdf
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PPTX
Cloud computing and distributed systems.
PDF
CIFDAQ's Market Insight: SEC Turns Pro Crypto
PPTX
MYSQL Presentation for SQL database connectivity
PDF
cuic standard and advanced reporting.pdf
PDF
Chapter 2 Digital Image Fundamentals.pdf
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
Review of recent advances in non-invasive hemoglobin estimation
Chapter 3 Spatial Domain Image Processing.pdf
Understanding_Digital_Forensics_Presentation.pptx
20250228 LYD VKU AI Blended-Learning.pptx
breach-and-attack-simulation-cybersecurity-india-chennai-defenderrabbit-2025....
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
Empathic Computing: Creating Shared Understanding
Advanced IT Governance
Advanced Soft Computing BINUS July 2025.pdf
madgavkar20181017ppt McKinsey Presentation.pdf
Electronic commerce courselecture one. Pdf
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
Cloud computing and distributed systems.
CIFDAQ's Market Insight: SEC Turns Pro Crypto
MYSQL Presentation for SQL database connectivity
cuic standard and advanced reporting.pdf
Chapter 2 Digital Image Fundamentals.pdf
Diabetes mellitus diagnosis method based random forest with bat algorithm
Advanced methodologies resolving dimensionality complications for autism neur...

Session 08 - OOP with Java - continued

  • 1. Java & JEE Training Session 8 – OOP with Java Contd.
  • 2. Page 1Classification: Restricted Review of last session… • Object Oriented Concepts • Introduction to OO Analysis and Design
  • 3. Page 2Classification: Restricted Agenda… • Deep dive into coding OOP with Java… with practical examples. • How to create a class • How to create objects • How to create instance variables • How to create class variables • Constructors
  • 4. Java & JEE Training Object Oriented Programming with Java - Basic Class Demo
  • 5. Page 4Classification: Restricted Naming Conventions Name Convention class name should start with uppercase letter and be a noun e.g. String, Color, Button, System, Thread etc. interface name should start with uppercase letter and be an adjective e.g. Runnable, Remote, ActionListener etc. method name should start with lowercase letter and be a verb e.g. actionPerformed(), main(), print(), println() etc. variable name should start with lowercase letter e.g. firstName, orderNumber etc. package name should be in lowercase letter e.g. java, lang, sql, util etc. constants name should be in uppercase letter. e.g. RED, YELLOW, MAX_PRIORITY etc.
  • 6. Page 5Classification: Restricted Object and Class in Java - Demo A basic example of a class: class Student1{ int id;//data member (also instance variable) String name;//data member(also instance variable) public static void main(String args[]){ Student1 s1=new Student1();//creating an object of Student System.out.println(s1.id); System.out.println(s1.name); } }
  • 7. Page 6Classification: Restricted Another Example of Objects and Classes in Java class Student2{ int rollno; String name; void insertRecord(int r, String n){ //method rollno=r; name=n; } void displayInformation(){System.out.println(rollno+" "+name);}//method public static void main(String args[]){ Student2 s1=new Student2(); Student2 s2=new Student2(); s1.insertRecord(111,"Karan"); s2.insertRecord(222,"Aryan"); s1.displayInformation(); s2.displayInformation(); } }
  • 9. Java & JEE Training Method Overloading
  • 10. Page 9Classification: Restricted Method Overloading • If a class have multiple methods by same name but different parameters. • Advantage: Increases readability of the program. • Two ways: oBy changing number of arguments oBy changing the data type
  • 11. Page 10Classification: Restricted Method Overloading: Changing number of arguments class Calculation{ void sum(int a,int b){System.out.println(a+b);} void sum(int a,int b,int c){System.out.println(a+b+c);} public static void main(String args[]){ Calculation obj=new Calculation(); obj.sum(10,10,10); obj.sum(20,20); } }
  • 12. Page 11Classification: Restricted Method overloading: Changing data type of argument class Calculation2{ void sum(int a,int b){System.out.println(a+b);} void sum(double a,double b){System.out.println(a+b);} public static void main(String args[]){ Calculation2 obj=new Calculation2(); obj.sum(10.5,10.5); obj.sum(20,20); } }
  • 13. Page 12Classification: Restricted Method overloading: Can it be done by changing return type of methods? class Calculation3{ int sum(int a,int b){System.out.println(a+b);} double sum(int a,int b){System.out.println(a+b);} public static void main(String args[]){ Calculation3 obj=new Calculation3(); int result=obj.sum(20,20); /* Compile Time Error; Here how can java determine which sum() method should be called */ } } //
  • 14. Page 13Classification: Restricted Method Overloading: Can we overload main() method? class Overloading1{ public static void main(int a){ System.out.println(a); } public static void main(String args[]){ System.out.println("main() method invoked"); main(10); } }
  • 15. Page 14Classification: Restricted Method Overloading and Type Promotion One type is promoted to another implicitly if no matching datatype is found class OverloadingCalculation1{ void sum(int a,long b){System.out.println(a+b);} void sum(int a,int b,int c){System.out.println(a+b+c);} public static void main(String args[]){ OverloadingCalculation1 obj=new OverloadingCalculation1(); obj.sum(20,20);//now second int literal will be promoted to long obj.sum(20,20,20); } }
  • 16. Page 15Classification: Restricted Method overloading: Ambiguous code class OverloadingCalculation3{ void sum(int a,long b){System.out.println("a method invoked");} void sum(long a,int b){System.out.println("b method invoked");} public static void main(String args[]){ OverloadingCalculation3 obj=new OverloadingCalculation3(); obj.sum(20,20);//now ambiguity; Compile time error. } }
  • 17. Page 16Classification: Restricted Constructors • Constructor in java is a special type of method that is used to initialize the object. • Java constructor is invoked at the time of object creation. • Two rules: oConstructor name must be same as its class name oConstructor must have no explicit return type oIf there is no constructor in a class, compiler automatically creates a default constructor.
  • 18. Java & JEE Training Constructors
  • 19. Page 18Classification: Restricted Example of default constructor that displays the default values class Student3{ int id; String name; void display(){ System.out.println(id+" "+name); } public static void main(String args[]){ Student3 s1=new Student3(); Student3 s2=new Student3(); s1.display(); s2.display(); } }
  • 20. Page 19Classification: Restricted Example of parameterized constructor class Student4{ int id; String name; Student4(int i,String n){ //Paremeterized Constructor id = i; name = n; } void display(){System.out.println(id+" "+name);} public static void main(String args[]){ Student4 s1 = new Student4(111,"Karan"); Student4 s2 = new Student4(222,"Aryan"); s1.display(); s2.display(); } }
  • 21. Page 20Classification: Restricted Example of Constructor Overloading class Student5{ int id; String name; int age; Student5(int i,String n){ id = i; name = n; } Student5(int i,String n,int a){ id = i; name = n; age=a; } void display(){System.out.println(id+" "+name+" "+age);} public static void main(String args[]){ Student5 s1 = new Student5(111,"Karan"); Student5 s2 = new Student5(222,"Aryan",25); s1.display(); s2.display(); } }
  • 22. Page 21Classification: Restricted Constructor vs Method Java Constructor Java Method Constructor is used to initialize the state of an object. Method is used to expose behaviour of an object. Constructor must not have return type. Method must have return type. Constructor is invoked implicitly. Method is invoked explicitly. The java compiler provides a default constructor if you don't have any constructor. Method is not provided by compiler in any case. Constructor name must be same as the class name. Method name may or may not be same as class name.
  • 23. Page 22Classification: Restricted Constructor Example: Used for cloning class Student6{ int id; String name; Student6(int i, String n){ id = i; name = n; } Student6(Student6 s){ id = s.id; name =s.name; } void display(){System.out.println(id+" "+name);} public static void main(String args[]){ Student6 s1 = new Student6(111,"Karan"); Student6 s2 = new Student6(s1); s1.display(); s2.display(); } }
  • 24. Page 23Classification: Restricted Point to ponder… Does constructor return any value?
  • 25. Java & JEE Training ”Static”
  • 26. Page 25Classification: Restricted Java “Static” • The static keyword in java is used for memory management mainly. • We can apply java static keyword with variables, methods, blocks and nested class. • The static keyword belongs to the class than instance of the class. • The static can be: ovariable (also known as class variable) omethod (also known as class method) oblock onested class
  • 27. Page 26Classification: Restricted Java Static Variable • If you declare any variable as static, it is known static variable. • The static variable can be used to refer the common property of all objects (that is not unique for each object) e.g. company name of employees, college name of students etc. • The static variable gets memory only once in class area at the time of class loading. • Advantage: It makes your program memory efficient
  • 28. Page 27Classification: Restricted Example: Problem without static variable class Student{ int rollno; String name; String college="ITS"; }
  • 29. Page 28Classification: Restricted Example: Static Variable solution class Student8{ int rollno; String name; static String college ="ITS"; Student8(int r,String n){ rollno = r; name = n; } void display (){System.out.println(rollno+" "+name+" "+college);} public static void main(String args[]){ Student8 s1 = new Student8(111,"Karan"); Student8 s2 = new Student8(222,"Aryan"); s1.display(); s2.display(); } }
  • 30. Page 29Classification: Restricted Static Variable Memory Allocation
  • 31. Page 30Classification: Restricted Example: Counter with static variable class Counter2{ static int count=0;//will get memory only once and retain its value Counter2(){ count++; System.out.println(count); } public static void main(String args[]){ Counter2 c1=new Counter2(); Counter2 c2=new Counter2(); Counter2 c3=new Counter2(); } }
  • 32. Page 31Classification: Restricted Java Static Method • A static method belongs to the class rather than object of a class. • A static method can be invoked without the need for creating an instance of a class. • static method can access static data member and can change the value of it. • There are two main restrictions for the static method. They are: oThe static method can not use non static data member or call non-static method directly. othis and super cannot be used in static context.
  • 33. Page 32Classification: Restricted Static Method Example class Student9{ int rollno; String name; static String college = "ITS"; static void change(){ college = "BBDIT"; } Student9(int r, String n){ rollno = r; name = n; } void display (){System.out.println(rollno+" "+name+" "+college);} public static void main(String args[]){ Student9.change(); Student9 s1 = new Student9 (111,"Karan"); Student9 s2 = new Student9 (222,"Aryan"); Student9 s3 = new Student9 (333,"Sonoo"); s1.display(); s2.display(); s3.display(); } }
  • 34. Page 33Classification: Restricted Example of static method that performs normal calculation //Program to get cube of a given number by static method class Calculate{ static int cube(int x){ return x*x*x; } public static void main(String args[]){ int result=Calculate.cube(5); System.out.println(result); } }
  • 35. Page 34Classification: Restricted What is the output? class A{ int a=40;//non static public static void main(String args[]){ System.out.println(a); } }
  • 36. Page 35Classification: Restricted Point to ponder • Why is main() method static?
  • 37. Page 36Classification: Restricted Java Static Block • Is used to initialize the static data member. • It is executed before main method at the time of classloading. class A2{ static{System.out.println("static block is invoked");} public static void main(String args[]){ System.out.println("Hello main"); } }
  • 38. Page 37Classification: Restricted “this” keyword • In java, this is a reference variable that refers to the current object. • Uses: • this keyword can be used to refer current class instance variable. • this() can be used to invoke current class constructor. • this keyword can be used to invoke current class method (implicitly) • this can be passed as an argument in the method call. • this can be passed as argument in the constructor call. • this keyword can also be used to return the current class instance.
  • 39. Page 38Classification: Restricted What’s the problem with the below code? class Student10{ int id; String name; Student10(int id,String name){ id = id; name = name; } void display(){System.out.println(id+" "+name);} public static void main(String args[]){ Student10 s1 = new Student10(111,"Karan"); Student10 s2 = new Student10(321,"Aryan"); s1.display(); s2.display(); } }
  • 40. Page 39Classification: Restricted Solution: //example of this keyword class Student11{ int id; String name; Student11(int id,String name){ this.id = id; this.name = name; } void display(){System.out.println(id+" "+name);} public static void main(String args[]){ Student11 s1 = new Student11(111,"Karan"); Student11 s2 = new Student11(222,"Aryan"); s1.display(); s2.display(); } } Note: If local variables(formal arguments) and instance variables are different, there is no need to use this keyword like in the following program:
  • 41. Page 40Classification: Restricted this() for invoking current class constructor: Constructor Chaining //Program of this() constructor call (constructor chaining) class Student13{ int id; String name; Student13(){System.out.println("default constructor is invoked");} Student13(int id,String name){ this ();//it is used to invoked current class constructor. this.id = id; this.name = name; } void display(){System.out.println(id+" "+name);} public static void main(String args[]){ Student13 e1 = new Student13(111,"karan"); Student13 e2 = new Student13(222,"Aryan"); e1.display(); e2.display(); } } Rule: Call to this() must be the first statement in constructor.
  • 42. Page 41Classification: Restricted this keyword can be used to invoke current class method (explicitly) class S{ void m(){ System.out.println("method is invoked"); } void n(){ this.m();//no need because compiler does it for you. } void p(){ n();//complier will add this to invoke n() method as this.n() } public static void main(String args[]){ S s1 = new S(); s1.p(); } }
  • 43. Page 42Classification: Restricted this keyword can be passed as an argument in the method class S2{ void m(S2 obj){ System.out.println("method is invoked"); } void p(){ m(this); } public static void main(String args[]){ S2 s1 = new S2(); s1.p(); } }
  • 44. Page 43Classification: Restricted What is the output? What does the below code do? class A5{ void m(){ System.out.println(this);//prints same reference ID } public static void main(String args[]){ A5 obj=new A5(); System.out.println(obj);//prints the reference ID obj.m(); } }
  • 45. Page 44Classification: Restricted Topics to be covered in next session • Review of last class concepts • Types of Inheritance and a look at Aggregation • Polymorphism • Method overloading • Method overriding