Agenda
Scope means life span and its visibility.
Ans:Local variables<Method parameters<Instance variables<Class Variables
Object's Life Cycle
Ans: By assigning null or reassigning the reference variable.
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
Rules to remember for method parameters.
Overloaded methods accept different lists of arguments.
It can differ by following
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:
Rules to remember.
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
To utilize those objects of Student,class StudentUtility contains for calculating the age.
Bundling the data with methods in Student class.
As of now, it does not provide any data protection or security.
Why Data Hiding is Important.
student.age= -20;
We just have a Student with negative age??
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.
0
10
0
Passing object refernces to methods
There are two main cases:
In this case, the state of the object, which was passed on to the method, remains intact(same).
Let's look at example:
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
Garbage Collection
- Scope of variables
- Object's Life cycle
- Method overloading
- Constructor overloading
- Encapsulation
- Impact of reference and primitive value upon an object.
- Garbage basics
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: 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.
- public void method(){
- int value;// this is local variable.Its life starts here.
- System.out.println(val) //Compiler Error
- //End here}
- 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.
- 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.
- 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.
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.
- 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.
Ans: By assigning null or reassigning the reference variable.
- Student student = new Student();
- Student student1 =new Student();
- student =null; // object is dereferenced.
- student=student1; // object is dereferenced.
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
- 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.
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
- 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 :
- void setAge(int val){
- return ;
- age =val;//Compiler Error; return statement must be the last statement to execute in a method.
- }
- 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.
- 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)
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)
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:
- Student(){}
- Student(int rollNo,String name){}
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).
- 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.
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.
- 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 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.
- public class Student{
- public String name;
- public Date dob;
- }
To utilize those objects of Student,class StudentUtility contains for calculating the age.
- public class StudentUtility{
- public static int calculateAge(Date dob){
- int age=0;
- //write logic here
- return age;
- }
- }
Bundling the data with methods in Student class.
- public class Student{
- public String name;
- public Date dob;
- public int calculateAge(Date dob){
- int age=0;
- //write logic here
- return age;
- }
- //getter and setter methods
- }
As of now, it does not provide any data protection or security.
Why Data Hiding is Important.
- Let's look at below example
- public class Student{
- public String name;
- public int age;
- public void setAge(){
- if(age < 0){
- System.out.println("Age can't be lesser than 0");
- throw new IllegalArgumentException();
- }
- public int getAge(){
- return age;
- }
- }
- public static void main(String[] args){
- Student student = new Student();
- student.age = -20;
- System.out.println(emp.getAge());
- }
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.
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.
- public class Student{
- public int age;
- public void modifyAge(int a){
- a=a+10;
- System.out.println(a);
- }
- }
- public static void main(String[] args){
- Student student = new Student();
- System.out.println(student.age);//0
- student.modifyAge(student.age);//10
- System.out.println(student.age);//0
- }
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.
In this case, the state of the object, which was passed on to the method, remains intact(same).
Let's look at example:
- class Student{
- private String name;
- Student(String newName){
- name=newName;
- }
- public String getName(){
- return name;
- }
- public void setName(String val){
- name=val;
- }
- }
- class Test{
- public static void swap(Student s1,Student s2){
- Student temp=s1;
- s1=s2;
- s2=temp;
- }
- public static void main(String[] args){
- Student student1 = new Student("Kalawati");
- Student student2 = new Student("Amit");
- System.out.println(student1.getName()+":"+student2.getName());//Kalawati : Amit
- swap(student1,student2);
- System.out.println(student1.getName()+":"+student2.getName());//Kalawati : Amit
- }
- }
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
- class Student{
- private String name;
- Student(String newName){
- name=newName;
- }
- public String getName(){
- return name;
- }
- public void setName(String val){
- name=val;
- }
- }
- class Test{
- public static void resetValueOfName(Student s1){
- s1.setName("Anu");
- }
- public static void main(String[] args){
- Student student1 = new Student("Kalawati");
- System.out.println(student1.getName());//Kalawati
- resetValueOfName(student1);
- System.out.println(student1.getName());//Anu
- }
- }
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