• Any entity that has state and behavior is known as an object. • Object is a basic unit of Object Oriented Programming. • Object represents the real life entities. • It can be physical or logical. • An Object can be defined as an instance of a class. • Java program creates many objects, which interact by invoking methods. • An object contains an address and takes up some space in memory. • It communicates without knowing details of each other's data or code. 1 Object
2 Characteristics of Object • An object consists of: • State : • It is represented by attributes of an object. • It also reflects the properties of an object. • Behavior : • It is represented by methods of an object. • It reflects response of an object with other objects. • Identity : • It gives a unique name to an object and enables one object to interact with other objects. • Method: • A method is a collection of statements that perform some specific task and return result to the caller.
• An object is a real-world entity. • An object is a runtime entity. • The object is an entity which has state and behavior. • The object is an instance of a class. • Objects correspond to things found in the real world. • Graphics program may have objects such as “circle”, “square”, “menu”. • An online shopping system have objects such as “shopping cart”, “customer”, and “product”. • Example of an object: dog 3 Object Definition and Example
• Definition: • Collection of objects is called class. • A class is a group of objects which have common properties. • It is defined as template or blueprint from which objects are created. • It is a logical entity. • It can't be physical. • Class doesn't consume any space • It represents the set of properties or methods that are common to all objects of one type 4 Class
5 Class • When an object of a class is created, the class is said to be instantiated. • All the instances share the attributes and the behavior of the class. • The values of those attributes, i.e. the state are unique for each object. • A single class may have any number of instances. • Example
6
7
• A class in Java can contain: • Fields/Variables/data members • Methods • Constructors • Nested class • Constructors are used for initializing new objects. • Fields are variables that provides the state of the class and its objects. • Methods are used to implement the behavior of the class and its objects. 8 Class components
class class_name { type instance_variable1; type instance_variable2; type method_name1(parameter-list) { // body of method } type method_name2(parameter-list) { // body of method } } 9 Declaring Classes class class_name { type variable; type method1(); type method2(parameter- list); } Class_name variable/attributes; int number; float marks; method() add(); class structure class declaration
• Class declarations can include following components • Modifiers: A class can be public or has default access. • class keyword: class keyword is used to create a class. • Class name: The name should begin with an initial letter. • Body: The class body surrounded by braces, { }. 10 Declaring Classes
• Syntax to create object for a class class_name object_name=new class_name(); • Create an object for class Student Student s1=new Student(); Student s2=new Student(): 11 Object Creation for a class
12 Class and object Example class Student { 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); } }
13 class Student { int id; String name; } //Creating another class TestStudent which contains the main method class TestStudent { public static void main(String args[]) { Student s1=new Student(); System.out.println(s1.id); System.out.println(s1.name); } } Class and object Example
class Student { int id; String name; } class TestStudent { public static void main(String args[]) { Student s1=new Student(); Student s2=new Student(); 14 //Initializing objects s1.id=101; s1.name=“Mahesh"; s2.id=102; s2.name="Amit"; System.out.println(s1.id+" "+s1.name); System.out.println(s2.id+" "+s2.name); } } Class and object Example
• Classes usually consist of two things: • Instance variables and • Methods. • A method is a way to perform some task. • The method in Java is a collection of instructions that performs a specific task. • A method is • a block of code or • collection of statements/ instructions or • a set of code grouped together to perform a certain task or operation. 15 Method: Definition
• 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 provides the easy modification and readability of code. • The method is executed only when we call or invoke it. • The most important method in Java is the main() method. 16 Method : Uses
• This is the general form of a method declaration: type name(parameter-list) { // body of method } 17 Method Declaration
18 Adding Methods • A class with only data fields has no life. Objects created by such a class cannot respond to any messages. • Methods are declared inside the body of the class but immediately after the declaration of data fields. • The general form of a method declaration is: type MethodName (parameter-list) { Method-body; }
19 Adding Methods to Class Circle public class Circle { public double x, y; // centre of the circle public double r; // radius of circle //Methods to return circumference and area public double circumference() { return 2*3.14*r; } public double area() { return 3.14 * r * r; } } Method Body
20 Data Abstraction • Declare the Circle class, have created a new data type – Data Abstraction • Can define variables (objects) of that type: Circle aCircle; Circle bCircle;
21 Class of Circle cont. • aCircle, bCircle simply refers to a Circle object, not an object itself. aCircle Points to nothing (Null Reference) bCircle Points to nothing (Null Reference) null null
22 Creating objects of a class • Objects are created dynamically using the new keyword. • aCircle and bCircle refer to Circle objects bCircle = new Circle() ; aCircle = new Circle() ;
23 Creating objects of a class aCircle = new Circle(); bCircle = new Circle() ; bCircle = aCircle; P aCircle Q bCircle Before Assignment P aCircle Q bCircle Before Assignment
24 Automatic garbage collection • The object does not have a reference and cannot be used in future. • The object becomes a candidate for automatic garbage collection. • Java automatically collects garbage periodically and releases the memory used to be used in the future. Q
25 Accessing Data members • Similar to C syntax for accessing data defined in a structure. Circle aCircle = new Circle(); aCircle.x = 2.0 // initialize center and radius aCircle.y = 2.0 aCircle.r = 1.0 ObjectName.VariableName ObjectName.MethodName(parameter-list)
26 Executing Methods in Object/Circle • Using Object Methods: Circle aCircle = new Circle(); double area; aCircle.r = 1.0; area = aCircle.area(); sent ‘message’ to aCircle
27 Using Circle Class // Circle.java: Contains both Circle class and its user class //Add Circle class code here class MyMain { public static void main(String args[]) { Circle aCircle; // creating reference aCircle = new Circle(); // creating object aCircle.x = 10; // assigning value to data field aCircle.y = 20; aCircle.r = 5; double area = aCircle.area(); // invoking method double circumf = aCircle.circumference(); System.out.println("Radius="+aCircle.r+" Area="+area); System.out.println("Radius="+aCircle.r+" Circumference ="+circumf);
• Return Type: • Return type is a data type that the method returns. • If the method does not return anything, then use void keyword. • Method Name: • It is a unique name that is used to define the name of a method. • Parameter List: • It is the list of parameters separated by a comma. • It contains the data type and variable name. • If the method has no parameter, left the parentheses blank. • Method Body: • It contains all the actions to be performed enclosed within the curly braces. 28 Method Declaration
• Example int multi (int a, int b) { // method body; return (a*b); } • Example void add() { // method body; } 29 Method sample example
• There are two types of methods in Java: • Predefined Method • User-defined Method 30 Method Types
• Predefined Method • 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 runs in the background that is already stored in the library. 31 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)); } } 32 Method Types
• The method written by the user or programmer is known as a user- defined method. • These methods are modified according to the requirement. • Example int EvenOdd(int num) { //method body if(num%2==0) System.out.println(num+" is even"); else System.out.println(num+" is odd"); } 33 User-defined Method
import java.util.Scanner; public class EvenOdd { public static void main (String args[]) { Scanner scan=new Scanner(System.in); System.out.print("Enter the number: "); //reading value from the user int num=scan.nextInt(); //method calling findEvenOdd(num); } 34 User-defined Method
class Rectangle { double l; double b; // display area of a rectangle void area() { System.out.print(“Area is "); System.out.println(l * b ); } } 35 Method Example Program to display area of Rectangle using method.
class BoxDemo { public static void main(String args[]) { Rectangle mybox1 = new Rectangle(); Rectangle mybox2 = new Rectangle(); // assign values to mybox1's instance variables mybox1.l = 10; mybox1.b = 20; mybox2.l = 3; /* assign different values to mybox2's instance variables */ mybox2.b = 6; mybox1.area(); // display volume of first box mybox2.area(); // display volume of second box } } 36 Method Example
• If a class has multiple methods having same name but different in parameters, it is known as Method Overloading. • If we have to perform only one operation, having same name of the methods increases the readability of the program. • Advantage of method overloading • Method overloading increases the readability of the program. • Different ways to overload the method • There are two ways to overload the method in java • By changing number of arguments • By changing the data type 37 Method Overloading
int area(int r) { return 3.14 * r * r; } int area(int h, int l) { return h * l; } 38 Method Overloading Example
class OverloadDemo { void test() { System.out.println("No parameters"); } // Overload test for one integer parameter. void test(int a) { System.out.println("a: " + a); } // Overload test for two integer parameters. void test(int a, int b) { System.out.println("a and b: " + a + " " + b); } // Overload test for a double parameter double test(double a) { System.out.println("double a: " + a); return a*a; } } 39 class Overload { public static void main(String args[]) { OverloadDemo ob = new OverloadDemo(); double result; ob.test(); ob.test(10); ob.test(10, 20); result = ob.test(123.25); System.out.println("Result of ob.test(123.25): " + result); } } Method Overloading Example
• This program generates the following output: No parameters a: 10 a and b: 10 20 double a: 123.25 Result of ob.test(123.25): 15190.5625 40 Method Overloading Example- Result
• 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. 41 Constructor
• 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. • Rules for creating Java constructor • There are two rules defined for the constructor. • Constructor name must be the same as its class name • A Constructor must have no explicit return type • A Java constructor cannot be abstract, static, final. 42 Constructor
• There are two types of constructors in Java: • Default constructor (no-arg constructor) • Parameterized constructor • Java Default Constructor • A constructor is called "Default Constructor" when it doesn't have any parameter. • Syntax of default constructor: <class_name>(){} • The default constructor is used to provide the default values to the object like 0, null, etc., depending on the type. 43 Constructor Types
• Java Parameterized Constructor • A constructor which has a specific number of parameters is called a parameterized constructor. • The parameterized constructor is used to provide different values to distinct objects. • However, you can provide the same values also. • Example Student(int i,String n){ id = i; name = n; } 44 Constructor Types
45 class Bike1{ //creating a default constructor Bike1() { System.out.println("Bike is created"); } public static void main(String args[]) { //calling a default constructor Bike1 b=new Bike1(); } } class Student { int id; String name; void display() { System.out.println(id+" "+name); } public static void main(String args[]) { Student s1=new Student(); Student s2=new Student(); //displaying values of the object s1.display(); s2.display(); } } Constructor Example
46 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[]) { //creating objects and passing values Student4 s1 = new Student4(111,"Karan"); Student4 s2 = new Student4(222,"Aryan"); s1.display(); s2.display(); } } Parameterized Constructor Example
• 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. 47 Constructor Overloading in Java
48 Constructor Overloading Example
49
• In Java, this is a reference variable that refers to the current object. • Usage of Java this keyword • this can be used to refer current class instance variable. • this can be used to invoke current class method (implicitly) • this() can be used to invoke current class constructor. • this can be passed as an argument in the method call. • this can be passed as argument in the constructor call. • this can be used to return the current class instance from the method. 50 this keyword in Java
class Student{ int rollno; String name; float fee; Student(int rollno,String name,float fee){ rollno=rollno; name=name; fee=fee; } void display(){ System.out.println(rollno+" "+name+" "+fee); } } 51 Program without this keyword class TestThis { public static void main(String args[]) { Student s1=new Student(111,“Ankit",5000f); Student s2=new Student(112,“Sumit",6000f); s1.display(); s2.display(); } }
52 0 null 0.0 0 null 0.0 • Parameters (formal arguments/local veriables) and instance variables are same. • So, need to use this keyword to distinguish local variable and instance variable. Program output
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); } } 53 Program with this keyword class TestThis { public static void main(String args[]) { Student s1=new Student(111,“Ankit",5000f); Student s2=new Student(112,“Sumit",6000f); s1.display(); s2.display(); } }
class Student{ int rollno; String name; float fee; Student(int r, String n, float f){ rollno=r; name=n; fee=f; } void display(){ System.out.println(rollno+" "+name+" "+fee); } } 54 Program without this keyword class TestThis { public static void main(String args[]) { Student s1=new Student(111,“Ankit",5000f); Student s2=new Student(112,“Sumit",6000f); s1.display(); s2.display(); } }
• The static keyword in Java is used for memory management mainly. • The static keyword belongs to the class than an instance of the class. • The static can be: • Variable (also known as a class variable) • Method (also known as a class method) • Nested class • If you declare any variable as static, it is known as a static variable. 55 static keyword in Java
• 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=“DYP-ATU"; } • Suppose there are 500 students in my college. • Now all instance data members will get memory each time when the object is created. • "college" refers to the common property of all objects. • If we make it static, this field will get the memory only once. 56 static keyword in Java
57 class Student{ int rollno; //instance variable String name; static String college =“DYP"; //static variable Student(int r, String n) { //constructor rollno = r; name = n; } void display () { System.out.println(rollno+" "+name+" "+college); } } public class TestStatic { public static void main(String args[]){ Student s1 = new Student(111,"Karan"); Student s2 = new Student(222,"Aryan"); //Student.college=“DYP"; s1.display(); s2.display(); } } static keyword Example
End of Unit 58

Core Java unit no. 1 object and class ppt

  • 1.
    • Any entitythat has state and behavior is known as an object. • Object is a basic unit of Object Oriented Programming. • Object represents the real life entities. • It can be physical or logical. • An Object can be defined as an instance of a class. • Java program creates many objects, which interact by invoking methods. • An object contains an address and takes up some space in memory. • It communicates without knowing details of each other's data or code. 1 Object
  • 2.
    2 Characteristics of Object •An object consists of: • State : • It is represented by attributes of an object. • It also reflects the properties of an object. • Behavior : • It is represented by methods of an object. • It reflects response of an object with other objects. • Identity : • It gives a unique name to an object and enables one object to interact with other objects. • Method: • A method is a collection of statements that perform some specific task and return result to the caller.
  • 3.
    • An objectis a real-world entity. • An object is a runtime entity. • The object is an entity which has state and behavior. • The object is an instance of a class. • Objects correspond to things found in the real world. • Graphics program may have objects such as “circle”, “square”, “menu”. • An online shopping system have objects such as “shopping cart”, “customer”, and “product”. • Example of an object: dog 3 Object Definition and Example
  • 4.
    • Definition: • Collectionof objects is called class. • A class is a group of objects which have common properties. • It is defined as template or blueprint from which objects are created. • It is a logical entity. • It can't be physical. • Class doesn't consume any space • It represents the set of properties or methods that are common to all objects of one type 4 Class
  • 5.
    5 Class • When anobject of a class is created, the class is said to be instantiated. • All the instances share the attributes and the behavior of the class. • The values of those attributes, i.e. the state are unique for each object. • A single class may have any number of instances. • Example
  • 6.
  • 7.
  • 8.
    • A classin Java can contain: • Fields/Variables/data members • Methods • Constructors • Nested class • Constructors are used for initializing new objects. • Fields are variables that provides the state of the class and its objects. • Methods are used to implement the behavior of the class and its objects. 8 Class components
  • 9.
    class class_name { typeinstance_variable1; type instance_variable2; type method_name1(parameter-list) { // body of method } type method_name2(parameter-list) { // body of method } } 9 Declaring Classes class class_name { type variable; type method1(); type method2(parameter- list); } Class_name variable/attributes; int number; float marks; method() add(); class structure class declaration
  • 10.
    • Class declarationscan include following components • Modifiers: A class can be public or has default access. • class keyword: class keyword is used to create a class. • Class name: The name should begin with an initial letter. • Body: The class body surrounded by braces, { }. 10 Declaring Classes
  • 11.
    • Syntax tocreate object for a class class_name object_name=new class_name(); • Create an object for class Student Student s1=new Student(); Student s2=new Student(): 11 Object Creation for a class
  • 12.
    12 Class and objectExample class Student { 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); } }
  • 13.
    13 class Student { int id; Stringname; } //Creating another class TestStudent which contains the main method class TestStudent { public static void main(String args[]) { Student s1=new Student(); System.out.println(s1.id); System.out.println(s1.name); } } Class and object Example
  • 14.
    class Student { int id; Stringname; } class TestStudent { public static void main(String args[]) { Student s1=new Student(); Student s2=new Student(); 14 //Initializing objects s1.id=101; s1.name=“Mahesh"; s2.id=102; s2.name="Amit"; System.out.println(s1.id+" "+s1.name); System.out.println(s2.id+" "+s2.name); } } Class and object Example
  • 15.
    • Classes usuallyconsist of two things: • Instance variables and • Methods. • A method is a way to perform some task. • The method in Java is a collection of instructions that performs a specific task. • A method is • a block of code or • collection of statements/ instructions or • a set of code grouped together to perform a certain task or operation. 15 Method: Definition
  • 16.
    • It isused 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 provides the easy modification and readability of code. • The method is executed only when we call or invoke it. • The most important method in Java is the main() method. 16 Method : Uses
  • 17.
    • This isthe general form of a method declaration: type name(parameter-list) { // body of method } 17 Method Declaration
  • 18.
    18 Adding Methods • Aclass with only data fields has no life. Objects created by such a class cannot respond to any messages. • Methods are declared inside the body of the class but immediately after the declaration of data fields. • The general form of a method declaration is: type MethodName (parameter-list) { Method-body; }
  • 19.
    19 Adding Methods toClass Circle public class Circle { public double x, y; // centre of the circle public double r; // radius of circle //Methods to return circumference and area public double circumference() { return 2*3.14*r; } public double area() { return 3.14 * r * r; } } Method Body
  • 20.
    20 Data Abstraction • Declarethe Circle class, have created a new data type – Data Abstraction • Can define variables (objects) of that type: Circle aCircle; Circle bCircle;
  • 21.
    21 Class of Circlecont. • aCircle, bCircle simply refers to a Circle object, not an object itself. aCircle Points to nothing (Null Reference) bCircle Points to nothing (Null Reference) null null
  • 22.
    22 Creating objects ofa class • Objects are created dynamically using the new keyword. • aCircle and bCircle refer to Circle objects bCircle = new Circle() ; aCircle = new Circle() ;
  • 23.
    23 Creating objects ofa class aCircle = new Circle(); bCircle = new Circle() ; bCircle = aCircle; P aCircle Q bCircle Before Assignment P aCircle Q bCircle Before Assignment
  • 24.
    24 Automatic garbage collection •The object does not have a reference and cannot be used in future. • The object becomes a candidate for automatic garbage collection. • Java automatically collects garbage periodically and releases the memory used to be used in the future. Q
  • 25.
    25 Accessing Data members •Similar to C syntax for accessing data defined in a structure. Circle aCircle = new Circle(); aCircle.x = 2.0 // initialize center and radius aCircle.y = 2.0 aCircle.r = 1.0 ObjectName.VariableName ObjectName.MethodName(parameter-list)
  • 26.
    26 Executing Methods inObject/Circle • Using Object Methods: Circle aCircle = new Circle(); double area; aCircle.r = 1.0; area = aCircle.area(); sent ‘message’ to aCircle
  • 27.
    27 Using Circle Class //Circle.java: Contains both Circle class and its user class //Add Circle class code here class MyMain { public static void main(String args[]) { Circle aCircle; // creating reference aCircle = new Circle(); // creating object aCircle.x = 10; // assigning value to data field aCircle.y = 20; aCircle.r = 5; double area = aCircle.area(); // invoking method double circumf = aCircle.circumference(); System.out.println("Radius="+aCircle.r+" Area="+area); System.out.println("Radius="+aCircle.r+" Circumference ="+circumf);
  • 28.
    • Return Type: •Return type is a data type that the method returns. • If the method does not return anything, then use void keyword. • Method Name: • It is a unique name that is used to define the name of a method. • Parameter List: • It is the list of parameters separated by a comma. • It contains the data type and variable name. • If the method has no parameter, left the parentheses blank. • Method Body: • It contains all the actions to be performed enclosed within the curly braces. 28 Method Declaration
  • 29.
    • Example int multi(int a, int b) { // method body; return (a*b); } • Example void add() { // method body; } 29 Method sample example
  • 30.
    • There aretwo types of methods in Java: • Predefined Method • User-defined Method 30 Method Types
  • 31.
    • Predefined Method •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 runs in the background that is already stored in the library. 31 Predefined Method
  • 32.
    public class Demo { publicstatic void main(String[] args) { // using the max() method of Math class System.out.print("The maximum number is: " + Math.max(9,7)); } } 32 Method Types
  • 33.
    • The methodwritten by the user or programmer is known as a user- defined method. • These methods are modified according to the requirement. • Example int EvenOdd(int num) { //method body if(num%2==0) System.out.println(num+" is even"); else System.out.println(num+" is odd"); } 33 User-defined Method
  • 34.
    import java.util.Scanner; public classEvenOdd { public static void main (String args[]) { Scanner scan=new Scanner(System.in); System.out.print("Enter the number: "); //reading value from the user int num=scan.nextInt(); //method calling findEvenOdd(num); } 34 User-defined Method
  • 35.
    class Rectangle { doublel; double b; // display area of a rectangle void area() { System.out.print(“Area is "); System.out.println(l * b ); } } 35 Method Example Program to display area of Rectangle using method.
  • 36.
    class BoxDemo { publicstatic void main(String args[]) { Rectangle mybox1 = new Rectangle(); Rectangle mybox2 = new Rectangle(); // assign values to mybox1's instance variables mybox1.l = 10; mybox1.b = 20; mybox2.l = 3; /* assign different values to mybox2's instance variables */ mybox2.b = 6; mybox1.area(); // display volume of first box mybox2.area(); // display volume of second box } } 36 Method Example
  • 37.
    • If aclass has multiple methods having same name but different in parameters, it is known as Method Overloading. • If we have to perform only one operation, having same name of the methods increases the readability of the program. • Advantage of method overloading • Method overloading increases the readability of the program. • Different ways to overload the method • There are two ways to overload the method in java • By changing number of arguments • By changing the data type 37 Method Overloading
  • 38.
    int area(int r) { return3.14 * r * r; } int area(int h, int l) { return h * l; } 38 Method Overloading Example
  • 39.
    class OverloadDemo { voidtest() { System.out.println("No parameters"); } // Overload test for one integer parameter. void test(int a) { System.out.println("a: " + a); } // Overload test for two integer parameters. void test(int a, int b) { System.out.println("a and b: " + a + " " + b); } // Overload test for a double parameter double test(double a) { System.out.println("double a: " + a); return a*a; } } 39 class Overload { public static void main(String args[]) { OverloadDemo ob = new OverloadDemo(); double result; ob.test(); ob.test(10); ob.test(10, 20); result = ob.test(123.25); System.out.println("Result of ob.test(123.25): " + result); } } Method Overloading Example
  • 40.
    • This programgenerates the following output: No parameters a: 10 a and b: 10 20 double a: 123.25 Result of ob.test(123.25): 15190.5625 40 Method Overloading Example- Result
  • 41.
    • 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. 41 Constructor
  • 42.
    • It iscalled 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. • Rules for creating Java constructor • There are two rules defined for the constructor. • Constructor name must be the same as its class name • A Constructor must have no explicit return type • A Java constructor cannot be abstract, static, final. 42 Constructor
  • 43.
    • There aretwo types of constructors in Java: • Default constructor (no-arg constructor) • Parameterized constructor • Java Default Constructor • A constructor is called "Default Constructor" when it doesn't have any parameter. • Syntax of default constructor: <class_name>(){} • The default constructor is used to provide the default values to the object like 0, null, etc., depending on the type. 43 Constructor Types
  • 44.
    • Java ParameterizedConstructor • A constructor which has a specific number of parameters is called a parameterized constructor. • The parameterized constructor is used to provide different values to distinct objects. • However, you can provide the same values also. • Example Student(int i,String n){ id = i; name = n; } 44 Constructor Types
  • 45.
    45 class Bike1{ //creating adefault constructor Bike1() { System.out.println("Bike is created"); } public static void main(String args[]) { //calling a default constructor Bike1 b=new Bike1(); } } class Student { int id; String name; void display() { System.out.println(id+" "+name); } public static void main(String args[]) { Student s1=new Student(); Student s2=new Student(); //displaying values of the object s1.display(); s2.display(); } } Constructor Example
  • 46.
    46 class Student4{ int id; Stringname; //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[]) { //creating objects and passing values Student4 s1 = new Student4(111,"Karan"); Student4 s2 = new Student4(222,"Aryan"); s1.display(); s2.display(); } } Parameterized Constructor Example
  • 47.
    • Constructor overloadingin 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. 47 Constructor Overloading in Java
  • 48.
  • 49.
  • 50.
    • In Java,this is a reference variable that refers to the current object. • Usage of Java this keyword • this can be used to refer current class instance variable. • this can be used to invoke current class method (implicitly) • this() can be used to invoke current class constructor. • this can be passed as an argument in the method call. • this can be passed as argument in the constructor call. • this can be used to return the current class instance from the method. 50 this keyword in Java
  • 51.
    class Student{ int rollno; Stringname; float fee; Student(int rollno,String name,float fee){ rollno=rollno; name=name; fee=fee; } void display(){ System.out.println(rollno+" "+name+" "+fee); } } 51 Program without this keyword class TestThis { public static void main(String args[]) { Student s1=new Student(111,“Ankit",5000f); Student s2=new Student(112,“Sumit",6000f); s1.display(); s2.display(); } }
  • 52.
    52 0 null 0.0 0null 0.0 • Parameters (formal arguments/local veriables) and instance variables are same. • So, need to use this keyword to distinguish local variable and instance variable. Program output
  • 53.
    class Student{ int rollno; Stringname; 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); } } 53 Program with this keyword class TestThis { public static void main(String args[]) { Student s1=new Student(111,“Ankit",5000f); Student s2=new Student(112,“Sumit",6000f); s1.display(); s2.display(); } }
  • 54.
    class Student{ int rollno; Stringname; float fee; Student(int r, String n, float f){ rollno=r; name=n; fee=f; } void display(){ System.out.println(rollno+" "+name+" "+fee); } } 54 Program without this keyword class TestThis { public static void main(String args[]) { Student s1=new Student(111,“Ankit",5000f); Student s2=new Student(112,“Sumit",6000f); s1.display(); s2.display(); } }
  • 55.
    • The statickeyword in Java is used for memory management mainly. • The static keyword belongs to the class than an instance of the class. • The static can be: • Variable (also known as a class variable) • Method (also known as a class method) • Nested class • If you declare any variable as static, it is known as a static variable. 55 static keyword in Java
  • 56.
    • It makesyour program memory efficient (i.e., it saves memory). • Understanding the problem without static variable class Student{ int rollno; String name; String college=“DYP-ATU"; } • Suppose there are 500 students in my college. • Now all instance data members will get memory each time when the object is created. • "college" refers to the common property of all objects. • If we make it static, this field will get the memory only once. 56 static keyword in Java
  • 57.
    57 class Student{ int rollno;//instance variable String name; static String college =“DYP"; //static variable Student(int r, String n) { //constructor rollno = r; name = n; } void display () { System.out.println(rollno+" "+name+" "+college); } } public class TestStatic { public static void main(String args[]){ Student s1 = new Student(111,"Karan"); Student s2 = new Student(222,"Aryan"); //Student.college=“DYP"; s1.display(); s2.display(); } } static keyword Example
  • 58.