Class Object
OOPS
Encapsulation
Inheritance
2. OBJECTIVES
Polymorphism
Abstraction
Oops
Object-oriented programming (OOP) is a computer
programming model that organizes software design
around data or objects rather than functions and logic.
An object can be defined as a data field that has unique
attributes and behavior.
Object oriented key component
Class -
A class is a blueprint or template that defines the structure
and behavior common to all objects created from that class.
Class contains
Properties - (Data / Attributes)
Functions - (Method / Instructions)
Object - An object is an instance of a class.
Note
A class is a conceptual blueprint, and it doesn't
occupy memory space at runtime.
An object is an instance of a class, and it does occupy
memory space because it represents the actual data
and functionality defined by the class.
Function in apex
A function is a block of code that performs a single
action. Functions are reusable, which helps avoid
repeating instructions. They can also improve the logical
flow of a program and make debugging easier
Acess modifier Return type
Public integer Adding(integer x,integer y)
{
return x+y ;
}
Function name Parameter
Access modifier public indicates that the method is
accessible from outside the class.
ArithmeticOperation add = new ArithmeticOperation();
system.debug(add.Adding(5,6)); // it return 11
If access modifier is private , it cannot access from
outside the class. if u try to access it shows a error
Method is not visible: Integer ArithmeticOperation.Adding(Integer,
Integer)
Return type
This method is declared to return an String, then the
return statement inside the method must return an
String value
Public string Adding(integer x,integer y)
{
return x+y ;
}
Error: Illegal conversion from integer to string
you can use various data types as return types for
methods.
Void: Indicates that the method does not return any value.
Primitive Data Types: Integer ,Decimal , Double , Boolean ,
String , Date , Time , Datetime.
Custom Objects: You can define your own custom classes and
use them as return types.
Collections:
List: List<Type>
Set: Set<Type>
Map: Map<KeyType, ValueType>
SObjects: You can use Salesforce objects (SObjects) as return
types.
Function name
Function name Adding communicates that the purpose
of the function is to perform addition. If someone
encounters this function call in the code, they can
reasonably expect that it adds two integers together.
This clarity is beneficial for both the original developer
and anyone else who reads or works with the code in the
future.
Parameter
Public Integer Adding(integer x,integer y)
{
return x+y ;
}
Parameters: x and y are parameters. Parameters are
variables that are declared in the method signature
and act as placeholders for the actual values that will
be passed into the method when it is called. They
define the input that a method expects.
Arguments: When you call the method and provide
actual values, those values are called arguments.
system.debug(add.Adding(5,6));
Function overloading in apex
Function overloading is a feature in object-oriented
programming languages that allows a class to have
multiple methods with the same name but different
parameter.
public class MathOperations {
public Integer add(integer a, integer b) {
return a + b;
}
public Decimal add(Decimal a, Decimal b) {
return a + b;
}
}
Readability
Overloading improves code readability by using the same
method name for similar task.
Flexibility
Function overloading provides flexibility in handling
different parameter types and numbers, accommodating
diverse scenarios
Consistent
It allows for consistent naming conventions, making the
codebase cohesive and easier to comprehend.
Constructor
A constructor is a special method in a class that initializes
the object's state when an instance of the class is
created. It is automatically invoked upon object creation .
Default constructor
This default constructor is also known as a no-argument
constructor because it doesn't take any parameters.
The primary purpose of the default constructor is to
initialize the object's state with default values or
perform any necessary setup operations.
public class ATM {
private String accountNumber;
private Decimal balance;
// Default constructor with default values
public ATM() {
accountNumber = '123456789';
balance = 1000.00;
}
}
NOTE
Constructor do not have return type.
It support overloading.
Parameterized Constructor
public class Adder {
private Integer number1;
private Integer number2;
private Integer sum;
// Parameterized constructor
public Adder(Integer num1, Integer num2) {
number1 = num1;
number2 = num2;
calculateSum();
}
// Private method to calculate the sum
private void calculateSum() {
sum = number1 + number2;
}
// Getter method to retrieve the sum
public Integer getSum() {
return sum;
}
}
Adder myAdder = new Adder(5, 10);
Why Constructor ?
Constructor play a crucial role in ensuring that objects start
with a well-defined state and are ready for use immediately
after creation.
Static variable and methods
A static variable is a class-level variable that is
associated with the class itself rather than with
instances of the class.
This means that all instances of the class share the
same memory for static variable.
public class MathOperations {
Public static Integer staticNumber = 10;
}
MathOperations obj1 = new MathOperations();
MathOperations.staticNumber += 10 ;
system.debug(MathOperations.staticNumber) ; 20
MathOperations obj2 = new MathOperations();
MathOperations.staticNumber += 10 ;
system.debug(MathOperations.staticNumber) ; 30
Static variable
Common
Memory
es
Sh
ar
ar
Sh
es
Object 1 Object 2
Properties :
Accessed by Class name
Initialized only once
Retain a last value
Uses
Counting Instances - Static variables are often
used to keep track of the number of instances
created for a class
Sharing Data - If you want to share data among
all instances of a class, a static variable can be
used to store that shared data like constant.
Static methods
Static methods are methods that are associated with
a class rather than an object. They are declared using
the keyword static.
We can call static methods without creating an
instance of the class.
String Name= 'Ashvin';
Integer size= Name.length();
system.debug(size);
String class is indeed an inbuilt class, and you can access
its methods without creating an object. length() is a static
method of the String class, so you can call it directly on
the string variable name.
Uses
Static methods are often used to perform operations, not
specific to any particular object, such as mathematical
operations or checking the type of an object.
Encapsulation
Encapsulation refers to the bundling of data
(attributes or properties) and the methods (functions
or procedures) that operate on that data into a single
unit known as a class.
It restricts direct access to some of an object's
components and can prevent unintended
interference or misuse.
With Encapsulation
public class BankAccount {
private Decimal balance;
public BankAccount(initialBalance)
{
this.balance = initialBalance >= 0 ? initialBalance : 0;
}
}
Public methods act as interface for
accessing private data
Without Encapsulation
public class BankAccount {
public Decimal balance;
}
In this example, the balance variable is public, lacking
encapsulation. Direct access to and modification of balance
outside the class may lead to unexpected behavior and
difficulties in maintaining the code.
Why ?
Encapsulation has several positive impacts on
software design and development, contributing to
the overall quality, maintainability, and security of a
system.
Access to sensitive data is restricted, and validation
logic can be implemented to ensure that only valid
operations are performed on the object.
Summary - Encapsulation provides a protective barrier
around the internal state of a class, promoting more robust,
maintainable, and secure code by controlling how external
code interacts with the class's data.
Inheritance
Child classes acquiring properties and
behaviors from a parent class in object
oriented programming.
Inheritance mechanism promotes code
reuse, extensibility, and the creation of a
hierarchy of classes.
Parent class
public virtual class BankTransaction {
protected Decimal balance;
public BankTransaction(Decimal initialBalance)
{
this.balance = initialBalance >= 0 ?
initialBalance : 0;
}
protected Decimal getBalance() {
return balance;
}
}
virtual keyword, then it indicates that this class can be
extended and overrides are allowed.
Private vs Protected
public virtual class MathOperations {
Private Integer staticNumber = 10;
}
public class Calculator extends MathOperations {
public void display(){
system.debug(staticNumber);
}
} Variable is not visible , because
integer staticNumber is private
in parent class
public virtual class MathOperations { Note
Protected Integer staticNumber = 10;
}
When the access modifier is private, accessing
attributes or methods outside the class, including
in anonymous windows, UI, and child classes, is
not allowed.
On the other hand, using the protected access
modifier enables the utilization of attributes or
methods within the child class .
Child class
public class Withdrawal extends BankTransaction {
public Withdrawal(Decimal initialBalance) {
super(initialBalance);
}
public void withdraw(Decimal amount) {
if (amount > 0 && amount <= balance) {
balance -= amount;
System.debug('Remaining balance: ' + balance);
} else {
System.debug('Insufficient funds for withdrawal.');
}
}
}
By using extends, the Withdrawal class gains access to the
fields and methods of the BankTransaction class. In this
specific example, when an instance of Withdrawal is
created, it can perform actions defined in both the
Withdrawal class and the BankTransaction class.
Here, Withdrawal is a subclass of BankTransaction.
The super(initialBalance) statement in the Withdrawal
class constructor is calling the constructor of the
BankTransaction class and passing the initialBalance
parameter to it.
This ensures that the balance property in the
BankTransaction class is initialized with the provided
initialBalance value
Child class
public class Deposit extends BankTransaction {
public Deposit(Decimal initialBalance) {
super(initialBalance);
}
public void deposit(Decimal amount) {
if (amount > 0) {
balance += amount;
System.debug('New balance: ' + balance);
} else {
System.debug('Invalid deposit amount.');
}
}
}
Bank Transaction
Withdrawal Deposit
By extending BankTransaction for Withdraw and Deposit,
you create a clear and organized structure in your code that
promotes maintainability and flexibility.
Each class can focus on its specific functionality while
inheriting and reusing the common behavior from the base
class.
Polymorphism
Common behaviour
Polymorphism allows a
variable, function, or object
to take on multiple forms.
In Apex, there are two main types of polymorphism:
compile-time polymorphism (also known as
method overloading)
Runtime polymorphism (achieved through
method overriding).
Method overloading - Method overloading refers to the ability to
define multiple methods in the same class with the same name
but with different parameters
Method overriding - Method overriding occurs when a subclass
provides a specific implementation for a method that is already
defined in its superclass
The method in the subclass must have the same signature
(name, return type, and parameters) as the method in the
superclass.
It allows a subclass to provide a specific implementation for a
method, which is already defined in its superclass
Method overloading
public virtual class Animal {
public virtual void makeSound()
{
System.debug('Generic Animal Sound');
}
}
public class Dog extends Animal{
public void makeSound(String soundType)
{
if (soundType == 'Bark') {
System.debug('Dog Barks');
} else {
System.debug('Generic Dog Sound');
}
}
Dog sound = new Dog();
sound.makeSound(); Generic Animal Sound
sound.makeSound('Bark'); Dog Barks
Why ?
Overloading allows a method to handle different types of input
data, providing adaptability to various scenarios without
sacrificing the simplicity of method names
Method overriding
public virtual class Animal {
public virtual void makeSound()
{
System.debug('Generic Animal Sound');
}
}
public class Cat extends Animal {
public override void makeSound()
{
System.debug('Cat Meows');
}
}
}
Cat sound= new Cat();
sound.makeSound(); Cat Meows
Why ?
Method overriding in object-oriented programming allows a
subclass to provide a specific implementation for a method
that is already defined in its superclass.
This promotes polymorphism, customization, and
extensibility, ensuring consistent behavior while allowing
dynamic dispatch at runtime.
Abstraction
Process of hiding the
implementation details and
showing only functionality to
the user.
Way to achieve Abstraction:
a) Abstract class
b) Interface
Abstract class - A class which is declared with the abstract
keyword is as a abstract class.
public abstract class Employee {
protected String name;
protected Decimal hourlyRate;
protected Integer hoursWorked;
public Employee(String name, Decimal hourlyRate,
Integer hoursWorked) {
this.name = name;
this.hourlyRate = hourlyRate;
this.hoursWorked = hoursWorked;
}
public abstract Decimal calculateSalary();
}
public abstract Decimal calculateSalary(){
return 0.4 + 0.5 ;
}
Abstract method cannot have a body
Note -
Abstract methods should be override in the child class.
It helps to avoid unwanted definition.
you cannot create instances of abstract classes on their own.
Child class
public class PartTimeEmployee extends Employee {
public PartTimeEmployee(String name, Decimal
hourlyRate, Integer hoursWorked) {
super(name, hourlyRate, hoursWorked);
}
public override Decimal calculateSalary() {
return hourlyRate * hoursWorked;
}
}
Forcing Implementation of Specific Methods.
Abstract classes make it easier to extend functionality in the
future. You can add new abstract methods to the Parent
class, and all child class must implement them. This
promotes a design that can be easily extended without
modifying existing code.
Interface
The interface in apex is a mechanism to achieve abstraction.
There can be only abstract methods in the interface, not
method body. It is used to achieve abstraction and multiple
inheritance in apex.
public interface IShape {
void draw();
}
public interface IColor {
1
String getColor();
}
2
public class Rectangle implements IShape,
IColor {
public void draw() {
System.debug('Drawing a rectangle');
}
public String getColor() {
return 'Red';
}
}
Note - Can you declare variables in Interface in Apex ?
NO but java u can declare the variable in interface.
1 void draw();
Apex interfaces are indeed implicitly public and abstract, so
you don't need to specify those modifiers for methods within
the interface.
Public void draw();
Error: Expecting '}' but was:'Public'
Note - But abstract class support both abstract method and
non- abstract method.
2 The implements keyword is used to indicate that a class
is adopting the behavior specified by one or more
interfaces.
IShape IColor
Rectangle
Note - But abstract class does not support multiple
inheritance.
Scenario for interface
In the scenario related to employees within the company,
common attributes include employeeId and name. The
method displayInfo() can be accessed by both Developers
and Managers. However, the method work() is accessible
only by Developers. How can this access control be
achieved?
Define an interface
called Workable with
a method work().
Create an abstract class
CompanyMember with
Implements
common attributes like
employeeId, name, and a
method displayInfo()
Extends
Developer class
Manager class
public interface Workable {
void work();
}
Common attributes and methods
public abstract class CompanyMember {
protected Integer employeeId;
protected String name;
public CompanyMember(Integer
employeeId, String name) {
this.employeeId = employeeId;
this.name = name;
}
public abstract void displayInfo();
}
Summary - Code introduces a Workable interface with a
work() method. An abstract class CompanyMember is
defined, containing common attributes (employeeId and
name) and an abstract method (displayInfo()) to be
implemented by subclasses.
Developer class
public class Developer extends
CompanyMember implements Workable {
public Developer(Integer employeeId,
String name) {
super(employeeId, name);
}
public override void displayInfo()
{
System.debug('Developer - Employee ID: '
+ employeeId + ', Name: ' + name);
}
public void work() {
System.debug('Developer is working on
code.');
}
}
Summary - The code defines a Developer class that
extends CompanyMember and implements the Workable
interface. The class has a constructor to initialize employee
details. It overrides the displayInfo() method to print
developer information and implements the work() method
to indicate coding work.
Manager class
public class Manager extends
CompanyMember {
public Manager(Integer
employeeId, String name) {
super(employeeId, name);
}
public override void
displayInfo() {
System.debug('Manager - Employee ID: ' +
employeeId + ', Name: ' + name);
}
}
Summary - The code defines a Manager class that extends
CompanyMember. It has a constructor to initialize
employee details. The class overrides the displayInfo()
method to print manager information.
Apex basics Part-3
loading...