Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...

Full Transcript

BCA Sy 2023 Class Object and Method COCSIT, Latur UNIT II Classes, Objects and Methods 2.1 Introduction Defining Class,...

BCA Sy 2023 Class Object and Method COCSIT, Latur UNIT II Classes, Objects and Methods 2.1 Introduction Defining Class, Fields Declaration, Methods Declaration, Creating Objects 2.2 Visibility controls 2.3 Use of ‘this’ Keyword 2.4 Method Parameters and Method Overloading 2.5 Constructor and Constructor Overloading 2.6 Static Members 2.7 Finializer Method 2.8 Inheritance and It’s Types 2.9 Method Overriding 2.10 Final Variable, Method and Final Class Introduction: In object-oriented programming technique, we design a program using objects and classes. An object in Java is the physical as well as a logical entity, whereas, a class in Java is a logical entity only. What is an object in Java? An entity that has state and behavior is known as an object e.g., chair, bike, marker, pen, table, car, etc. It can be physical or logical (tangible and intangible). The example of an intangible object is the banking system. 1 BCA Sy 2023 Class Object and Method COCSIT, Latur An object has three characteristics: Play Video o State: represents the data (value) of an object. o Behavior: represents the behavior (functionality) of an object such as deposit, withdraw, etc. o Identity: An object identity is typically implemented via a unique ID. The value of the ID is not visible to the external user. However, it is used internally by the JVM to identify each object uniquely. For Example, Pen is an object. Its name is Reynolds; color is white, known as its state. It is used to write, so writing is its behavior. An object is an instance of a class. A class is a template or blueprint from which objects are created. So, an object is the instance(result) of a class. Object Definitions: o An object is a real-world entity. o An object is a runtime entity. o The object is an entity which has state and behavior. o The object is an instance of a class. What is a class in Java? A class is a group of objects which have common properties. It is a template or blueprint from which objects are created. It is a logical entity. It can't be physical. A class in Java can contain: o Fields o Methods o Constructors o Blocks o Nested class and interface Syntax to declare a class: class { field; method; } Instance variable in Java A variable which is created inside the class but outside the method is known as an instance variable. Instance variable doesn't get memory at compile time. It gets memory at runtime when an object or instance is created. That is why it is known as an instance variable. 2 BCA Sy 2023 Class Object and Method COCSIT, Latur Method in Java In Java, a method is like a function which is used to expose the behavior of an object. Advantage of Method o Code Reusability o Code Optimization new keyword in Java The new keyword is used to allocate memory at runtime. All objects get memory in Heap memory area. Object and Class Example: main within the class In this example, we have created a Student class which has two data members id and name. We are creating the object of the Student class by new keyword and printing the object's value. Here, we are creating a main() method inside the class. //Java Program to illustrate how to define a class and fields //Defining a Student class. class Student{ //defining fields int id;//field or data member or instance variable String name; //creating main method inside the Student class public static void main(String args[]){ //Creating an object or instance Student s1=new Student();//creating an object of Student //Printing values of the object System.out.println(s1.id);//accessing member through reference variable System.out.println(s1.name); } } Object and Class Example: main outside the class In real time development, we create classes and use it from another class. It is a better approach than previous one. Let's see a simple example, where we are having main() method in another class. 3 BCA Sy 2023 Class Object and Method COCSIT, Latur We can have multiple classes in different Java files or single Java file. If you define multiple classes in a single Java source file, it is a good idea to save the file name with the class name which has main() method. //Java Program to demonstrate having the main method in //another class //Creating Student class. class Student{ int id; String name; } //Creating another class TestStudent1 which contains the main method class TestStudent1{ public static void main(String args[]){ Student s1=new Student(); System.out.println(s1.id); System.out.println(s1.name); } } Three Ways to initialize object There are three ways to initialize object in Java. 1. By reference variable 2. By method 3. By constructor 1) Object and Class Example: Initialization through reference Initializing an object means storing data into the object. Let's see a simple example where we are going to initialize the object through a reference variable. class Student{ int id; String name; } class TestStudent2{ public static void main(String args[]){ Student s1=new Student(); s1.id=101; s1.name="Sonoo"; System.out.println(s1.id+" "+s1.name);//printing members with a white space } } We can also create multiple objects and store information in it through reference variable. 4 BCA Sy 2023 Class Object and Method COCSIT, Latur class Student{ int id; String name; } class TestStudent3{ public static void main(String args[]){ //Creating objects Student s1=new Student(); Student s2=new Student(); //Initializing objects s1.id=101; s1.name="Sonoo"; s2.id=102; s2.name="Amit"; //Printing data System.out.println(s1.id+" "+s1.name); System.out.println(s2.id+" "+s2.name); } } 2) Object and Class Example: Initialization through method In this example, we are creating the two objects of Student class and initializing the value to these objects by invoking the insertRecord method. Here, we are displaying the state (data) of the objects by invoking the displayInformation() method. class Student{ int rollno; String name; void insertRecord(int r, String n){ rollno=r; name=n; } void displayInformation(){System.out.println(rollno+" "+name);} } class TestStudent4{ public static void main(String args[]){ Student s1=new Student(); s1.insertRecord(111,"Karan"); s1.displayInformation(); }} 5 BCA Sy 2023 Class Object and Method COCSIT, Latur As you can see in the above figure, object gets the memory in heap memory area. The reference variable refers to the object allocated in the heap memory area. Here, s1 and s2 both are reference variables that refer to the objects allocated in memory. 3) Object and Class Example: Initialization through a constructor Object and Class Example: Employee Let's see an example where we are maintaining records of employees. File: TestEmployee.java class Employee{ int id; String name; float salary; void insert(int i, String n, float s) { id=i; name=n; salary=s; } void display(){System.out.println(id+" "+name+" "+salary);} } public class TestEmployee { public static void main(String[] args) { Employee e1=new Employee(); e1.insert(101,"ajeet",45000); e1.display(); }} 6 BCA Sy 2023 Class Object and Method COCSIT, Latur Object and Class Example: Rectangle There is given another example that maintains the records of Rectangle class. class Rectangle{ int length, width; void insert(int l, int w){ length=l; width=w; } void calculateArea(){System.out.println(length*width);} } class TestRectangle1{ public static void main(String args[]){ Rectangle r1=new Rectangle(); r1.insert(11,5); r1.calculateArea(); } } What are the different ways to create an object in Java? There are many ways to create an object in java. They are: o By new keyword o By newInstance() method o By clone() method o By deserialization o By factory method etc. Anonymous object Anonymous simply means nameless. An object which has no reference is known as an anonymous object. It can be used at the time of object creation only. If you have to use an object only once, an anonymous object is a good approach. For example: new Calculation();//anonymous object Calling method through a reference: Calculation c=new Calculation(); c.fact(5); Calling method through an anonymous object new Calculation().fact(5); 7 BCA Sy 2023 Class Object and Method COCSIT, Latur Access Modifiers in Java There are two types of modifiers in Java: access modifiers and non-access modifiers. The access modifiers in Java specifies the accessibility or scope of a field, method, constructor, or class. We can change the access level of fields, constructors, methods, and class by applying the access modifier on it. There are four types of Java access modifiers: 1. Private: The access level of a private modifier is only within the class. It cannot be accessed from outside the class. 2. Default: The access level of a default modifier is only within the package. It cannot be accessed from outside the package. If you do not specify any access level, it will be the default. 3. Protected: The access level of a protected modifier is within the package and outside the package through child class. If you do not make the child class, it cannot be accessed from outside the package. 4. Public: The access level of a public modifier is everywhere. It can be accessed from within the class, outside the class, within the package and outside the package. There are many non-access modifiers, such as static, abstract, synchronized, native, volatile, transient, etc. Here, we are going to learn the access modifiers only. Understanding Java Access Modifiers Let's understand the access modifiers in Java by a simple table. Access within within outside package outside Modifier class package by subclass only package Private Y N N N Default Y Y N N Protected Y Y Y N Public Y Y Y Y 1) Private The private access modifier is accessible only within the class. 8 BCA Sy 2023 Class Object and Method COCSIT, Latur Role of Private Constructor If you make any class constructor private, you cannot create the instance of that class from outside the class. For example: class A{ private A(){}//private constructor void msg(){System.out.println("Hello java");} } public class Simple{ public static void main(String args[]){ A obj=new A();//Compile Time Error } } Note: A class cannot be private or protected except nested class. 2) Default If you don't use any modifier, it is treated as default by default. The default modifier is accessible only within package. It cannot be accessed from outside the package. It provides more accessibility than private. But, it is more restrictive than protected, and public. 3) Protected The protected access modifier is accessible within package and outside the package but through inheritance only. The protected access modifier can be applied on the data member, method and constructor. It can't be applied on the class. It provides more accessibility than the default modifer. 4) Public The public access modifier is accessible everywhere. It has the widest scope among all other modifiers. Method in Java In general, a method is a way to perform some task. Similarly, the method in Java is a collection of instructions that performs a specific task. It provides the reusability of code. We 9 BCA Sy 2023 Class Object and Method COCSIT, Latur can also easily modify code using methods. In this section, we will learn what is a method in Java, types of methods, method declaration, and how to call a method in Java. What is a method in Java? A method is a block of code or collection of statements or a set of code grouped together to perform a certain task or operation. It is used to achieve the reusability of code. We write a method once and use it many times. We do not require to write code again and again. It also provides the easy modification and readability of code, just by adding or removing a chunk of code. The method is executed only when we call or invoke it. The most important method in Java is the main() method.. Method Declaration The method declaration provides information about method attributes, such as visibility, return-type, name, and arguments. It has six components that are known as method header, Method Signature: Every method has a method signature. It is a part of the method declaration. It includes the method name and parameter list. Access Specifier: Access specifier or modifier is the access type of the method. It specifies the visibility of the method. Java provides four types of access specifier: o Public: The method is accessible by all classes when we use public specifier in our application. 10 BCA Sy 2023 Class Object and Method COCSIT, Latur o Private: When we use a private access specifier, the method is accessible only in the classes in which it is defined. o Protected: When we use protected access specifier, the method is accessible within the same package or subclasses in a different package. o Default: When we do not use any access specifier in the method declaration, Java uses default access specifier by default. It is visible only from the same package only. Return Type: Return type is a data type that the method returns. It may have a primitive data type, object, collection, void, etc. If the method does not return anything, we use void keyword. Method Name: It is a unique name that is used to define the name of a method. It must be corresponding to the functionality of the method. Suppose, if we are creating a method for subtraction of two numbers, the method name must be subtraction(). A method is invoked by its name. Parameter List: It is the list of parameters separated by a comma and enclosed in the pair of parentheses. It contains the data type and variable name. If the method has no parameter, left the parentheses blank. Method Body: It is a part of the method declaration. It contains all the actions to be performed. It is enclosed within the pair of curly braces. Naming a Method While defining a method, remember that the method name must be a verb and start with a lowercase letter. If the method name has more than two words, the first name must be a verb followed by adjective or noun. In the multi-word method name, the first letter of each word must be in uppercase except the first word. For example: Single-word method name: sum(), area() Multi-word method name: areaOfCircle(), stringComparision() It is also possible that a method has the same name as another method name in the same class, it is known as method overloading. 11 BCA Sy 2023 Class Object and Method COCSIT, Latur Types of Method There are two types of methods in Java: o Predefined Method o User-defined Method Predefined Method In Java, predefined methods are the method that is already defined in the Java class libraries is known as predefined methods. It is also known as the standard library method or built-in method. We can directly use these methods just by calling them in the program at any point. Some pre-defined methods are length(), equals(), compareTo(), sqrt(), etc. When we call any of the predefined methods in our program, a series of codes related to the corresponding method runs in the background that is already stored in the library. Each and every predefined method is defined inside a class. Such as print() method is defined in the java.io.PrintStream class. It prints the statement that we write inside the method. For example, print("Java"), it prints Java on the console. Let's see an example of the predefined method. public class Demo { public static void main(String[] args) { // using the max() method of Math class System.out.print("The maximum number is: " + Math.max(9,7)); } } User-defined Method The method written by the user or programmer is known as a user-defined method. These methods are modified according to the requirement. How to Create a User-defined Method Let's create a user defined method that checks the number is even or odd. First, we will define the method. 12 BCA Sy 2023 Class Object and Method COCSIT, Latur //user defined method public static void findEvenOdd(int num) { //method body if(num%2==0) System.out.println(num+" is even"); else System.out.println(num+" is odd"); } Static Method A method that has static keyword is known as static method. In other words, a method that belongs to a class rather than an instance of a class is known as a static method. We can also create a static method by using the keyword static before the method name. The main advantage of a static method is that we can call it without creating an object. It can access static data members and also change the value of it. It is used to create an instance method. It is invoked by using the class name. The best example of a static method is the main() method. public class Display { public static void main(String[] args) { show(); } static void show() { System.out.println("It is an example of static method."); } } Instance Method The method of the class is known as an instance method. It is a non-static method defined in the class. Before calling or invoking the instance method, it is necessary to create an object of its class. Let's see an example of an instance method. 13 BCA Sy 2023 Class Object and Method COCSIT, Latur InstanceMethodExample.java public class InstanceMethodExample { public static void main(String [] args) { //Creating an object of the class InstanceMethodExample obj = new InstanceMethodExample(); //invoking instance method System.out.println("The sum is: "+obj.add(12, 13)); } int s; //user-defined method because we have not used static keyword public int add(int a, int b) { s = a+b; //returning the sum return s; } } Constructors in Java In Java, a constructor is a block of codes similar to the method. It is called when an instance of the class is created. At the time of calling constructor, memory for the object is allocated in the memory. It is a special type of method which is used to initialize the object. Every time an object is created using the new() keyword, at least one constructor is called. It calls a default constructor if there is no constructor available in the class. In such case, Java compiler provides a default constructor by default. There are two types of constructors in Java: no-arg constructor, and parameterized constructor. Note: It is called constructor because it constructs the values at the time of object creation. It is not necessary to write a constructor for a class. It is because java compiler creates a default constructor if your class doesn't have any. 14 BCA Sy 2023 Class Object and Method COCSIT, Latur Rules for creating Java constructor There are two rules defined for the constructor. 1. Constructor name must be the same as its class name 2. A Constructor must have no explicit return type 3. A Java constructor cannot be abstract, static, final, and synchronized Note: We can use access modifiers while declaring a constructor. It controls the object creation. In other words, we can have private, protected, public or default constructor in Java. Types of Java constructors There are two types of constructors in Java: 1. Default constructor (no-arg constructor) 2. Parameterized constructor Java Default Constructor A constructor is called "Default Constructor" when it doesn't have any parameter. //Java Program to create and call a default constructor class Bike1{ //creating a default constructor Bike1(){System.out.println("Bike is created");} public static void main(String args[]){ Bike1 b=new Bike1(); //calling a default constructor }} 15 BCA Sy 2023 Class Object and Method COCSIT, Latur Rule: If there is no constructor in a class, compiler automatically creates a default constructor. Q) What is the purpose of a default constructor? The default constructor is used to provide the default values to the object like 0, null, etc., depending on the type. Java Parameterized Constructor A constructor which has a specific number of parameters is called a parameterized constructor. Why use the parameterized constructor? The parameterized constructor is used to provide different values to distinct objects. However, you can provide the same values also. //Java Program to demonstrate the parameterized constructor. class Student4{ int id; String name; //creating a parameterized constructor Student4(int i,String n){ id = i; name = n; } void display(){System.out.println(id+" "+name);} public static void main(String args[]){ Student4 s1 = new Student4(111,"Karan"); //calling method to display the values of object s1.display(); } } 16 BCA Sy 2023 Class Object and Method COCSIT, Latur Constructor Overloading in Java In Java, a constructor is just like a method but without return type. It can also be overloaded like Java methods. Constructor overloading in Java is a technique of having more than one constructor with different parameter lists. They are arranged in a way that each constructor performs a different task. They are differentiated by the compiler by the number of parameters in the list and their types. //Java program to overload constructors class Student5{ int id; String name; int age; //creating two arg constructor Student5(int i,String n){ id = i; name = n; } //creating three arg constructor Student5(int i,String n,int a){ id = i; name = n; age=a; } void display(){System.out.println(id+" "+name+" "+age);} public static void main(String args[]){ Student5 s1 = new Student5(111,"Karan"); Student5 s2 = new Student5(222,"Aryan",25); s1.display(); s2.display(); } } 17 BCA Sy 2023 Class Object and Method COCSIT, Latur Difference between constructor and method in Java There are many differences between constructors and methods. They are given below. Java Constructor Java Method A constructor is used to initialize the state A method is used to expose the behavior of an object. of an object. A constructor must not have a return type. A method must have a return type. The constructor is invoked implicitly. The method is invoked explicitly. The Java compiler provides a default The method is not provided by the constructor if you don't have any compiler in any case. constructor in a class. The constructor name must be same as the The method name may or may not be class name. same as the class name. Java Copy Constructor There is no copy constructor in Java. However, we can copy the values from one object to another like copy constructor in C++. 18 BCA Sy 2023 Class Object and Method COCSIT, Latur There are many ways to copy the values of one object into another in Java. They are: o By constructor o By assigning the values of one object into another o By clone() method of Object class In this example, we are going to copy the values of one object into another using Java constructor. //Java program to initialize the values from one object to anot her object. class Student6{ int id; String name; //constructor to initialize integer and string Student6(int i,String n){ id = i; name = n; } //constructor to initialize another object Student6(Student6 s){ id = s.id; name =s.name; } void display(){System.out.println(id+" "+name);} public static void main(String args[]){ Student6 s1 = new Student6(111,"Karan"); Student6 s2 = new Student6(s1); s1.display(); s2.display(); } } Use of ‘this’ Keyword There can be a lot of usage of Java this keyword. In Java, this is a reference variable that refers to the current object. 19 BCA Sy 2023 Class Object and Method COCSIT, Latur Usage of Java this keyword Here is given the 6 usage of java this keyword. 1. this can be used to refer current class instance variable. 2. this can be used to invoke current class method (implicitly) 3. this() can be used to invoke current class constructor. 4. this can be passed as an argument in the method call. 5. this can be passed as argument in the constructor call. 6. this can be used to return the current class instance from the method. Suggestion: If you are beginner to java, lookup only three usages of this keyword. 1) this: to refer current class instance variable The this keyword can be used to refer current class instance variable. If there is ambiguity between the instance variables and parameters, this keyword resolves the problem of ambiguity. Solution of the above problem by this keyword class Student{ int rollno; String name; float fee; Student(int rollno,String name,float fee){ this.rollno=rollno; this.name=name; this.fee=fee; } void display(){System.out.println(rollno+" "+name+" "+fee);} } class TestThis2{ public static void main(String args[]){ Student s1=new Student(111,"ankit",5000f); s1.display(); 20 BCA Sy 2023 Class Object and Method COCSIT, Latur }} It is better approach to use meaningful names for variables. So we use same name for instance variables and parameters in real time, and always use this keyword. 2) this: to invoke current class method You may invoke the method of the current class by using the this keyword. If you don't use the this keyword, compiler automatically adds this keyword while invoking the method. Let's see the example class A{ void m(){System.out.println("hello m");} void n(){ System.out.println("hello n"); this.m(); //m();//same as this.m() }} class TestThis4{ public static void main(String args[]){ A a=new A(); a.n(); } } 3) this() : to invoke current class constructor 21 BCA Sy 2023 Class Object and Method COCSIT, Latur The this() constructor call can be used to invoke the current class constructor. It is used to reuse the constructor. In other words, it is used for constructor chaining. Calling default constructor from parameterized constructor: class A{ A(){System.out.println("hello a");} A(int x){ this(); System.out.println(x); } } class TestThis5{ public static void main(String args[]){ A a=new A(10); }} Calling parameterized constructor from default constructor: class A{ A(){ this(5); System.out.println("hello a"); } A(int x){ System.out.println(x); } } class TestThis6{ public static void main(String args[]){ A a=new A(); }} Real usage of this() constructor call 22 BCA Sy 2023 Class Object and Method COCSIT, Latur The this() constructor call should be used to reuse the constructor from the constructor. It maintains the chain between the constructors i.e. it is used for constructor chaining. Let's see the example given below that displays the actual use of this keyword. class Student{ int rollno; String name,course; float fee; Student(int rollno,String name,String course){ this.rollno=rollno; this.name=name; this.course=course; } Student(int rollno,String name,String course,float fee){ this(rollno,name,course);//reusing constructor this.fee=fee; } void display(){System.out.println(rollno+" "+name+" "+course+" "+fee);} } class TestThis7{ public static void main(String args[]){ Student s1=new Student(111,"ankit","java"); Student s2=new Student(112,"sumit","java",6000f); s1.display(); s2.display(); }} Rule: Call to this() must be the first statement in constructor. class Student{ int rollno; String name,course; float fee; Student(int rollno,String name,String course){ 23 BCA Sy 2023 Class Object and Method COCSIT, Latur this.rollno=rollno; this.name=name; this.course=course; } Student(int rollno,String name,String course,float fee){ this.fee=fee; this(rollno,name,course);//C.T.Error } void display(){System.out.println(rollno+" "+name+" "+course+" "+fee);} } class TestThis8{ public static void main(String args[]){ Student s1=new Student(111,"ankit","java"); Student s2=new Student(112,"sumit","java",6000f); s1.display(); s2.display(); }} 4) this: to pass as an argument in the method The this keyword can also be passed as an argument in the method. It is mainly used in the event handling. Let's see the example: class S2{ void m(S2 obj){ System.out.println("method is invoked"); } void p(){ m(this); } public static void main(String args[]){ S2 s1 = new S2(); s1.p(); } } Application of this that can be passed as an argument: 24 BCA Sy 2023 Class Object and Method COCSIT, Latur In event handling (or) in a situation where we have to provide reference of a class to another one. It is used to reuse one object in many methods. 5) this: to pass as argument in the constructor call We can pass the this keyword in the constructor also. It is useful if we have to use one object in multiple classes. Let's see the example: class B{ A4 obj; B(A4 obj){ this.obj=obj; } void display(){ System.out.println(obj.data);//using data member of A4 class } } class A4{ int data=10; A4(){ B b=new B(this); b.display(); } public static void main(String args[]){ A4 a=new A4(); } } 6) this keyword can be used to return current class instance We can return this keyword as an statement from the method. In such case, return type of the method must be the class type (non-primitive). Let's see the example: Syntax of this that can be returned as a statement return_type method_name(){ return this; } Example of this keyword that you return as a statement from the method class A{ 25 BCA Sy 2023 Class Object and Method COCSIT, Latur A getA(){ return this; } void msg(){System.out.println("Hello java");} } class Test1{ public static void main(String args[]){ new A().getA().msg(); } } Proving this keyword Let's prove that this keyword refers to the current class instance variable. In this program, we are printing the reference variable and this, output of both variables are same. class A5{ void m(){ System.out.println(this);//prints same reference ID } public static void main(String args[]){ A5 obj=new A5(); System.out.println(obj);//prints the reference ID obj.m(); } } Finalize Method: finalize() is a method of the Object class in Java. The finalize() method is a non-static and protected method of java.lang.Object class. In Java, the Object class is superclass of all Java classes. Being an object class method finalize() method is available for every class in Java. Hence, Garbage Collector can call finalize() method on any Java object for clean-up activity. finalize() method in Java is used to release all the resources used by the object before it is deleted/destroyed by the Garbage collector. finalize is not a reserved keyword, it's a method. Once the clean-up activity is done by the finalize() method, garbage collector immediately destroys the Java object. Java Virtual Machine(JVM) permits invoking of finalize() method 26 BCA Sy 2023 Class Object and Method COCSIT, Latur only once per object. Once object is finalized JVM sets a flag in the object header to say that it has been finalized, and won't finalize it again. If user tries to use finalize() method for the same object twice, JVM ignores it. Garbage Collector in Java Java considers unreferenced objects that are not being used by any program execution or objects that are no longer needed, as garbage. Garbage collection is the process of destroying unused objects and reclaiming the unused runtime memory automatically. By doing this memory is managed efficiently by Java. Unrefrencing of objects is done in multiple ways as follows: 1. By anonymous object: Anonymous objects are those objects in Java which are created without any reference variable. As a result, after creation, we have no way to access the anonymous object. new Student(); In the above code, even though an object of Student class is created, it has no reference variable and cannot be used after creation, but it acquires memory. 2. By nulling reference: When an object is referenced to null value, it is considered an unreferenced object as it holds only null value. Student S=new Student(); S=null; Here, s is an unreferenced object that holds null value. It is considered garbage by JVM. 3. By assigning a reference to another object: When one object is assigned to another, first object is of no use and can be considered as garbage. Student S1=new Student(); Student S2=new Student(); S1=S2; 27 BCA Sy 2023 Class Object and Method COCSIT, Latur After the last statement s1 = s2 is executed, the first object becomes unreferenced and can be considered for garbage collection. The garbage collector is a part of Java Virtual Machine(JVM). Garbage collector checks the heap memory, where all the objects are stored by JVM, looking for unreferenced objects that are no more needed. And automatically destroys those objects. Garbage collector calls finalize() method for clean up activity before destroying the object. Java does garbage collection automatically; there is no need to do it explicitly, unlike other programming languages. The garbage collector in Java can be called explicitly using the following method: System.gc(); System.gc() is a method in Java that invokes garbage collector which will destroy the unreferenced objects. System.gc() calls finalize() method only once for each object. How does the finalize() Method Work with Garbage Collection? As explained earlier, JVM calls the garbage collector to delete unreferenced objects. After determining the objects that have no links or references, it calls the finalize() method which will perform the clean activity and the garbage collector destroys the object. Let's see a code to understand this: public class Demo{ public static void main(String[] args) { String a = "Hello World!"; a = null; // unreferencing string object } } In the above program, when the String object a holds value Hello World! it has a reference to an object of the String class. But, when it holds a null value it does not have any reference. Hence, it is eligible for garbage collection. The garbage collector calls finalize() method to perform clean-up before destroying the object. 28 BCA Sy 2023 Class Object and Method COCSIT, Latur What is the Cleanup Activity? Cleanup activity is the process of closing all the resources being used by an object before it is destroyed. Resources that can be used by any object are database connections, network connections, etc. These resources are released and clean-up activity is performed by the garbage collector in Java and then the object is deleted. The major advantage of performing clean-up before garbage collection is data resources or network connections that are linked to unreferenced object are revoked and can be used again. Cleanup ensures resources are not linked to objects unnecessarily and helps JVM in boosting memory optimization and speed. Finalization Garbage collector always invokes finalize() method in java to perform clean-up activities before destroying any object. This process of performing clean-up activities using finalize() method is called finalization. Note: For each object garbage collector calls finalize() method only once. Syntax of finalize() Method in Java As mentioned earlier, finalize() is a protected method of the Object class in Java. Here is the syntax: protected void finalize() throws Throwable{}  Protected method: protected is an access specifier for variables and methods in java. When a variable or method is protected it means it can be accessed within the class where it's declared and other derived classes of that class.  In Java, all classes inherit the Object class directly or indirectly. finalize() method is protected in Object class so that all classes in Java can override and use it. finalize() method in Java is a method of the Object class that is used to perform clean-up activity before destroying any object. It is called by Garbage collector before destroying the objects from memory. finalize() method is called by default for every object before its deletion. 29 BCA Sy 2023 Class Object and Method COCSIT, Latur This method helps Garbage Collector to close all the resources used by the object and helps JVM in-memory optimization. To understand this topic, you should have some knowledge of the following Java Programming topics:  Garbage Collection in Java  Final Keyword in Java  Exception Handling in Java Static Members The static keyword in Java is used for memory management mainly. We can apply static keyword with variables, methods, blocks and nested classes. The static keyword belongs to the class than an instance of the class. The static can be: 1. Variable (also known as a class variable) 2. Method (also known as a class method) 3. Block 4. Nested class 1) Java static variable If you declare any variable as static, it is known as a static variable. o The static variable can be used to refer to the common property of all objects (which is not unique for each object), for example, the company name of employees, college name of students, etc. o The static variable gets memory only once in the class area at the time of class loading. Advantages of static variable 30 BCA Sy 2023 Class Object and Method COCSIT, Latur It makes your program memory efficient (i.e., it saves memory). Understanding the problem without static variable class Student{ int rollno; String name; String college="ITS"; } Suppose there are 500 students in my college, now all instance data members will get memory each time when the object is created. All students have its unique rollno and name, so instance data member is good in such case. Here, "college" refers to the common property of all objects. If we make it static, this field will get the memory only once. Java static property is shared to all objects. Example of static variable //Java Program to demonstrate the use of static variable class Student{ int rollno;//instance variable String name; static String college ="ITS";//static variable //constructor Student(int r, String n){ rollno = r; name = n; } //method to display the values void display (){System.out.println(rollno+" "+name+" "+college);} } //Test class to show the values of objects public class TestStaticVariable1{ public static void main(String args[]){ Student s1 = new Student(111,"Karan"); Student s2 = new Student(222,"Aryan"); s1.display(); s2.display(); } } 31 BCA Sy 2023 Class Object and Method COCSIT, Latur Program of the counter without static variable In this example, we have created an instance variable named count which is incremented in the constructor. Since instance variable gets the memory at the time of object creation, each object will have the copy of the instance variable. If it is incremented, it won't reflect other objects. So each object will have the value 1 in the count variable. //Java Program to demonstrate the use of an instance variable //which get memory each time when we create an object of the cla ss. class Counter{ int count=0;//will get memory each time when the instance is crea ted Counter(){ count++;//incrementing value System.out.println(count); } public static void main(String args[]){ //Creating objects Counter c1=new Counter(); Counter c2=new Counter(); Counter c3=new Counter(); } } 32 BCA Sy 2023 Class Object and Method COCSIT, Latur Program of counter by static variable As we have mentioned above, static variable will get the memory only once, if any object changes the value of the static variable, it will retain its value. //Java Program to illustrate the use of static variable which //is shared with all objects. class Counter2{ static int count=0;//will get memory only once and retain its value Counter2(){ count++;//incrementing the value of static variable System.out.println(count); } public static void main(String args[]){ //creating objects Counter2 c1=new Counter2(); Counter2 c2=new Counter2(); Counter2 c3=new Counter2(); } } 2) Java static method If you apply static keyword with any method, it is known as static method. o A static method belongs to the class rather than the object of a class. o A static method can be invoked without the need for creating an instance of a class. o A static method can access static data member and can change the value of it. Example of static method //Java Program to demonstrate the use of a static method. class Student{ int rollno; String name; static String college = "ITS"; //static method to change the value of static variable 33 BCA Sy 2023 Class Object and Method COCSIT, Latur static void change(){ college = "BBDIT"; } //constructor to initialize the variable Student(int r, String n){ rollno = r; name = n; } //method to display values void display(){System.out.println(rollno+" "+name+" "+college);} } //Test class to create and display the values of object public class TestStaticMethod{ public static void main(String args[]){ Student.change();//calling change method //creating objects Student s1 = new Student(111,"Karan"); Student s2 = new Student(222,"Aryan"); Student s3 = new Student(333,"Sonoo"); //calling display method s1.display(); s2.display(); s3.display(); } } Another example of a static method that performs a normal calculation //Java Program to get the cube of a given number using the stat ic method class Calculate{ static int cube(int x){ return x*x*x; } 34 BCA Sy 2023 Class Object and Method COCSIT, Latur public static void main(String args[]){ int result=Calculate.cube(5); System.out.println(result); } } Restrictions for the static method There are two main restrictions for the static method. They are: 1. The static method can not use non static data member or call non-static method directly. 2. this and super cannot be used in static context. class A{ int a=40;//non static public static void main(String args[]){ System.out.println(a); } } Q) Why is the Java main method static? Ans) It is because the object is not required to call a static method. If it were a non-static method, JVM creates an object first then call main() method that will lead the problem of extra memory allocation. 3) Java static block o Is used to initialize the static data member. o It is executed before the main method at the time of classloading. Example of static block class A2{ static{System.out.println("static block is invoked");} public static void main(String args[]){ System.out.println("Hello main"); } } 35 BCA Sy 2023 Class Object and Method COCSIT, Latur Q) Can we execute a program without main() method? Ans) No, one of the ways was the static block, but it was possible till JDK 1.6. Since JDK 1.7, it is not possible to execute a Java class without the main method. class A3{ static{ System.out.println("static block is invoked"); System.exit(0); } } Inheritance and It’s Types Inheritance in Java is a mechanism in which one object acquires all the properties and behaviors of a parent object. It is an important part of OOPs (Object Oriented programming system). The idea behind inheritance in Java is that you can create new classes that are built upon existing classes. When you inherit from an existing class, you can reuse methods and fields of the parent class. Moreover, you can add new methods and fields in your current class also. Inheritance represents the IS-A relationship which is also known as a parent- child relationship. Why use inheritance in java o For Method Overriding (so runtime polymorphism can be achieved). o For Code Reusability. Terms used in Inheritance o Class: A class is a group of objects which have common properties. It is a template or blueprint from which objects are created. o Sub Class/Child Class: Subclass is a class which inherits the other class. It is also called a derived class, extended class, or child class. o Super Class/Parent Class: Superclass is the class from where a subclass inherits the features. It is also called a base class or a parent class. 36 BCA Sy 2023 Class Object and Method COCSIT, Latur o Reusability: As the name specifies, reusability is a mechanism which facilitates you to reuse the fields and methods of the existing class when you create a new class. You can use the same fields and methods already defined in the previous class. The syntax of Java Inheritance class Subclass-name extends Superclass-name { //methods and fields } The extends keyword indicates that you are making a new class that derives from an existing class. The meaning of "extends" is to increase the functionality. Java Inheritance Example As displayed in the above figure, Programmer is the subclass and Employee is the superclass. The relationship between the two classes is Programmer IS-A Employee. It means that Programmer is a type of Employee. class Employee{ float salary=40000; } class Programmer extends Employee{ int bonus=10000; public static void main(String args[]){ Programmer p=new Programmer(); System.out.println("Programmer salary is:"+p.salary); System.out.println("Bonus of Programmer is:"+p.bonus); } 37 BCA Sy 2023 Class Object and Method COCSIT, Latur } Types of inheritance in java On the basis of class, there can be three types of inheritance in java: single, multilevel and hierarchical. In java programming, multiple and hybrid inheritance is supported through interface only. We will learn about interfaces later. Note: Multiple inheritance is not supported in Java through class. When one class inherits multiple classes, it is known as multiple inheritance. For Example: 38 BCA Sy 2023 Class Object and Method COCSIT, Latur Single Inheritance Example When a class inherits another class, it is known as a single inheritance. In the example given below, Dog class inherits the Animal class, so there is the single inheritance. class Animal{ void eat(){System.out.println("eating...");} } class Dog extends Animal{ void bark(){System.out.println("barking...");} } class TestInheritance{ public static void main(String args[]){ Dog d=new Dog(); d.bark(); d.eat(); }} When there is a chain of inheritance, it is known as multilevel inheritance. As you can see in the example given below, BabyDog class inherits the Dog class which again inherits the Animal class, so there is a multilevel inheritance. class Animal{ void eat(){System.out.println("eating...");} } class Dog extends Animal{ void bark(){System.out.println("barking...");} } class BabyDog extends Dog{ void weep(){System.out.println("weeping...");} } class TestInheritance2{ public static void main(String args[]){ BabyDog d=new BabyDog(); d.weep(); d.bark(); d.eat(); }} 39 BCA Sy 2023 Class Object and Method COCSIT, Latur Hierarchical Inheritance Example When two or more classes inherits a single class, it is known as hierarchical inheritance. In the example given below, Dog and Cat classes inherits the Animal class, so there is hierarchical inheritance. class Animal{ void eat(){System.out.println("eating...");} } class Dog extends Animal{ void bark(){System.out.println("barking...");} } class Cat extends Animal{ void meow(){System.out.println("meowing...");} } class TestInheritance3{ public static void main(String args[]){ Cat c=new Cat(); c.meow(); c.eat(); //c.bark();//C.T.Error }} Q) Why multiple inheritance is not supported in java? To reduce the complexity and simplify the language, multiple inheritance is not supported in java. Consider a scenario where A, B, and C are three classes. The C class inherits A and B classes. If A and B classes have the same method and you call it from child class object, there will be ambiguity to call the method of A or B class. Since compile-time errors are better than runtime errors, Java renders compile-time error if you inherit 2 classes. So whether you have same method or different, there will be compile time error. class A{ void msg(){System.out.println("Hello");} } class B{ void msg(){System.out.println("Welcome");} } class C extends A,B{//suppose if it were public static void main(String args[]){ C obj=new C(); obj.msg();//Now which msg() method would be invoked? } } 40 BCA Sy 2023 Class Object and Method COCSIT, Latur Final Variable, Method and Final Class The final keyword in java is used to restrict the user. The java final keyword can be used in many context. Final can be: 1. variable 2. method 3. class The final keyword can be applied with the variables, a final variable that have no value it is called blank final variable or uninitialized final variable. It can be initialized in the constructor only. The blank final variable can be static also which will be initialized in the static block only. We will have detailed learning of these. Let's first learn the basics of final keyword. 1) Java final variable If you make any variable as final, you cannot change the value of final variable (It will be constant). Example of final variable There is a final variable speedlimit, we are going to change the value of this variable, but It can't be changed because final variable once assigned a value can never be changed. class Bike9{ final int speedlimit=90;//final variable void run(){ speedlimit=400; } public static void main(String args[]){ Bike9 obj=new Bike9(); obj.run(); } }//end of class 41 BCA Sy 2023 Class Object and Method COCSIT, Latur 2) Java final method If you make any method as final, you cannot override it. Example of final method class Bike{ final void run(){System.out.println("running");} } class Honda extends Bike{ void run(){System.out.println("running safely with 100kmph");} public static void main(String args[]){ Honda honda= new Honda(); honda.run(); } } 3) Java final class If you make any class as final, you cannot extend it. Example of final class final class Bike{} class Honda1 extends Bike{ void run(){System.out.println("running safely with 100kmph");} public static void main(String args[]){ Honda1 honda= new Honda1(); honda.run(); } } Q) Is final method inherited? Ans) Yes, final method is inherited but you cannot override it. For Example: class Bike{ final void run(){System.out.println("running...");} } class Honda2 extends Bike{ public static void main(String args[]){ 42 BCA Sy 2023 Class Object and Method COCSIT, Latur new Honda2().run(); } } Q) What is blank or uninitialized final variable? A final variable that is not initialized at the time of declaration is known as blank final variable. If you want to create a variable that is initialized at the time of creating object and once initialized may not be changed, it is useful. For example PAN CARD number of an employee. It can be initialized only in constructor. Example of blank final variable class Student{ int id; String name; final String PAN_CARD_NUMBER;... } Que) Can we initialize blank final variable? Yes, but only in constructor. For example: class Bike10{ final int speedlimit;//blank final variable Bike10(){ speedlimit=70; System.out.println(speedlimit); } public static void main(String args[]){ new Bike10(); } } Static blank final variable A static final variable that is not initialized at the time of declaration is known as static blank final variable. It can be initialized only in static block. Example of static blank final variable 43 BCA Sy 2023 Class Object and Method COCSIT, Latur 1. class A{ 2. static final int data;//static blank final variable 3. static{ data=50;} 4. public static void main(String args[]){ 5. System.out.println(A.data); 6. } 7. } Q) What is final parameter? If you declare any parameter as final, you cannot change the value of it. class Bike11{ int cube(final int n){ n=n+2;//can't be changed as n is final n*n*n; } public static void main(String args[]){ Bike11 b=new Bike11(); b.cube(5); } } 44

Use Quizgecko on...
Browser
Browser