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
}
}
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
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
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
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