Pages

Sunday 4 August 2019

Methods & encapsulation

Agenda
  1. Scope of variables
  2. Object's Life cycle
  3. Method overloading
  4. Constructor overloading
  5. Encapsulation
  6. Impact of reference and primitive value upon an object.
  7. Garbage basics
Scope of variables
Scope means life span and its visibility.
  • Local variables(aka method-local variables)
  • Method parameters(aka method arguments)
  • Instance variables(aka attributes,fields and non-static variables)
  • Class variables(aka static variables)
Local Variables
  • Local variables: Those variables which resides in method, if,else,switch,for,do,while,try-catch-finally static and instance blocks.
  • Used to store the intermediate results of a calculation.
  • Visibility: Within method block. We can't access local variables outside of the method block.
  • Local variables get memory in the stack.
  • You can use only the final modifier with the local variable.
Note: You can't access local variable before initializing it otherwise Compiler Error.
  1. public void method(){
  2. int value;// this is local variable.Its life starts here.
  3. System.out.println(val) //Compiler Error
  4. //End here}
Method parameters
  • The variables that accept values in a method signature are called method parameters.
  • Method signature = method name + argument e.g: add(int a,int b)
  • Used to pass values to a method. These values can be manipulated and may also be assigned to instance variables.
  • Visibility: Within the method block only.
  • It will get memory in the stack.
  • You can use only the final modifier with the local variable.
Instance Variables
  • The instance is another name for an object.
  • Used to store the state of an object. These are the values that need to be accessed by multiple methods.
  • Visibility: Within the class. It can be accessed within any method, if, else, switch, for, do, while, try-catch-finally, and instance block.
  • It will get memory when the object is created and destroyed when the object is destroyed. Hence it's life span is object life.
  • It will get memory in heap.
Class Variable
  • A class variable is defined by using the keyword static.
  • Used to store values that should be shared by all the objects of a class.
  • It belongs to a class, not to individual objects of the class.
  • It is shared(same copy) cross all objects.
  • It will get memory when class is loaded.
  • It will get memory in the method area.
  • Its scope is the largest among variables.
Q.Arrange the variables scope wise(ascending order)
Ans:Local variables<Method parameters<Instance variables<Class Variables

Object's Life Cycle
  • An object comes into the picture when you use the keyword new.
    E.g.: Student student = new Student(); // Here an object is born.
  • Here the object is accessible. You can access its members, using the reference variable(student).
  • Note: Declaration + Initialization of an object = object is created.
Declaration of an object
  • Student student; //Here object is not born.
  • Here the object is not accessible.
  • If you want to access the members of the class using the reference variable(student), you will get NullPointerException at runtime.
Q.How to deference an object?.
Ans: By assigning null or reassigning the reference variable.
  1.     Student student = new Student();
  2.     Student student1 =new Student();
  3.     student =null; // object is dereferenced.
  4.     student=student1; // object is dereferenced.
Note: Dereferenced objects are eligible for garbage collection.

1.Student student = new Student();(object is born) 
2.student = null;(dereference the object,Now this is eligible for garbage collection)
3.garbage collector will destroy the object when required.(end of life)

Create methods with arguments and return values
 Components of a method
  • Return type
  • Method parameters
  • return statement
  • Access Modifiers
  • non-access modifiers
Return Type
  • A return type of a method states the type of value that a method will return.
  • A method may or may not return a value.
  • One that doesn't return value has a return type void.
  • A method can return a primitive value, class, interface.
Method Parameters
Rules to remember for method parameters.
  • You can define multiple parameters for a method.
  • The method parameter can be a primitive type or object.
  • The method's parameters are separated by commas.
  • Example : m1(int a,int b,Student student) // valid , m1(int a,b,Student student) // invalid
Return statement
  • A return statement is used to exit from a method with or without a value.
  • For a method that returns a value, the return statement must be followed immediately by a value.
  • For a method that doesn't return a value(return type is void), the return statement must not be followed by the return value.
  • If the compiler determines that a return statement isn't the last statement to execute in a method, the method will fail to compile.

    Example :
  1.   void setAge(int val){
  2.            return ;
  3.           age =val;//Compiler Error; return statement must be the last statement to execute in a method.
  4. }
Method Overloading
  • Overloaded methods are methods with the same name but different method parameter(argument) lists.
  • Method overloading is also known as early binding/static polymorphism.
  • In method overloading, the resolution happens at compile-time based on the reference type.
Rules
  • Parameter(argument) lists must be different from other methods.
  • Method overloading is not applied on method return type, method modifiers
  • Method overloading is applicable only on method signature(method name+parameter list)
Argument List
Overloaded methods accept different lists of arguments.
It can differ by following
  • The number of arguments.
  • Types of parameters.
  • Position of arguments(based on argument type, not variable names)
Constructor Overloading
Default constructor
By default, the Compiler inserts the default constructor/ no-argument constructor in the class.
If you explicitly put any constructor then the compiler will not put default constructor in the class.
User define constructor
The constructor which is defined by you is called the user define the constructor.
Example:
  1. Student(){}
  2. Student(int rollNo,String name){}
Note: Constructor overloading you can do as method overloading.
Rules to remember.
  • Overloaded constructors must be defined using different argument lists.
  • A constructor can call another overloaded constructor by using the keyword this.
  • A constructor can't invoke a constructor by its class's name.
  • If you want to invoke another overloaded constructor then it must be the first statement in a constructor.
  • You can't call multiple constructors from a constructor.
  • A constructor can't be invoked from a method(except by instantiating a class using the new keyword).
Encapsulation
  • A mechanism of wrapping the data(variables) and code acting on the data(methods) together as a single unit
  • In encapsulation the variables of a class will be hidden from other classes and can be accessed only through the methods of their current class, therefore it is also known as data hiding.
To achieve encapsulation in Java
Declare the variables of a class as private.
Provide public setter and getter methods to modify and view the values of the variables.
Benefits of Encapsulation
  • The fields of a class can be made read-only or write-only.
  • A class can have total control over what is stored in its fields.
  • The users of a class do not know how the class stores its data.
  • A class can change the data type of a field and users of the class do not need to change any of their code.
Data Hiding
  • An object should not disclose all its attributes and behavior.
  • It should reveal only the required methods which the other object requires to interact with.
  • These methods which need to be exposed to other objects define the interface of the class.
  • Example: An object to sort a list of employees should only expose the method which accepts the list of employees as a parameter and the algorithm to sort the employees should be hidden from another object.
Encapsulation is not Information Hiding
  • Encapsulation is just the container we need to place a similar item like fields and methods.
  • While Data Hiding is protecting your data from the outside world(clients and consumers).
  • Data hiding is not possible without Encapsulation. You can't hide your data without putting it in some form of container.
  • But yes Encapsulation is possible without hiding your data. Put all things public and you can see the effect.
  • Keeping instance variable and getters/setters method as the public is still Encapsulation but this way we are not achieving Data Hiding.
Consider a class Student.
  1. public class Student{
  2. public String name;
  3. public  Date dob;
  4. }
At present Student is nothing but a bag of data.
To utilize those objects of Student,class StudentUtility contains for calculating the age.
  1. public class StudentUtility{
  2. public static int calculateAge(Date dob){
  3. int age=0;
  4. //write logic here
  5. return age;
  6. }
  7. }
Here Student is simple data structure and StudentUtility is repository of methods.
Bundling the data with methods in Student class.
  1. public class Student{
  2. public String name;
  3. public Date dob;
  4. public int calculateAge(Date dob){
  5. int age=0;
  6. //write logic here
  7. return age;
  8. }
  9. //getter and setter methods
  10.  }
This bundling is called Encapsulation.
As of now, it does not provide any data protection or security.
Why Data Hiding is Important.
  1. Let's look at below example
  2. public class Student{
  3. public String name;
  4. public int age;

  5. public void setAge(){
  6. if(age < 0){
  7. System.out.println("Age can't be lesser than 0");
  8. throw new IllegalArgumentException();
  9. }
  10. public int getAge(){
  11. return age;
  12. }
  13. }
Now consider the below main method:
  1. public static void main(String[] args){
  2. Student student = new Student();
  3. student.age = -20;
  4. System.out.println(emp.getAge());
  5. }
In main method below line is offending
student.age= -20;
We just have a Student with negative age??
  • To avoid such errors. Keep the information(variables) hidden(private) from outer world and expose setter
  • behaviors where a level of control can be implemented.
  • Like we have the public setAge() method wherein we are throwing IllegalArgumentException in case someone tries to set the illegal value to age.
Impact of reference and primitive value upon an object
When Passing Primitive to methods
When you pass a primitive variable to a method, its value remains the same after the execution of the method.
Let's look at below example.
  1. public class Student{
  2.  public int age;
  3. public void modifyAge(int a){
  4.  a=a+10;
  5.  System.out.println(a);
  6. }
  7. }
  8. public  static void main(String[] args){
  9. Student student = new Student();
  10. System.out.println(student.age);//0
  11. student.modifyAge(student.age);//10
  12. System.out.println(student.age);//0
  13. }
The output of the above code is:
0
10
0
Passing object refernces to methods
There are two main cases:
  • when a method reassigns the object reference passed to it to another variable.
  • When a method modifies the state of the object reference passed to it.
When methods reassign the object references passed to them.
In this case, the state of the object, which was passed on to the method, remains intact(same).
Let's look at example:
  1. class Student{
  2. private String name;
  3. Student(String newName){
  4.  name=newName;
  5. }
  6. public String getName(){
  7. return name;
  8. }
  9. public void setName(String val){
  10. name=val;
  11. }
  12. }
Think about the output of the following code??
  1. class Test{

  2. public static void swap(Student s1,Student s2){
  3. Student temp=s1;
  4. s1=s2;
  5. s2=temp;
  6. }
  7. public static void main(String[] args){
  8. Student student1 = new Student("Kalawati");
  9. Student student2 = new Student("Amit");
  10. System.out.println(student1.getName()+":"+student2.getName());//Kalawati : Amit
  11. swap(student1,student2);
  12. System.out.println(student1.getName()+":"+student2.getName());//Kalawati : Amit

  13. }
  14. }
Fig 1.1


When methods modify the state of the object references passed to them
In this case, the state of the object which was passed on to the method, modified and reflected in the calling method.
Let's look at example
  1. class Student{
  2. private String name;
  3. Student(String newName){
  4.  name=newName;
  5. }
  6. public String getName(){
  7. return name;
  8. }
  9. public void setName(String val){
  10. name=val;
  11. }
  12. }
Think about the output of the following code??
  1. class Test{

  2. public static void resetValueOfName(Student s1){
  3. s1.setName("Anu");
  4. }
  5. public static void main(String[] args){
  6. Student student1 = new Student("Kalawati");
  7. System.out.println(student1.getName());//Kalawati
  8. resetValueOfName(student1);
  9. System.out.println(student1.getName());//Anu
  10. }
  11. }
Fig 2

Garbage Collection
  • Garbage Collection: It is a process of collecting unused objects from the memory(heap).
  • And the actor who is collecting this garbage is called Garbage Collector.
  • Garbage Collection is an automatic process, JVM will do this process with the help of the Garbage collector.
  • As a developer, you can't start the execution of Java's garbage collector. You can only request it to be started by calling
  • System.gc() or Runtime.getRuntime().gc().But calling this method doesn't guarantee when the garbage collector would start.
Next Topic:  INHERITANCE