SlideShare uma empresa Scribd logo
1 de 37
Object Oriented
Concepts
GOUSALYA RAMACHANDRAN
Basic Concepts in Java
----------------------------------------------------------------------
What is a Class?
 Class is a defined blue print (sketch) of how an object should be. From a
class several identical objects (real world things) can be created
(instantiated)
Person.class
public class Person {
String name;
int age;
public Sam(String mName, int mAge){
name = mName;
age = mAge
}
public void eat(){
System.out.println(“I eat”);
}
}
Creating an Object from Person.class
Person Sam = new Person(“Sam”, 42);
Sam.eat(); //prints I eat
What is a Class?
 Declaring a class – Creating a “Person.class” file
 Instantiating a class – Creating “Sam” object from “Person.class”
 When declaring a class, following components should be added to the class :
 Access Modifier – Granting an access level to the class. Eg: public/protected/default
 Class name
 Super class (if any) – Will be discussed later
 Interfaces (if any) – Will be discussed later
 Body - Body also have following controls
 Variables : describing the properties of the object (Eg : name, age)
 Methods : describing behavior of the object (Eg : eat(), sleep())
 An object instantiated from a class will have the attributes and behavior available for the class along with a
unique object name (Eg: Sam)
What is a class?
Person.class
Characteristics
Name
Age
Behaviors
Eat()
Sleep()
Sam
Amal
John
What is a class?
 Access modifiers
The access modifiers in Java specifies the accessibility or scope of a field,
method, constructor, or class
Note : Package is a collection of classes.
Access Modifiers Public Protected Private Default
Accessible inside class Yes Yes Yes Yes
Accessible within subclass inside
same package
Yes Yes No Yes
Accessible outside the package Yes No No No
Accessible within subclass outside
package
Yes Yes No No
What is a class?
 Datatypes
Data Types
Primitive : Most basic
Int : Integer
Float : large decimal numbers
Boolean : True(1)/False(0)
Double : decimal values
Char : single character
Non Primitive
String : characters
Array : collection of values of a data type
Variables in a class
This represents the properties of a class and has following components:
<access modifier> <datatype> <variable_name> = <value>
Declaring the variable Initializing the variable
E.g.: public String name = “Sam”
Variables in a class
 Variables can be placed in 3 locations in a class
 Local variable
 Declared and can be accessed within a method only
 Access modifiers cannot be used for this variable
 Instance variable
 Declared outside the method and within the class
 For each new object of the class, new instance(duplicate) of the variable is created
 If the object is destroyed, the instance is also destroyed
 Class / Static variable
 Declared with keyword static, outside the method and within the class
 There would only be one copy of each class variable per class, regardless of how many
objects are created from it.
Variables in a class
 Static keyword
 There would only be one copy of each variable/method, regardless of how many objects are
created from it
 Final keyword
 When a variable is given the keyword final, the value of the variable cannot be changed and
can only be used as a constant
Public class CalculateArea {
final double pi = 3.14;
public void changePi(){
pi = 3.15 //This is not allowed. Will generate a compile error
}
}
Operators in Java
 Arithmetic Operators
 +, -, *(multiply), /(Division), % (Modulus), ++ (Increment by 1), -- (Decrement by 1)
 Relational Operators
 ==(Equal), !==(not equal), >, <, <=,>=
 Logical Operators
 &&(And), || (OR), ! (NOT)
 Assignment Operators
 = : A+B = C
 += : A+=C (C+A=A)
 -= : A-=C (A-C=A)
 *= : A*=C (A*C=A)
 /= : A/=C (A/C=A)
 %= : A%=C (A%C=A)
Methods in Java
 These describe the behavior of the object
 A method has following components:
<access modifier> <return type> <method name> ( <parameter list>){
<method body> //known as implementation
}
Return type : The datatype of the value returned from the method.
 If there is a value returning from the method, “return <value>” SHOULD BE
PLACEED IN THE BOTTOM OF THE METHOD BODY.
 If there is no data returned from the method the return type should be
VOID.
Declaring a method
Implementing
a method
Methods in Java
Public int sumValue(int a, int b){
return a+b;
}
Public void sumValue(int a, int b){
int sum = a+b;//There is nothing returned from the method
}
• Main Method :
• This is the method that is the entry point to the Java class/application.
• The signature of the main method is always:
public static void main(String[] args){
//method implementation
}
What are constructors then?
 Constructors are the first method executed when an Object is created from
a class.
 Person Sam = new Person()
 This has the same name as the class and has no return type (so void)
 We use the constructors to initialize the instance variables in the class
 Whether you define or not every class has a constructor.
This is the first method
executed for the Sam
object
Loops in Java
 There are various types of loops in Java
 For loop
 While loop
 Do..while loop
 Break keyword allows to break from the complete loop
 Continue keyword allows to move to the next loop iteration skipping the
rest of the code
Decision making statements
 If
 If-else
 Nested if (if-else if-else)
 Switch statements
OOP Concepts
---------------------------------------------------
Why do you need OOP Concepts?
 Ensuring security and access levels of classes
 Easy to understand and implement the code
 Ensure redundancy and increased code re-use
 Maintenance of the code is easy
What are the OOP Concepts?
 Inheritance
 Encapsulation
 Abstraction
 Polymorphism
Inheritance
 The concept allows us to place the general characteristics of several classes
in one class – super class.
 From this class, the sub classes can inherit the general characteristics and
behaviors of the super class using the keyword - extend
 The attributes and methods in the super class can be accessed using the
keyword super
Inheritance
Employee
Attributes :
Name
Address
Age
Methods:
getAttendance()
Full Time
Attributes :
BasicSalary
Methods:
getBasicSalary()
Part Time
Attributes:
Allowance
Methods:
getAllowance()
extends
extends
Inheritance
Public class Employee{
String name;
int age;
String address;
getAttendance(){
System.out.println(“Attendance”);
}
}
Public class FullTime extends Employee{
double basicSalary;
getBasicSalary(){
System.out.println(“Name is” + super.name);
System.out.println(“Salary is” + basicSalary);
}
}
Public class PartTime extends Employee{
double allowance;
getBasicSalary(){
System.out.println(“Name is” + super.name);
System.out.println(“Allowance is” + allowance);
}
}
Super keyword allows to access variables or methods
from the parent class
Inheritance
 Inheritance can be implemented in several ways:
Polymorphism
 The ability of an object to have many forms.
Public class Animal{}
Public class Herbivores extends Animal{}
Public class Cow extends Herbivores{}
 So we know that
 Cow is a herbivore
 Cow is an animal
 Cow is a cow
 Cow is an object
So a cow displays many such forms
displaying Polymorphism
Polymorphism
 Methods can also implement polymorphism
 Method overloading
 Allowing a class to have method with same name but different parameters
 This can be a constructor or any other method inside a class
 The method can be overloaded by following ways
Public class Calculator{
Public void add(int num1, float num2){}//Original method
public void add(int num1, float num2, float num3){}//overloaded by no. of parameters
public void add(int num1,int num2){}//overloaded by data type
public void add(float num1,int num2){}//overloaded by data type order
}
Polymorphism
 Method Overriding
 Sub class having the same method as the parent class.
 This occurs when the child class has different implementation(method body) for a method in parent class
Public class Employee{
public void getAttendance(){
System.out.println(“Employee Attendance”);
}
}
Public class PartTime extends Employee{
public void getAttendance(){
System.out.println(“Part Time Employee Attendance”);//Employee class method is override
}
}
Polymorphism
 Method Overriding
 When calling the getAttendance method for the PartTimeClass, the method
implementation in the PartTimeClass is executed.
Public class Test{
public static void main(String[] args){
Employee e = new Employee();
e.getAttendance(); // Employee Attendance – printed
PartTime p = new PartTime();
p.getAttendance();// Part Time Employee Attendance – printed
}
}
Encapsulation
 Also known as data hiding.
 Textbook definition : Wrapping variables and the methods acting on the variable as
single unit
 Basically, we hide the data(variables) and allow the data to be accessed using methods.
We do not allow the variables/data to be accessed directly.
 To achieve encapsulation in Java −
 Declare the variables of a class as private.
 Provide public setter and getter methods to modify and view the variables values.
Encapsulation
Public class Employee{
private string employeeName;
public string getName(){
return employeeName;
}
protected void setName(string eName){
employeeName = eName;
}
}
The employee name can be accessed by any
classes within / outside the package(of the
original class).
But the name can be updated only by the
classes within the package and the sub classes
outside the package
Abstraction
 Abstraction hides how something is done. It gives the details of the method
name, output (returned) and input(parameter) details but not the method
body.
 Abstraction is achieved using abstract classes, methods and interfaces
 If a method is abstract the class must be abstract.
public abstract class Employee{
private string employeeName;
public abstract string setName(String name); //abstract method without body
}
Abstraction
Public abstract class Employee{
private string employeeName;
public string getName(){
return employeeName;
}
protected void setName(string eName){
employeeName = eName;
}
}
An abstract class is NOT allowed to create
objects(so that implementation is not visible to
another class).
But an abstract class can be inherited.
Why can’t we instantiate(create an object from) an abstract class?
An abstract class is an incomplete class and can have abstract methods. These
abstract methods do not have implementation(method body), so the will not be
allowed to execute. Hence, we cannot create objects from abstract class
Abstraction
Abstract methods
• Abstract methods are methods without method body.
• They have the method signature ( or what the method is about), not the implementation
(how the method is carried out)
Public abstract class Employee{
private string employeeName;
public string getName(){
return employeeName;
}
public abstract string setName();
}
Abstraction
Public class PartTime extends Employee{
public void setName(string eName){
employeeName = eName;//The abstract method must be implemented
}
}
When inheriting an abstract class, the abstract method must be implemented(method body should be written).
The sub class is now a complete class.
So this class can be used to create objects.
Interfaces
 Java does not support multiple inheritance via classes.
 But Java allows multiple inheritance via interfaces
Parent Class :
CalculateArea
Parent Class :
RegularShape
X
Child Class : Circle
Child Class :
Square
Interface:
CalculateArea
Parent Class :
RegularShape
Child Class : Circle
Child Class :
Square
X
Interfaces
 Interfaces are implemented as follows:
<access_modifier> interface <interface_name>{
final <data type> <variable_name> = <value>
abstract <return type> <method_name> (parameter_list);
}
 All the variables in an interface is final and the methods are abstract compared to a class
which doesn’t have such restrictions
 All the variables and methods are public
 A class can implement multiple interfaces
When to create an interface?
 Consider the below scenario
 A regular shape can be a circle or square.
 The common characteristics of a regular shape is
 Color
 No. of edges
 Most of the shapes(regular or irregular) have an area. In such case you can
have:
 A parent class called shape (inherited by regular and with method CalculateArea
 But the area calculation changes from shape to shape
 An abstract class with method CalculateArea
 Multiple inheritance is not allowed in Java
 Interface with abstract method CalculateArea
 This can be implemented
Abstract Classes and Interfaces
Interface Abstract Class
Support Multiple Inheritance Do not support multiple inheritance
Doesn’t have constructors Have constructors
Only has abstract method Has abstract and complete classes
Everything is public Can have other access modifiers
Cannot be static Can be static

Mais conteúdo relacionado

Mais procurados

java-06inheritance
java-06inheritancejava-06inheritance
java-06inheritance
Arjun Shanka
 
Inheritance And Traits
Inheritance And TraitsInheritance And Traits
Inheritance And Traits
Piyush Mishra
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in java
Tech_MX
 

Mais procurados (20)

Built in classes in java
Built in classes in javaBuilt in classes in java
Built in classes in java
 
Generics in java
Generics in javaGenerics in java
Generics in java
 
Introduction to php oop
Introduction to php oopIntroduction to php oop
Introduction to php oop
 
Java: Inheritance
Java: InheritanceJava: Inheritance
Java: Inheritance
 
Introduction to OOP(in java) BY Govind Singh
Introduction to OOP(in java)  BY Govind SinghIntroduction to OOP(in java)  BY Govind Singh
Introduction to OOP(in java) BY Govind Singh
 
Core & Advance Java Training For Beginner-PSK Technologies Pvt. Ltd. Nagpur
Core & Advance Java Training For Beginner-PSK Technologies Pvt. Ltd. NagpurCore & Advance Java Training For Beginner-PSK Technologies Pvt. Ltd. Nagpur
Core & Advance Java Training For Beginner-PSK Technologies Pvt. Ltd. Nagpur
 
Java q ref 2018
Java q ref 2018Java q ref 2018
Java q ref 2018
 
03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots
 
javainheritance
javainheritancejavainheritance
javainheritance
 
Java Inheritance
Java InheritanceJava Inheritance
Java Inheritance
 
Java Generics
Java GenericsJava Generics
Java Generics
 
Unit3 inheritance
Unit3 inheritanceUnit3 inheritance
Unit3 inheritance
 
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYAPYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
 
Object oriented programming with python
Object oriented programming with pythonObject oriented programming with python
Object oriented programming with python
 
Class or Object
Class or ObjectClass or Object
Class or Object
 
java-06inheritance
java-06inheritancejava-06inheritance
java-06inheritance
 
Inheritance And Traits
Inheritance And TraitsInheritance And Traits
Inheritance And Traits
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in java
 
Python unit 3 m.sc cs
Python unit 3 m.sc csPython unit 3 m.sc cs
Python unit 3 m.sc cs
 
The Ring programming language version 1.6 book - Part 76 of 189
The Ring programming language version 1.6 book - Part 76 of 189The Ring programming language version 1.6 book - Part 76 of 189
The Ring programming language version 1.6 book - Part 76 of 189
 

Semelhante a Object oriented concepts

Object Oriented Programming with Java
Object Oriented Programming with JavaObject Oriented Programming with Java
Object Oriented Programming with Java
backdoor
 
9781439035665 ppt ch08
9781439035665 ppt ch089781439035665 ppt ch08
9781439035665 ppt ch08
Terry Yoast
 
JAVA Notes - All major concepts covered with examples
JAVA Notes - All major concepts covered with examplesJAVA Notes - All major concepts covered with examples
JAVA Notes - All major concepts covered with examples
Sunil Kumar Gunasekaran
 

Semelhante a Object oriented concepts (20)

Chapter 5 (OOP Principles).ppt
Chapter 5 (OOP Principles).pptChapter 5 (OOP Principles).ppt
Chapter 5 (OOP Principles).ppt
 
Introduction of Object Oriented Programming Language using Java. .pptx
Introduction of Object Oriented Programming Language using Java. .pptxIntroduction of Object Oriented Programming Language using Java. .pptx
Introduction of Object Oriented Programming Language using Java. .pptx
 
Java Reflection
Java ReflectionJava Reflection
Java Reflection
 
Basics of Java
Basics of JavaBasics of Java
Basics of Java
 
Unit3 part1-class
Unit3 part1-classUnit3 part1-class
Unit3 part1-class
 
03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots
 
Java session4
Java session4Java session4
Java session4
 
Corejava Training in Bangalore Tutorial
Corejava Training in Bangalore TutorialCorejava Training in Bangalore Tutorial
Corejava Training in Bangalore Tutorial
 
Object Oriented Programming with Java
Object Oriented Programming with JavaObject Oriented Programming with Java
Object Oriented Programming with Java
 
Basic concept of class, method , command line-argument
Basic concept of class, method , command line-argumentBasic concept of class, method , command line-argument
Basic concept of class, method , command line-argument
 
Java Basic day-2
Java Basic day-2Java Basic day-2
Java Basic day-2
 
Sonu wiziq
Sonu wiziqSonu wiziq
Sonu wiziq
 
9781439035665 ppt ch08
9781439035665 ppt ch089781439035665 ppt ch08
9781439035665 ppt ch08
 
JAVA Notes - All major concepts covered with examples
JAVA Notes - All major concepts covered with examplesJAVA Notes - All major concepts covered with examples
JAVA Notes - All major concepts covered with examples
 
Core java oop
Core java oopCore java oop
Core java oop
 
Assignment 7
Assignment 7Assignment 7
Assignment 7
 
Java assignment help
Java assignment helpJava assignment help
Java assignment help
 
Computer programming 2 Lesson 15
Computer programming 2  Lesson 15Computer programming 2  Lesson 15
Computer programming 2 Lesson 15
 
Lecture 6.pptx
Lecture 6.pptxLecture 6.pptx
Lecture 6.pptx
 
Chap11
Chap11Chap11
Chap11
 

Último

Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
VictoriaMetrics
 
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Medical / Health Care (+971588192166) Mifepristone and Misoprostol tablets 200mg
 
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
masabamasaba
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
Health
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is inside
shinachiaurasa2
 

Último (20)

Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
 
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
Abortion Pills In Pretoria ](+27832195400*)[ 🏥 Women's Abortion Clinic In Pre...
 
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdfPayment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
 
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto
 
What Goes Wrong with Language Definitions and How to Improve the Situation
What Goes Wrong with Language Definitions and How to Improve the SituationWhat Goes Wrong with Language Definitions and How to Improve the Situation
What Goes Wrong with Language Definitions and How to Improve the Situation
 
WSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go PlatformlessWSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go Platformless
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
 
WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is inside
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
 
Artyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptxArtyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptx
 
%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Harare%in Harare+277-882-255-28 abortion pills for sale in Harare
%in Harare+277-882-255-28 abortion pills for sale in Harare
 
Architecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastArchitecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the past
 
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
 
tonesoftg
tonesoftgtonesoftg
tonesoftg
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students
 

Object oriented concepts

  • 2. Basic Concepts in Java ----------------------------------------------------------------------
  • 3. What is a Class?  Class is a defined blue print (sketch) of how an object should be. From a class several identical objects (real world things) can be created (instantiated) Person.class public class Person { String name; int age; public Sam(String mName, int mAge){ name = mName; age = mAge } public void eat(){ System.out.println(“I eat”); } } Creating an Object from Person.class Person Sam = new Person(“Sam”, 42); Sam.eat(); //prints I eat
  • 4. What is a Class?  Declaring a class – Creating a “Person.class” file  Instantiating a class – Creating “Sam” object from “Person.class”  When declaring a class, following components should be added to the class :  Access Modifier – Granting an access level to the class. Eg: public/protected/default  Class name  Super class (if any) – Will be discussed later  Interfaces (if any) – Will be discussed later  Body - Body also have following controls  Variables : describing the properties of the object (Eg : name, age)  Methods : describing behavior of the object (Eg : eat(), sleep())  An object instantiated from a class will have the attributes and behavior available for the class along with a unique object name (Eg: Sam)
  • 5. What is a class? Person.class Characteristics Name Age Behaviors Eat() Sleep() Sam Amal John
  • 6. What is a class?  Access modifiers The access modifiers in Java specifies the accessibility or scope of a field, method, constructor, or class Note : Package is a collection of classes. Access Modifiers Public Protected Private Default Accessible inside class Yes Yes Yes Yes Accessible within subclass inside same package Yes Yes No Yes Accessible outside the package Yes No No No Accessible within subclass outside package Yes Yes No No
  • 7. What is a class?  Datatypes Data Types Primitive : Most basic Int : Integer Float : large decimal numbers Boolean : True(1)/False(0) Double : decimal values Char : single character Non Primitive String : characters Array : collection of values of a data type
  • 8. Variables in a class This represents the properties of a class and has following components: <access modifier> <datatype> <variable_name> = <value> Declaring the variable Initializing the variable E.g.: public String name = “Sam”
  • 9. Variables in a class  Variables can be placed in 3 locations in a class  Local variable  Declared and can be accessed within a method only  Access modifiers cannot be used for this variable  Instance variable  Declared outside the method and within the class  For each new object of the class, new instance(duplicate) of the variable is created  If the object is destroyed, the instance is also destroyed  Class / Static variable  Declared with keyword static, outside the method and within the class  There would only be one copy of each class variable per class, regardless of how many objects are created from it.
  • 10. Variables in a class  Static keyword  There would only be one copy of each variable/method, regardless of how many objects are created from it  Final keyword  When a variable is given the keyword final, the value of the variable cannot be changed and can only be used as a constant Public class CalculateArea { final double pi = 3.14; public void changePi(){ pi = 3.15 //This is not allowed. Will generate a compile error } }
  • 11. Operators in Java  Arithmetic Operators  +, -, *(multiply), /(Division), % (Modulus), ++ (Increment by 1), -- (Decrement by 1)  Relational Operators  ==(Equal), !==(not equal), >, <, <=,>=  Logical Operators  &&(And), || (OR), ! (NOT)  Assignment Operators  = : A+B = C  += : A+=C (C+A=A)  -= : A-=C (A-C=A)  *= : A*=C (A*C=A)  /= : A/=C (A/C=A)  %= : A%=C (A%C=A)
  • 12. Methods in Java  These describe the behavior of the object  A method has following components: <access modifier> <return type> <method name> ( <parameter list>){ <method body> //known as implementation } Return type : The datatype of the value returned from the method.  If there is a value returning from the method, “return <value>” SHOULD BE PLACEED IN THE BOTTOM OF THE METHOD BODY.  If there is no data returned from the method the return type should be VOID. Declaring a method Implementing a method
  • 13. Methods in Java Public int sumValue(int a, int b){ return a+b; } Public void sumValue(int a, int b){ int sum = a+b;//There is nothing returned from the method } • Main Method : • This is the method that is the entry point to the Java class/application. • The signature of the main method is always: public static void main(String[] args){ //method implementation }
  • 14. What are constructors then?  Constructors are the first method executed when an Object is created from a class.  Person Sam = new Person()  This has the same name as the class and has no return type (so void)  We use the constructors to initialize the instance variables in the class  Whether you define or not every class has a constructor. This is the first method executed for the Sam object
  • 15. Loops in Java  There are various types of loops in Java  For loop  While loop  Do..while loop  Break keyword allows to break from the complete loop  Continue keyword allows to move to the next loop iteration skipping the rest of the code
  • 16. Decision making statements  If  If-else  Nested if (if-else if-else)  Switch statements
  • 18. Why do you need OOP Concepts?  Ensuring security and access levels of classes  Easy to understand and implement the code  Ensure redundancy and increased code re-use  Maintenance of the code is easy
  • 19. What are the OOP Concepts?  Inheritance  Encapsulation  Abstraction  Polymorphism
  • 20. Inheritance  The concept allows us to place the general characteristics of several classes in one class – super class.  From this class, the sub classes can inherit the general characteristics and behaviors of the super class using the keyword - extend  The attributes and methods in the super class can be accessed using the keyword super
  • 21. Inheritance Employee Attributes : Name Address Age Methods: getAttendance() Full Time Attributes : BasicSalary Methods: getBasicSalary() Part Time Attributes: Allowance Methods: getAllowance() extends extends
  • 22. Inheritance Public class Employee{ String name; int age; String address; getAttendance(){ System.out.println(“Attendance”); } } Public class FullTime extends Employee{ double basicSalary; getBasicSalary(){ System.out.println(“Name is” + super.name); System.out.println(“Salary is” + basicSalary); } } Public class PartTime extends Employee{ double allowance; getBasicSalary(){ System.out.println(“Name is” + super.name); System.out.println(“Allowance is” + allowance); } } Super keyword allows to access variables or methods from the parent class
  • 23. Inheritance  Inheritance can be implemented in several ways:
  • 24. Polymorphism  The ability of an object to have many forms. Public class Animal{} Public class Herbivores extends Animal{} Public class Cow extends Herbivores{}  So we know that  Cow is a herbivore  Cow is an animal  Cow is a cow  Cow is an object So a cow displays many such forms displaying Polymorphism
  • 25. Polymorphism  Methods can also implement polymorphism  Method overloading  Allowing a class to have method with same name but different parameters  This can be a constructor or any other method inside a class  The method can be overloaded by following ways Public class Calculator{ Public void add(int num1, float num2){}//Original method public void add(int num1, float num2, float num3){}//overloaded by no. of parameters public void add(int num1,int num2){}//overloaded by data type public void add(float num1,int num2){}//overloaded by data type order }
  • 26. Polymorphism  Method Overriding  Sub class having the same method as the parent class.  This occurs when the child class has different implementation(method body) for a method in parent class Public class Employee{ public void getAttendance(){ System.out.println(“Employee Attendance”); } } Public class PartTime extends Employee{ public void getAttendance(){ System.out.println(“Part Time Employee Attendance”);//Employee class method is override } }
  • 27. Polymorphism  Method Overriding  When calling the getAttendance method for the PartTimeClass, the method implementation in the PartTimeClass is executed. Public class Test{ public static void main(String[] args){ Employee e = new Employee(); e.getAttendance(); // Employee Attendance – printed PartTime p = new PartTime(); p.getAttendance();// Part Time Employee Attendance – printed } }
  • 28. Encapsulation  Also known as data hiding.  Textbook definition : Wrapping variables and the methods acting on the variable as single unit  Basically, we hide the data(variables) and allow the data to be accessed using methods. We do not allow the variables/data to be accessed directly.  To achieve encapsulation in Java −  Declare the variables of a class as private.  Provide public setter and getter methods to modify and view the variables values.
  • 29. Encapsulation Public class Employee{ private string employeeName; public string getName(){ return employeeName; } protected void setName(string eName){ employeeName = eName; } } The employee name can be accessed by any classes within / outside the package(of the original class). But the name can be updated only by the classes within the package and the sub classes outside the package
  • 30. Abstraction  Abstraction hides how something is done. It gives the details of the method name, output (returned) and input(parameter) details but not the method body.  Abstraction is achieved using abstract classes, methods and interfaces  If a method is abstract the class must be abstract. public abstract class Employee{ private string employeeName; public abstract string setName(String name); //abstract method without body }
  • 31. Abstraction Public abstract class Employee{ private string employeeName; public string getName(){ return employeeName; } protected void setName(string eName){ employeeName = eName; } } An abstract class is NOT allowed to create objects(so that implementation is not visible to another class). But an abstract class can be inherited. Why can’t we instantiate(create an object from) an abstract class? An abstract class is an incomplete class and can have abstract methods. These abstract methods do not have implementation(method body), so the will not be allowed to execute. Hence, we cannot create objects from abstract class
  • 32. Abstraction Abstract methods • Abstract methods are methods without method body. • They have the method signature ( or what the method is about), not the implementation (how the method is carried out) Public abstract class Employee{ private string employeeName; public string getName(){ return employeeName; } public abstract string setName(); }
  • 33. Abstraction Public class PartTime extends Employee{ public void setName(string eName){ employeeName = eName;//The abstract method must be implemented } } When inheriting an abstract class, the abstract method must be implemented(method body should be written). The sub class is now a complete class. So this class can be used to create objects.
  • 34. Interfaces  Java does not support multiple inheritance via classes.  But Java allows multiple inheritance via interfaces Parent Class : CalculateArea Parent Class : RegularShape X Child Class : Circle Child Class : Square Interface: CalculateArea Parent Class : RegularShape Child Class : Circle Child Class : Square X
  • 35. Interfaces  Interfaces are implemented as follows: <access_modifier> interface <interface_name>{ final <data type> <variable_name> = <value> abstract <return type> <method_name> (parameter_list); }  All the variables in an interface is final and the methods are abstract compared to a class which doesn’t have such restrictions  All the variables and methods are public  A class can implement multiple interfaces
  • 36. When to create an interface?  Consider the below scenario  A regular shape can be a circle or square.  The common characteristics of a regular shape is  Color  No. of edges  Most of the shapes(regular or irregular) have an area. In such case you can have:  A parent class called shape (inherited by regular and with method CalculateArea  But the area calculation changes from shape to shape  An abstract class with method CalculateArea  Multiple inheritance is not allowed in Java  Interface with abstract method CalculateArea  This can be implemented
  • 37. Abstract Classes and Interfaces Interface Abstract Class Support Multiple Inheritance Do not support multiple inheritance Doesn’t have constructors Have constructors Only has abstract method Has abstract and complete classes Everything is public Can have other access modifiers Cannot be static Can be static