SlideShare a Scribd company logo
Core Java Training
OOP with Java Contd.
Page 1Classification: 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 3Classification: 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 4Classification: 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 5Classification: 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 6Classification: Restricted
Memory Allocation
Java & JEE Training
Method Overloading
Page 8Classification: 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 9Classification: 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 10Classification: 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 11Classification: 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 12Classification: 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 13Classification: 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 14Classification: 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 15Classification: 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 17Classification: 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 18Classification: 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 19Classification: 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 20Classification: 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 21Classification: 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 22Classification: Restricted
Point to ponder…
Does constructor return any value?
Java & JEE Training
”Static”
Page 24Classification: 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 25Classification: 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 26Classification: Restricted
Example: Problem without static variable
class Student{
int rollno;
String name;
String college="ITS";
}
Page 27Classification: 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 28Classification: Restricted
Static Variable Memory Allocation
Page 29Classification: 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 30Classification: 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 31Classification: 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 32Classification: 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 33Classification: Restricted
What is the output?
class A{
int a=40;//non static
public static void main(String args[]){
System.out.println(a);
}
}
Page 34Classification: Restricted
Point to ponder
• Why is main() method static?
Page 35Classification: 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 36Classification: 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 37Classification: 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 38Classification: 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 39Classification: 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 40Classification: 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 41Classification: 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 42Classification: 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 43Classification: 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 44Classification: Restricted
Thank you!

More Related Content

What's hot

Inheritance in java
Inheritance in javaInheritance in java
Inheritance in java
RahulAnanda1
 
Elements of Java Language
Elements of Java Language Elements of Java Language
Elements of Java Language
Hitesh-Java
 
Java Lambda Expressions.pptx
Java Lambda Expressions.pptxJava Lambda Expressions.pptx
Java Lambda Expressions.pptx
SameerAhmed593310
 
Java Presentation For Syntax
Java Presentation For SyntaxJava Presentation For Syntax
Java Presentation For Syntax
PravinYalameli
 
Java Collections | Collections Framework in Java | Java Tutorial For Beginner...
Java Collections | Collections Framework in Java | Java Tutorial For Beginner...Java Collections | Collections Framework in Java | Java Tutorial For Beginner...
Java Collections | Collections Framework in Java | Java Tutorial For Beginner...
Edureka!
 
Java Classes | Java Tutorial for Beginners | Java Classes and Objects | Java ...
Java Classes | Java Tutorial for Beginners | Java Classes and Objects | Java ...Java Classes | Java Tutorial for Beginners | Java Classes and Objects | Java ...
Java Classes | Java Tutorial for Beginners | Java Classes and Objects | Java ...
Edureka!
 
Control Statements in Java
Control Statements in JavaControl Statements in Java
Control Statements in Java
Niloy Saha
 
Interface in java
Interface in javaInterface in java
Interface in java
PhD Research Scholar
 
Core java complete notes - Contact at +91-814-614-5674
Core java complete notes - Contact at +91-814-614-5674Core java complete notes - Contact at +91-814-614-5674
Core java complete notes - Contact at +91-814-614-5674
Lokesh Kakkar Mobile No. 814-614-5674
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
kamal kotecha
 
Java threads
Java threadsJava threads
Java threads
Prabhakaran V M
 
Introduction to method overloading & method overriding in java hdm
Introduction to method overloading & method overriding  in java  hdmIntroduction to method overloading & method overriding  in java  hdm
Introduction to method overloading & method overriding in java hdm
Harshal Misalkar
 
Java 8 Lambda Expressions
Java 8 Lambda ExpressionsJava 8 Lambda Expressions
Java 8 Lambda Expressions
Scott Leberknight
 
Packages in java
Packages in javaPackages in java
Packages in java
Elizabeth alexander
 
Database Connectivity in PHP
Database Connectivity in PHPDatabase Connectivity in PHP
Database Connectivity in PHP
Taha Malampatti
 
Method Overloading in Java
Method Overloading in JavaMethod Overloading in Java
Method Overloading in Java
Sonya Akter Rupa
 
Inner classes in java
Inner classes in javaInner classes in java
Inner classes in java
PhD Research Scholar
 

What's hot (20)

Inheritance in java
Inheritance in javaInheritance in java
Inheritance in java
 
Elements of Java Language
Elements of Java Language Elements of Java Language
Elements of Java Language
 
Java Lambda Expressions.pptx
Java Lambda Expressions.pptxJava Lambda Expressions.pptx
Java Lambda Expressions.pptx
 
Java Presentation For Syntax
Java Presentation For SyntaxJava Presentation For Syntax
Java Presentation For Syntax
 
Java Collections | Collections Framework in Java | Java Tutorial For Beginner...
Java Collections | Collections Framework in Java | Java Tutorial For Beginner...Java Collections | Collections Framework in Java | Java Tutorial For Beginner...
Java Collections | Collections Framework in Java | Java Tutorial For Beginner...
 
Java Classes | Java Tutorial for Beginners | Java Classes and Objects | Java ...
Java Classes | Java Tutorial for Beginners | Java Classes and Objects | Java ...Java Classes | Java Tutorial for Beginners | Java Classes and Objects | Java ...
Java Classes | Java Tutorial for Beginners | Java Classes and Objects | Java ...
 
Control Statements in Java
Control Statements in JavaControl Statements in Java
Control Statements in Java
 
Interface in java
Interface in javaInterface in java
Interface in java
 
Core java complete notes - Contact at +91-814-614-5674
Core java complete notes - Contact at +91-814-614-5674Core java complete notes - Contact at +91-814-614-5674
Core java complete notes - Contact at +91-814-614-5674
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
 
OOP java
OOP javaOOP java
OOP java
 
Java threads
Java threadsJava threads
Java threads
 
Introduction to method overloading & method overriding in java hdm
Introduction to method overloading & method overriding  in java  hdmIntroduction to method overloading & method overriding  in java  hdm
Introduction to method overloading & method overriding in java hdm
 
Java 8 Lambda Expressions
Java 8 Lambda ExpressionsJava 8 Lambda Expressions
Java 8 Lambda Expressions
 
Generics
GenericsGenerics
Generics
 
Packages in java
Packages in javaPackages in java
Packages in java
 
Database Connectivity in PHP
Database Connectivity in PHPDatabase Connectivity in PHP
Database Connectivity in PHP
 
Method Overloading in Java
Method Overloading in JavaMethod Overloading in Java
Method Overloading in Java
 
Arrays in Java
Arrays in JavaArrays in Java
Arrays in Java
 
Inner classes in java
Inner classes in javaInner classes in java
Inner classes in java
 

Similar to OOP with Java - Continued

Session 08 - OOP with Java - continued
Session 08 - OOP with Java - continuedSession 08 - OOP with Java - continued
Session 08 - OOP with Java - continued
PawanMM
 
OOP with Java - continued
OOP with Java - continuedOOP with Java - continued
OOP with Java - continued
RatnaJava
 
constructors.pptx
constructors.pptxconstructors.pptx
constructors.pptx
Epsiba1
 
Static keyword ppt
Static keyword pptStatic keyword ppt
Static keyword ppt
Vinod Kumar
 
Object Oriented Programming with Java
Object Oriented Programming with JavaObject Oriented Programming with Java
Object Oriented Programming with JavaJussi Pohjolainen
 
Static keyword.pptx
Static keyword.pptxStatic keyword.pptx
Static keyword.pptx
KishanMishra44
 
11.Object Oriented Programming.pdf
11.Object Oriented Programming.pdf11.Object Oriented Programming.pdf
11.Object Oriented Programming.pdf
Export Promotion Bureau
 
OOPs Concepts - Android Programming
OOPs Concepts - Android ProgrammingOOPs Concepts - Android Programming
OOPs Concepts - Android Programming
Purvik Rana
 
03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots
mha4
 
03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots
mha4
 
JAVA CONCEPTS
JAVA CONCEPTS JAVA CONCEPTS
JAVA CONCEPTS
Shivam Singh
 
11. Java Objects and classes
11. Java  Objects and classes11. Java  Objects and classes
11. Java Objects and classes
Intro C# Book
 
Defining classes-and-objects-1.0
Defining classes-and-objects-1.0Defining classes-and-objects-1.0
Defining classes-and-objects-1.0
BG Java EE Course
 
Oop java
Oop javaOop java
Oop java
Minal Maniar
 
Sonu wiziq
Sonu wiziqSonu wiziq
Sonu wiziq
Sonu WIZIQ
 
Java Programs
Java ProgramsJava Programs
Java Programs
vvpadhu
 
CH1 ARRAY (1).pptx
CH1 ARRAY (1).pptxCH1 ARRAY (1).pptx
CH1 ARRAY (1).pptx
AnkitaVerma776806
 
Java Foundations: Objects and Classes
Java Foundations: Objects and ClassesJava Foundations: Objects and Classes
Java Foundations: Objects and Classes
Svetlin Nakov
 

Similar to OOP with Java - Continued (20)

Session 08 - OOP with Java - continued
Session 08 - OOP with Java - continuedSession 08 - OOP with Java - continued
Session 08 - OOP with Java - continued
 
OOP with Java - continued
OOP with Java - continuedOOP with Java - continued
OOP with Java - continued
 
constructors.pptx
constructors.pptxconstructors.pptx
constructors.pptx
 
Static keyword ppt
Static keyword pptStatic keyword ppt
Static keyword ppt
 
Object Oriented Programming with Java
Object Oriented Programming with JavaObject Oriented Programming with Java
Object Oriented Programming with Java
 
Static keyword.pptx
Static keyword.pptxStatic keyword.pptx
Static keyword.pptx
 
11.Object Oriented Programming.pdf
11.Object Oriented Programming.pdf11.Object Oriented Programming.pdf
11.Object Oriented Programming.pdf
 
OOPs Concepts - Android Programming
OOPs Concepts - Android ProgrammingOOPs Concepts - Android Programming
OOPs Concepts - Android Programming
 
Core java Essentials
Core java EssentialsCore java Essentials
Core java Essentials
 
03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots
 
03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots
 
JAVA CONCEPTS
JAVA CONCEPTS JAVA CONCEPTS
JAVA CONCEPTS
 
Java basic understand OOP
Java basic understand OOPJava basic understand OOP
Java basic understand OOP
 
11. Java Objects and classes
11. Java  Objects and classes11. Java  Objects and classes
11. Java Objects and classes
 
Defining classes-and-objects-1.0
Defining classes-and-objects-1.0Defining classes-and-objects-1.0
Defining classes-and-objects-1.0
 
Oop java
Oop javaOop java
Oop java
 
Sonu wiziq
Sonu wiziqSonu wiziq
Sonu wiziq
 
Java Programs
Java ProgramsJava Programs
Java Programs
 
CH1 ARRAY (1).pptx
CH1 ARRAY (1).pptxCH1 ARRAY (1).pptx
CH1 ARRAY (1).pptx
 
Java Foundations: Objects and Classes
Java Foundations: Objects and ClassesJava Foundations: Objects and Classes
Java Foundations: Objects and Classes
 

More from Hitesh-Java

Spring - Part 4 - Spring MVC
Spring - Part 4 - Spring MVCSpring - Part 4 - Spring MVC
Spring - Part 4 - Spring MVC
Hitesh-Java
 
Spring - Part 3 - AOP
Spring - Part 3 - AOPSpring - Part 3 - AOP
Spring - Part 3 - AOP
Hitesh-Java
 
Spring - Part 2 - Autowiring, Annotations, Java based Configuration - slides
Spring - Part 2 - Autowiring, Annotations, Java based Configuration - slidesSpring - Part 2 - Autowiring, Annotations, Java based Configuration - slides
Spring - Part 2 - Autowiring, Annotations, Java based Configuration - slides
Hitesh-Java
 
Spring - Part 1 - IoC, Di and Beans
Spring - Part 1 - IoC, Di and Beans Spring - Part 1 - IoC, Di and Beans
Spring - Part 1 - IoC, Di and Beans
Hitesh-Java
 
JSP - Part 2 (Final)
JSP - Part 2 (Final) JSP - Part 2 (Final)
JSP - Part 2 (Final)
Hitesh-Java
 
JSP - Part 1
JSP - Part 1JSP - Part 1
JSP - Part 1
Hitesh-Java
 
Struts 2 - Hibernate Integration
Struts 2 - Hibernate Integration Struts 2 - Hibernate Integration
Struts 2 - Hibernate Integration
Hitesh-Java
 
Struts 2 - Introduction
Struts 2 - Introduction Struts 2 - Introduction
Struts 2 - Introduction
Hitesh-Java
 
Hibernate - Part 2
Hibernate - Part 2 Hibernate - Part 2
Hibernate - Part 2
Hitesh-Java
 
Hibernate - Part 1
Hibernate - Part 1Hibernate - Part 1
Hibernate - Part 1
Hitesh-Java
 
JDBC Part - 2
JDBC Part - 2JDBC Part - 2
JDBC Part - 2
Hitesh-Java
 
JDBC
JDBCJDBC
Java IO, Serialization
Java IO, Serialization Java IO, Serialization
Java IO, Serialization
Hitesh-Java
 
Inner Classes
Inner Classes Inner Classes
Inner Classes
Hitesh-Java
 
Collections - Maps
Collections - Maps Collections - Maps
Collections - Maps
Hitesh-Java
 
Review Session - Part -2
Review Session - Part -2Review Session - Part -2
Review Session - Part -2
Hitesh-Java
 
Review Session and Attending Java Interviews
Review Session and Attending Java Interviews Review Session and Attending Java Interviews
Review Session and Attending Java Interviews
Hitesh-Java
 
Collections - Sorting, Comparing Basics
Collections - Sorting, Comparing Basics Collections - Sorting, Comparing Basics
Collections - Sorting, Comparing Basics
Hitesh-Java
 
Collections - Array List
Collections - Array List Collections - Array List
Collections - Array List
Hitesh-Java
 
Object Class
Object Class Object Class
Object Class
Hitesh-Java
 

More from Hitesh-Java (20)

Spring - Part 4 - Spring MVC
Spring - Part 4 - Spring MVCSpring - Part 4 - Spring MVC
Spring - Part 4 - Spring MVC
 
Spring - Part 3 - AOP
Spring - Part 3 - AOPSpring - Part 3 - AOP
Spring - Part 3 - AOP
 
Spring - Part 2 - Autowiring, Annotations, Java based Configuration - slides
Spring - Part 2 - Autowiring, Annotations, Java based Configuration - slidesSpring - Part 2 - Autowiring, Annotations, Java based Configuration - slides
Spring - Part 2 - Autowiring, Annotations, Java based Configuration - slides
 
Spring - Part 1 - IoC, Di and Beans
Spring - Part 1 - IoC, Di and Beans Spring - Part 1 - IoC, Di and Beans
Spring - Part 1 - IoC, Di and Beans
 
JSP - Part 2 (Final)
JSP - Part 2 (Final) JSP - Part 2 (Final)
JSP - Part 2 (Final)
 
JSP - Part 1
JSP - Part 1JSP - Part 1
JSP - Part 1
 
Struts 2 - Hibernate Integration
Struts 2 - Hibernate Integration Struts 2 - Hibernate Integration
Struts 2 - Hibernate Integration
 
Struts 2 - Introduction
Struts 2 - Introduction Struts 2 - Introduction
Struts 2 - Introduction
 
Hibernate - Part 2
Hibernate - Part 2 Hibernate - Part 2
Hibernate - Part 2
 
Hibernate - Part 1
Hibernate - Part 1Hibernate - Part 1
Hibernate - Part 1
 
JDBC Part - 2
JDBC Part - 2JDBC Part - 2
JDBC Part - 2
 
JDBC
JDBCJDBC
JDBC
 
Java IO, Serialization
Java IO, Serialization Java IO, Serialization
Java IO, Serialization
 
Inner Classes
Inner Classes Inner Classes
Inner Classes
 
Collections - Maps
Collections - Maps Collections - Maps
Collections - Maps
 
Review Session - Part -2
Review Session - Part -2Review Session - Part -2
Review Session - Part -2
 
Review Session and Attending Java Interviews
Review Session and Attending Java Interviews Review Session and Attending Java Interviews
Review Session and Attending Java Interviews
 
Collections - Sorting, Comparing Basics
Collections - Sorting, Comparing Basics Collections - Sorting, Comparing Basics
Collections - Sorting, Comparing Basics
 
Collections - Array List
Collections - Array List Collections - Array List
Collections - Array List
 
Object Class
Object Class Object Class
Object Class
 

Recently uploaded

When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
Elena Simperl
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
BookNet Canada
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Product School
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Inflectra
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Thierry Lestable
 
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptxIOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
Abida Shariff
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
Elena Simperl
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
Laura Byrne
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
Sri Ambati
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Tobias Schneck
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
Product School
 
ODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User GroupODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User Group
CatarinaPereira64715
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
Product School
 
Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*
Frank van Harmelen
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
ThousandEyes
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
Alison B. Lowndes
 
Search and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical FuturesSearch and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical Futures
Bhaskar Mitra
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
Kari Kakkonen
 

Recently uploaded (20)

When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
 
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptxIOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
 
ODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User GroupODC, Data Fabric and Architecture User Group
ODC, Data Fabric and Architecture User Group
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
 
Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
 
Search and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical FuturesSearch and Society: Reimagining Information Access for Radical Futures
Search and Society: Reimagining Information Access for Radical Futures
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
 

OOP with Java - Continued

  • 1. Core Java Training OOP with Java Contd.
  • 2. Page 1Classification: 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
  • 3. Java & JEE Training Object Oriented Programming with Java - Basic Class Demo
  • 4. Page 3Classification: 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.
  • 5. Page 4Classification: 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); } }
  • 6. Page 5Classification: 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(); } }
  • 8. Java & JEE Training Method Overloading
  • 9. Page 8Classification: 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
  • 10. Page 9Classification: 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); } }
  • 11. Page 10Classification: 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); } }
  • 12. Page 11Classification: 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 */ } } //
  • 13. Page 12Classification: 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); } }
  • 14. Page 13Classification: 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); } }
  • 15. Page 14Classification: 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. } }
  • 16. Page 15Classification: 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.
  • 17. Java & JEE Training Constructors
  • 18. Page 17Classification: 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(); } }
  • 19. Page 18Classification: 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(); } }
  • 20. Page 19Classification: 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(); } }
  • 21. Page 20Classification: 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.
  • 22. Page 21Classification: 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(); } }
  • 23. Page 22Classification: Restricted Point to ponder… Does constructor return any value?
  • 24. Java & JEE Training ”Static”
  • 25. Page 24Classification: 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
  • 26. Page 25Classification: 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
  • 27. Page 26Classification: Restricted Example: Problem without static variable class Student{ int rollno; String name; String college="ITS"; }
  • 28. Page 27Classification: 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(); } }
  • 29. Page 28Classification: Restricted Static Variable Memory Allocation
  • 30. Page 29Classification: 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(); } }
  • 31. Page 30Classification: 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.
  • 32. Page 31Classification: 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(); } }
  • 33. Page 32Classification: 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); } }
  • 34. Page 33Classification: Restricted What is the output? class A{ int a=40;//non static public static void main(String args[]){ System.out.println(a); } }
  • 35. Page 34Classification: Restricted Point to ponder • Why is main() method static?
  • 36. Page 35Classification: 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"); } }
  • 37. Page 36Classification: 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.
  • 38. Page 37Classification: 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(); } }
  • 39. Page 38Classification: 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:
  • 40. Page 39Classification: 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.
  • 41. Page 40Classification: 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(); } }
  • 42. Page 41Classification: 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(); } }
  • 43. Page 42Classification: 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(); } }
  • 44. Page 43Classification: 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