Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

OOP Session 2 PT 1 Slides

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 32

Session 2

Declarations and Access Control


Declarations and Access Control

Objectives
In this Chapter you will learn to:
 Create a Class in Java
 Define a Constructor
 Use access Specifiers and Modifiers
Declare and define Classes and Interfaces

 A class is just a platform that we use to create objects in Java and we have some rules that
we need to follow when coming up with a class name like the class name should start with
an alphabet letter not a number and the first letter should be capitalized and the name
should be a noun, for example
public class Student{
}
 The code in a class should be put inside the curly brackets as shown above, the first
bracket is the opening and the last is the one that closes the class.
 Let us consider this example to help us come up with a class.
Declare and define Classes and Interfaces

 void calculate();
 void average();
Adding method to a class
 A method is just a group of statements that perform a specific task and the method name should use a verb. Let us come
up with a method example
 public class Master {
public void Master() {
String name = “James”;
int age = 60;
double salary = 789.70;
System.out.println(“ My name is “ + name);
System.out.println(“ My age is “ + age);
System.out.println(“ My salary is “ + salary);
}
 The method signature tells us that this method calculate will not return any value because of the void keyword but if we
replaced the void with String it means the method will return a string value.
Adding method to a class
 Let us create another method called sum() which should add two numbers:
public void sum() {
float number1 = 7.99f;
float number2 = 8.77f;
float total = number1 + number2;
System.out.println(“ The total is “ +total)
}
Adding method to a class
 Let us call the methods in the main method:
public static void main(String[] args) {
Student p = new Student();
p.calculate();
p.sum();
}
}
Activity
 Create a class with two methods. The first method will declare 4 numbers and find their
average
 The second method will calculate the monthly salary for an employee by the name
Thomas. Thomas worked for 20 days and each day he gets 200rtgs. The tax is charged at
12% . Calculate his net salary.
Defining Constructors

 Constructor is a block of code that initializes the newly created object. A constructor
resembles an instance method in java but it’s not a method as it doesn’t have a return type.
 Constructor has same name as the class and looks like this in a java code
 public class January{
 January() { //constructor
 In the main method
 January p = new January();
 The new keyword creates the object for the January class and invokes the constructor to
initialize this created object
Defining Constructors

 We have three types of constructors:


A default constructor
 If you do not implement any constructor in your class, Java compiler inserts a default
constructor into your code on your behalf.
 This constructor is known as default constructor.
 You would not find it in your source code as it would be inserted into the code during
compilation and exists in .class file.
Defining Constructors

no-arg constructor:
 Constructor with no arguments is known as no-arg constructor.
 The signature is same as default constructor, however body can have any code unlike default
constructor where the body of the constructor is empty.
 public class January{
 January(){
 System.out.println(“This is a no – arg constructor”);
 }
 In the main method
 new January();
Defining Constructors

A parameterized constructor
 This is a constructor with parameters inside, let us consider our
Teacher class above and come up with a parameterized constructor.
 Parameter: variable named in the method definition that is
standing in for a value that will be supplied when the method is
called.
 Argument: is a value that is supplied when a method is called
 this keyword: If local variables and instance variables are the
same, we use the this keyword
.
Defining Constructors

public class Master {


int age;
String name;
Master( int studentAge, String studentName) {
this.age = studentAge;
this.name = studentName;
System.out.println(" The student age is " + studentAge+ " and name " +
studentName);
}
Master( int studentAge, String studentName,
public static void main(String[] args) {
Janu p = new Janu(50,"Martha");
Janu p1 = new Janu(90,"John"); }}
Defining Constructors

Constructor overloading
 At times you may want to come up with another constructor but with a
different number of parameters from the first one that we did, this is called
constructor overloading.
 The compiler at run time will be able to separate the constructors basing on
the number of parameters specified in the constructor and the sequence of
data types.
 For example using the same class of Teacher we can use this constructor:
public class January {
int age;
String name;
int age2;
January( int studentAge, String studentName) {
this.age = studentAge;
this.name = studentName;
System.out.println(" The student age is " + studentAge+ " and name " + studentName);
}
January(int teacherAge){
this.age2 = teacherAge;
System.out.println(" The teacher age is " + teacherAge);
}
public static void main(String[] args) {
January p = new January(50,"Martha");
January p1 = new January(100);
}
Defining Constructors

Difference between a constructor and a method


Re-Cap Activity
The recap is based on the topics we covered: variable declaration, Method and
Constructor.
Activity
Create a class called Recap
You are required to calculate the area of a Circle and a Triangle.
You need to come up with variables for the Circle and the Triangle
Create a constructor to initialize the variables
Create two methods to calculate and print the area of the Circle and the Triangle
Note pi = 3.14

Task duration 25 mins


Instance Variables and methods
Instance variable
 An instance variable is basically a variable declared inside a class but outside a method and even a constructor.
 The instance variable can be given the access modifiers.
 You will find out that these instance variables have default values associated with them like for example for
numbers the value is 0 while for object references it is null.
 Let us look at this example we used before:
public class January {
String name; //instance variable
int age; //instance variable
double salary; //instance variable
}
Instance Variables and methods
Instance method
 An instance method is a method declared without the static keyword like for example:

public void calculate() {


}
 However, if you create a method with a static keyword then it is called a class method for example:

public static int calculate() {


return age;
}
}
public class January {
static double PI = 3.14;
public static double calculate(){
double area = PI * 5;
return area;
}
public static void main(String[] args) {
System.out.println(calculate());
}}
Local variables
 These are variables declared inside a method or constructor and they are only visible in
that method or constructor.
 We cannot use access modifiers for local variables like static or final keywords.
 The local variables do not have default values so the rule is declare the local variable and
assign a value to it before you use the variable.
Example:
public void calculate() {
int age = 10; //age is an example of a local variable
}
Class variables
 Class variables are also called static variables because they are declared with a static keyword
outside a method.
 The class variables are not used very often except when you want to come up with a constant
variable name since the value of that variable name will never change during the program
execution.
 Class variables have default values just the same as the instance variables.
 If the class variable is declared as public static final then the constants should be in upper case
for example:
public class Teacher {
public static final double RATE = 4.56;
}
Access Specifiers and Modifiers
 Access specifiers are there to regulate access to fields, classes and methods.
 So if you use the specifier you restrict how the class, field or method will be invoked by a method or
even a sub class.
 We have four specifiers and these are public, private, protected and default .
Public
 When we use the public keyword it means the class, method or field can be accessed everywhere by any
method or class even if the class is not in the same package
Example:
public class Teacher {
public void calculate() {
}
}
Access Specifiers and Modifiers
Private
 When you use the private specifier we restrict access to the method or field so that they can only be accessed within the same class but
not accessed from subclasses.
 You will find out that when we use the private keyword we are enforcing encapsulation and data hiding from the outside world.
Example:
public class January {
private int age;
private String name;
} We can not declare top level class as private. Java allows only public and default modifier for top level classes in java. Inner classes
can be private.
 It means the variable names age and name can only be accessed within the class January only.
Protected
 If we declare a method or variable as protected it means they can be accessed by sub classes or class within the package of the
member’s class.
 However the protected keyword cannot be applied to a class or interface.
Access Specifiers and Modifiers
Default
 At times we come up with variable name, method and class and do not give the specifier for that element the
element will be given default accessibility but we do not have a default access specifier keyword in Java.
 This means that we will be able to access a variable, method or class which belongs in the same package but
not from another package.
Example:
class Teacher {
int age;
void calculate() {
}
}
Modifiers
 These are the keywords that we use at the beginning of statements in Java to change the statement’s meaning. To use
this modifier what we need to do is just add the keyword of the modifier at the beginning of class name, method or
variable.
Example:
public class Teacher {
private int age;
private String name;
}
 The modifiers are the ones shown in bold that is the public and the private keywords.
Access control modifiers:
 These access control modifiers set control on the visibility of the class, method or variable like for example: public,
private, protected and default.
Modifiers
Non access modifiers

 Static modifier is used to when coming up with class, method and variables
 Final modifier used also on class, method and variables
 The final modifier indicates that an object is fixed and cannot be changed. When you use
this modifier with a class-level object, it means that the class can never have subclasses.
When you apply this modifier to a method, the method can never be overridden. When you
apply this modifier to a variable, the value of the variable remains constant
Modifiers
 Abstract modifier used on classes and methods
 The abstract modifier is placed before classes or methods. For a class, it means that it cannot be directly
instantiated, but has to be subclassed. For a method, it means that it does not have an implementation in the
class, but has to be implemented in a subclass. It cannot be applied to variables

 Synchronized and volatile modifiers these are used on threads


 The synchronized keyword used to indicate that a method can be accessed by only one thread at a time
 The volatile modifier is used to let the JVM know that a thread accessing the variable must always merge its
own private copy of the variable with the master copy in the memory
Accessors and Mutators
 Data encapsulation is enforced through the use of accessor and mutator methods.
 The accessor is also called the getter and the mutator is also called the setter.

Let us look at this example


public class Teacher {
private int age;
private String name;
public int getAge() { //example of an getter method
return age;
}
Accessors and Mutators
public String getName() { //example of a getter method
return name;
}
public void setAge( int age) { //example of a setter method
this.age = age;
}
public void setName( String name) { //example of a setter method
this.name = name;
}
public static void main(String[] args) {
p.setAge(90);
p.setName(“January");
System.out.println("My name is " +p.getName()+" and my age is " +p.getAge()); } }
 The process of doing the setter and the getter looks tiring but the bottom line is we want to hide the data as much as possible from the outside
world.
End of Session 2 part 1

You might also like