Ce diaporama a bien été signalé.
Nous utilisons votre profil LinkedIn et vos données d’activité pour vous proposer des publicités personnalisées et pertinentes. Vous pouvez changer vos préférences de publicités à tout moment.

Object Oriented Programming in Java (Slide 2/6)

Constructor in Java
Types of Java Constructors
Parameterized Constructor in Java
Constructor Overloading in Java
Copy Constructor in Java
Access Modifiers in java
Role of Private Constructor in Java
this keyword in java
Static keyword in java
Instance initializer block

  • Identifiez-vous pour voir les commentaires

Object Oriented Programming in Java (Slide 2/6)

  1. 1. Object Oriented Programming in Java Lecture Slides By Adil Aslam My Email Address is : adilaslam5959@gmail.com
  2. 2. About Me Introduction to Java Programming Language Notes By Adil Aslam i am Student of BSCS My email address: adilaslam5959@gmail.com
  3. 3. Introduction to Java Programming Language Notes By Adil Aslam Constructor in Java
  4. 4. Constructor in Java • Constructor in Java is a special type of method that is used to initialize the object. • Java constructor is invoked at the time of object creation. It constructs the values i.e. provides data for the object that is why it is known as constructor. • Rules for Creating Java Constructor • There are basically two rules defined for the constructor. • Constructor name must be same as its class name • Constructor must have no explicit return type Introduction to Java Programming Language Notes By Adil Aslam
  5. 5. Constructor in Java • Some Rules of Using Constructor : • Constructor Initializes an Object. • Constructor cannot be called like methods. • Constructors are called automatically as soon as object gets created. • Constructor don’t have any return Type. (even Void) • Constructor name is same as that of “Class Name“. • Constructor can accept parameter. • Default constructor automatically called when object is created. Introduction to Java Programming Language Notes By Adil Aslam
  6. 6. Constructor in Java • Types of Java Constructors • There are two Types of Constructors: • Default constructor (no-arg constructor) • Parameterized constructor Introduction to Java Programming Language Notes By Adil Aslam Type of Constructor Default Constructor Parameterized Constructor
  7. 7. Constructor in Java • Java Default Constructor: • A constructor that have no parameter is known as default constructor. • Syntax of Default Constructor: • Example Introduction to Java Programming Language Notes By Adil Aslam class_name() { } Rectangle() { }
  8. 8. Example of Default Constructor public class Rectangle { Rectangle() { System.out.println("Rectangle is created"); } public static void main(String[] args) { //Creating new object rec below Rectangle rec=new Rectangle(); } } Introduction to Java Programming Language Notes By Adil Aslam
  9. 9. Example of Default Constructor public class Rectangle { Rectangle() { System.out.println("Rectangle is created"); } public static void main(String[] args) { //Creating new object rec below Rectangle rec=new Rectangle(); } } Introduction to Java Programming Language Notes By Adil Aslam Class Name and Constructor Name are Same Default Constructor
  10. 10. Example of default Constructor public class Rectangle { Rectangle() { System.out.println("Rectangle is created"); } public static void main(String[] args) { //Creating new object rec below Rectangle rec=new Rectangle(); } } Introduction to Java Programming Language Notes By Adil Aslam Output is: Rectangle is created In this Example, we are Creating the no-arg Constructor in the Rectangle class. It will be Invoked at the time of Object Creation. Class Name and Constructor Name are Same Default Constructor
  11. 11. Explanation of Previous Program • First JVM searches for main() method in class whose access modifier is public • And this main() method should be static, as JVM invokes this method without instantiating the object • Return type should be void, as there is no need to send any return value to invoking JVM • So when JVM executes main() method, then below statement gets fired Rectangle rec=new Rectangle(); • This statement in turn will invoke default constructor i.e. no-arg constructor gets executed and prints the message inside default constructor Rectangle is created • Finally, program exits with success Introduction to Java Programming Language Notes By Adil Aslam
  12. 12. Another Example of Default Constructor public class Rectangle { int length; int breadth; Rectangle() { length = 20; breadth = 10; } public static void main(String args[]) { Rectangle r1 = new Rectangle(); System.out.println("Length of Rectangle : " + r1.length); System.out.println("Breadth of Rectangle : " + r1.breadth); } } Introduction to Java Programming Language Notes By Adil Aslam Two Instance Variables
  13. 13. Another Example of Default Constructor public class Rectangle { int length; int breadth; Rectangle() { length = 20; breadth = 10; } public static void main(String args[]) { Rectangle r1 = new Rectangle(); System.out.println("Length of Rectangle : " + r1.length); System.out.println("Breadth of Rectangle : " + r1.breadth); } } Introduction to Java Programming Language Notes By Adil Aslam Default Constructor
  14. 14. Another Example of Default Constructor public class Rectangle { int length; int breadth; Rectangle() { length = 20; breadth = 10; } public static void main(String args[]) { Rectangle r1 = new Rectangle(); System.out.println("Length of Rectangle : " + r1.length); System.out.println("Breadth of Rectangle : " + r1.breadth); } } Introduction to Java Programming Language Notes By Adil Aslam Initializing the Values of Instance Variables Output is: Length of Rectangle : 20 Breadth of Rectangle : 10
  15. 15. Explanation of Previous Program • new Operator will create an object. • As soon as Object gets created it will call Constructor: • In the above Constructor Instance Variables of Object r1 gets their own values. • Thus Constructor Initializes an Object as soon as after creation. • It will print Values initialized by Constructor : Introduction to Java Programming Language Notes By Adil Aslam Rectangle() { //This is default Constructor length = 20; breadth = 10; } System.out.println("Length of Rectangle : " + r1.length); System.out.println("Breadth of Rectangle : " + r1.breadth);
  16. 16. Another Example of Default Constructor-1 class Rectangle{ int length; int breadth; Rectangle() { length = 10; breadth = 10; } void setDimentions() { length = 20; breadth = 20; } Introduction to Java Programming Language Notes By Adil Aslam Two instance Variables Default Constructor
  17. 17. Another Example of Default Constructor-1 class Rectangle{ int length; int breadth; Rectangle() { length = 10; breadth = 10; } void setDimentions() { length = 20; breadth = 20; } Introduction to Java Programming Language Notes By Adil Aslam Two instance Variables default Constructor Method setDimensions return Nothing
  18. 18. Another Example of Default Constructor-2 public static void main(String args[]) { Rectangle r1 = new Rectangle(); System.out.println("Length of Rectangle : " + r1.length); System.out.println("Breadth of Rectangle : " + r1.breadth); r1.setDiamentions(); System.out.println("Length of Rectangle : " + r1.length); System.out.println("Breadth of Rectangle : " + r1.breadth); } } Introduction to Java Programming Language Notes By Adil Aslam Calling the Method with using the Reference of r1 object
  19. 19. Another Example of Default Constructor-2 public static void main(String args[]) { Rectangle r1 = new Rectangle(); System.out.println("Length of Rectangle : " + r1.length); System.out.println("Breadth of Rectangle : " + r1.breadth); r1.setDiamentions(); System.out.println("Length of Rectangle : " + r1.length); System.out.println("Breadth of Rectangle : " + r1.breadth); } } Introduction to Java Programming Language Notes By Adil Aslam Output is: Length of Rectangle : 10 Breadth of Rectangle : 10 Length of Rectangle : 20 Breadth of Rectangle : 20 After the Creation of Object , Instance Variables have their own values inside. As soon as we call method , values are Re-initialized.
  20. 20. Default Constructor • If there is no constructor in a class, compiler automatically creates a default constructor. • What is the Purpose of Default Constructor? • Default constructor provides the default values to the object like 0, null etc. depending on the type. Introduction to Java Programming Language Notes By Adil Aslam class Rectangle { } class Rectangle { Rectangle(){} } Compiler Rectangle.java Rectangle.class
  21. 21. Example of Default Constructor that Displays the Default Values public class Example{ int id; String name; void display() { System.out.println(id+“ "+name); } public static void main(String args[]){ Example s1=new Example(); Example s2=new Example(); s1.display(); s2.display(); } } Introduction to Java Programming Language Notes By Adil Aslam
  22. 22. Example of Default Constructor that Displays the Default Values public class Example{ int id; String name; void display() { System.out.println(id+" "+name); } public static void main(String args[]){ Example s1=new Example(); Example s2=new Example(); s1.display(); s2.display(); } } Introduction to Java Programming Language Notes By Adil Aslam Output is: 0 null 0 null Explanation: In the above class, we are not creating any constructor so compiler provides you a default constructor. Here 0 and null values are provided by default constructor.
  23. 23. Constructor in Java • Java Parameterized Constructor • A constructor that have parameters is known as parameterized constructor. • Why use Parameterized Constructor? • Parameterized constructor is used to provide different values to the distinct objects. • Syntax of Parameterized Constructor • Example Introduction to Java Programming Language Notes By Adil Aslam class_name(parameter_list) { } Rectangle (int len , int bre) { }
  24. 24. Constructor in Java • Java Parameterized Constructor • Constructor Can Take Value , Value is Called as – “Argument“. • Argument can be of any type i.e Integer, Character, Array or any Object. • Constructor can take any number of Argument. Introduction to Java Programming Language Notes By Adil Aslam
  25. 25. Example of Parameterized Constructor class Rectangle { int length; int breadth; Rectangle(int len , int bre) { length = len; breadth = bre; } public static void main(String args[]) { Rectangle r1 = new Rectangle(20,10); System.out.println("Length of Rectangle: " + r1.length); System.out.println("Breadth of Rectangle: "+ r1.breadth); } } Introduction to Java Programming Language Notes By Adil Aslam
  26. 26. Example of Parameterized Constructor class Rectangle { int length; int breadth; Rectangle(int len , int bre) { length = len; breadth = bre; } public static void main(String args[]) { Rectangle r1 = new Rectangle(20,10); System.out.println("Length of Rectangle: " + r1.length); System.out.println("Breadth of Rectangle: "+ r1.breadth); } } Introduction to Java Programming Language Notes By Adil Aslam Constructor with two Parameters
  27. 27. Example of Parameterized Constructor class Rectangle { int length; int breadth; Rectangle(int len , int bre) { length = len; breadth = bre; } public static void main(String args[]) { Rectangle r1 = new Rectangle(20,10); System.out.println("Length of Rectangle: " + r1.length); System.out.println("Breadth of Rectangle: "+ r1.breadth); } } Introduction to Java Programming Language Notes By Adil Aslam Here we Create an Object and Passing Arguments to Constructor as 20,10
  28. 28. Example of Parameterized Constructor class Rectangle { int length; int breadth; Rectangle(int len , int bre) { length = len; breadth = bre; } public static void main(String args[]) { Rectangle r1 = new Rectangle(20,10); System.out.println("Length of Rectangle: " + r1.length); System.out.println("Breadth of Rectangle: "+ r1.breadth); } } Introduction to Java Programming Language Notes By Adil Aslam Output is: Length of Rectangle: 20 Breadth of Rectangle: 10
  29. 29. Explanation of Previous Program • Carefully observe Previous program – We will found something like this – • This is Parameterized Constructor taking argument. These arguments are used for any purpose inside Constructor Body. • New Operator is used to Create Object. • We are passing Parameter to Constructor as 20,10. • These parameters are assigned to Instance Variables of the Class. Introduction to Java Programming Language Notes By Adil Aslam Rectangle r1 = new Rectangle(20,10);
  30. 30. Example of Parameterized Constructor class Rectangle { int length; int breadth; Rectangle(int length , int breadth) { length = length; breadth = breadth; } public static void main(String args[]) { Rectangle r1 = new Rectangle(20,10); System.out.println("Length of Rectangle: " + r1.length); System.out.println("Breadth of Rectangle: "+ r1.breadth); } } Introduction to Java Programming Language Notes By Adil Aslam Here Parameter (Formal Arguments) and Instance Variables Name are Same There is Ambiguity between the Instance Variable and Parameter or Local Variable
  31. 31. Example of Parameterized Constructor class Rectangle { int length; int breadth; Rectangle(int length , int breadth) { length = length; breadth = breadth; } public static void main(String args[]) { Rectangle r1 = new Rectangle(20,10); System.out.println("Length of Rectangle: " + r1.length); System.out.println("Breadth of Rectangle: "+ r1.breadth); } } Introduction to Java Programming Language Notes By Adil Aslam Output is: Length of Rectangle: 0 Breadth of Rectangle: 0 Due to Ambiguity Compiler Print the Default Values of the Instance Variables Here Compiler Understand “Assignment to itself “
  32. 32. Example of Parameterized Constructor class Rectangle { int length; int breadth; Rectangle(int length , int breadth) { this.length = length; this.breadth = breadth; } public static void main(String args[]) { Rectangle r1 = new Rectangle(20,10); System.out.println("Length of Rectangle: " + r1.length); System.out.println("Breadth of Rectangle: "+ r1.breadth); } } Introduction to Java Programming Language Notes By Adil Aslam Output is: Length of Rectangle: 20 Breadth of Rectangle: 10 Parameter (Formal Arguments) and Instance Variables are same that is Why we are Using this keyword to Distinguish Between Local Variable and Instance Variable.
  33. 33. More Example of Parameterized Constructor class Student{ int id; String name; Student(int i, String n){ id = i; name = n; } void display(){System.out.println(id+“ "+name);} public static void main(String args[]){ Student s1 = new Student(11,"Adil"); Student s2 = new Student(22,"Hina"); s1.display(); s2.display(); } } Introduction to Java Programming Language Notes By Adil Aslam
  34. 34. More Example of Parameterized Constructor class Student{ int id; String name; Student(int i, String n){ id = i; name = n; } void display(){System.out.println(id+" "+name);} public static void main(String args[]){ Student s1 = new Student(11,"Adil"); Student s2 = new Student(22,"Hina"); s1.display(); s2.display(); } } Introduction to Java Programming Language Notes By Adil Aslam Parameterized Constructor
  35. 35. More Example of Parameterized Constructor class Student{ int id; String name; Student(int i, String n){ id = i; name = n; } void display(){System.out.println(id+" "+name);} public static void main(String args[]){ Student s1 = new Student(11,"Adil"); Student s2 = new Student(22,"Hina"); s1.display(); s2.display(); } } Introduction to Java Programming Language Notes By Adil Aslam Parameterized Constructor Output is: 11 Adil 22 Hina
  36. 36. Point to be Note class Student{ int var=5; public Student(int num) { var=num; } public int getValue() { return var; } public static void main(String args[]){ Student ob = new Student(); System.out.println("value is: "+ob.getValue()); } Introduction to Java Programming Language Notes By Adil Aslam Output: It will throw a compilation error!!. The reason is when we don’t define any constructor in our class, compiler defines default one for us, however when we declare any constructor (in this example we have already defined a parameterized constructor), compiler doesn’t do it for us. Since we have defined a constructor in this code, compiler didn’t create default one. While creating object we am invoking default one, which doesn’t exist in this code. The code gives an compilation error. If we remove the parametrized constructor from the code above then the code would run fine because, java would generate the default constructor if it doesn’t find any in the code. Compiler Error Here
  37. 37. Difference Between Constructor and Method • The purpose of constructor is to create object of a class while the purpose of a method is to perform a task by executing java code. • Constructors cannot be abstract, final, static and synchronized while methods can be. • Constructors do not have return types while methods do. Introduction to Java Programming Language Notes By Adil Aslam
  38. 38. Difference Between Constructor and Method Java Constructor Java Method Constructor is used to initialize the state of an object. Method is used to expose behaviour of an object. Constructor must not have return type. Method must have return type. Constructor is invoked implicitly. Method is invoked explicitly. The java compiler provides a default constructor if you don't have any constructor. Method is not provided by compiler in any case. Constructor name must be same as the class name. Method name may or may not be same as class name. Introduction to Java Programming Language Notes By Adil Aslam
  39. 39. Constructor Overloading • Like methods, a constructor can also be overloaded. • Overloaded constructors are differentiated on the basis of their type of parameters or number of parameters. • Constructor overloading is not much different than method overloading. • In case of method overloading we have multiple methods with same name but different signature, whereas in Constructor overloading we have multiple constructor with different signature but only difference is that Constructor doesn't have return type in Java. • Why do we Overload constructors ? • Constructor overloading is done to construct object in different ways. Introduction to Java Programming Language Notes By Adil Aslam
  40. 40. Constructor Overloading • Why Constructor Overloading is Required in Java? • Constructor provides a way to create objects implicitly of any class using ‘new’ keyword • So, overloaded constructor serves many ways to create distinct objects using different types of data of same class • One classical example to discuss about constructor overloading is ‘StringBuffer’ class from ‘java.lang’ package • StringBuffer class has four overloaded constructors • StringBuffer(String str) is one of the parametrized constructor which has a initial capacity of 16 plus length of the String supplied • We can use this constructor if we have initial string value to supply • Or else, if we don’t have any idea about initial String to specify then simply use 1st overloaded constructor which has no argument (default constructor) Introduction to Java Programming Language Notes By Adil Aslam
  41. 41. Constructor Overloading • Different Ways to Overload Constructor in Java, by Changing • Number of input parameters • Data-type of input parameters • Order/sequence of input parameters, if they are of different data-types • Constructor Signature • Constructor signature consists of • Name of the constructor which should be same as that of class name • number of input parameters • their data types • access modifiers like private, default, protected or public • Access modifiers are not valid to consider in constructor overloading concept and in fact compiler throws exception if we overload constructor just by changing access modifiers keeping other things in constructor signature same Introduction to Java Programming Language Notes By Adil Aslam
  42. 42. Constructor Overloading • Things to Remember About Constructor Overloading (Constructor Signature) • Compiler checks 3 things when we overload constructor 1. constructor name (should be same as that of class name) 2. number of input parameters and 3. data-type of input parameters • –> Combination of number of input parameters & their data-type has to be different for successful compilation • –> Or else compiler throws duplicate error • Note: If name of the constructor differs and doesn’t have any return type then compiler threat this as method and throws compile time error Introduction to Java Programming Language Notes By Adil Aslam
  43. 43. Syntax of Overloaded Constructor Introduction to Java Programming Language Notes By Adil Aslam class ClassName { // Variable declaration // Constructor ClassName() { // body of constructor } ClassName(Parameter_List) { // body of constructor } : : ClassName(Parameter_List) { // body of constructor } // Methods }
  44. 44. Example of Constructor Overloading-1 class Student{ int id; String name; int age; Student(int i, String n) { id = i; name = n; } Student(int i, String n, int a){ id = i; name = n; age=a; } Introduction to Java Programming Language Notes By Adil Aslam Example on Constructor Overloading Based on Number of input Parameters
  45. 45. Example of Constructor Overloading-1 class Student{ int id; String name; int age; Student(int i, String n) { id = i; name = n; } Student(int i, String n, int a){ id = i; name = n; age=a; } Introduction to Java Programming Language Notes By Adil Aslam Both Constructors having same Name and Different Number of Parameters
  46. 46. Example of Constructor Overloading-2 void display() { System.out.println(id+" "+name+" "+age); } public static void main(String args[]){ Student s1 = new Student(11,"Adil"); Student s2 = new Student(22,"Hina",20); s1.display(); s2.display(); } } Introduction to Java Programming Language Notes By Adil Aslam Output is: 11 Adil 0 22 Hina 20
  47. 47. Example of Constructor Overloading-1 public class Employee { // member variables int employeeId; String employeeName; // parametrized constructor 1 (String, int) Employee(String name, int id) { this.employeeId = id; this.employeeName = name; } // parametrized constructor 2 (int, String) Employee(int id, String name) { this.employeeId = id; this.employeeName = name; } Introduction to Java Programming Language Notes By Adil Aslam Example on Constructor Overloading Based on data types of input Parameters
  48. 48. Example of Constructor Overloading-2 // display() method void displayEmployeeInfo() { System.out.println("Employee detailsnId: " + employeeId + "t Name: " + employeeName + "n"); } // main() method - entry point to JVM public static void main(String args[]) { Employee emp1 = new Employee("Adil", 23); emp1.displayEmployeeInfo(); Employee emp2 = new Employee(19, "Kashif"); emp2.displayEmployeeInfo(); } } Introduction to Java Programming Language Notes By Adil Aslam
  49. 49. Example of Constructor Overloading-2 // display() method void displayEmployeeInfo() { System.out.println("Employee detailsnId: " + employeeId + "t Name: " + employeeName + "n"); } // main() method - entry point to JVM public static void main(String args[]) { Employee emp1 = new Employee("Adil", 23); emp1.displayEmployeeInfo(); Employee emp2 = new Employee(19, "Kashif"); emp2.displayEmployeeInfo(); } } Introduction to Java Programming Language Notes By Adil Aslam Output is: Employee details Id: 23 Name: Adil Employee details Id: 19 Name: Kashif
  50. 50. Explanation of Previous Program • In previous example, both overloaded constructors have two input parameters with one is ‘String’ argument and another is ‘int’ argument • but their order/sequence of input parameters differs i.e.; • 1st constructor takes String as first argument and int as second argument • Whereas 2nd constructor takes int as first argument and String as second argument • So we can overload constructor based on their data types or say sequence of input parameters along with their data types • after creating both instances, displayEmployeeInfo() method is invoked to print employee details • which simply prints employee details such as Id and Name for this example Introduction to Java Programming Language Notes By Adil Aslam
  51. 51. Default Constructor v/s Parametrized Constructor Introduction to Java Programming Language Notes By Adil Aslam Sr. No. Default Constructor Parametrized Constructor 1 A constructor which takes no arguments is known as default constructor A constructor which takes one or more arguments is known as parametrized constructor 2 Compiler inserts a default no-arg constructor after compilation, if there is no explicit constructor defined in class When parametrized constructor are defined in class, then programmer needs to define default no-arg constructor explicitly if required 3 No need to pass any parameters while constructing new objects using default constructor At least one or more parameters needs to be passed while constructing new objects using argument constructors 4 Default constructor is used to initialize objects with same data Whereas parametrized constructor are used to create distinct objects with different data
  52. 52. Java Copy Constructor • There is no copy constructor in java. But, we can copy the values of one object to another like copy constructor in C++. • There are many ways to copy the values of one object into another in java. They are: • By Constructor • By Assigning the Values of one object into Another • By clone() Method of Object class • Let see first example of copy the values of one object into another using java constructor. Introduction to Java Programming Language Notes By Adil Aslam
  53. 53. Copy Constructor(By constructor)-1 class Student{ int id; String name; Student(int i, String n){ id = i; name = n; } Student(Student s){ id = s.id; name =s.name; } Introduction to Java Programming Language Notes By Adil Aslam
  54. 54. Copy Constructor(By constructor)-2 void display() { System.out.println(id+" "+name); } public static void main(String args[]){ Student s1 = new Student(11,"Adil"); Student s2 = new Student(s1); s1.display(); s2.display(); } } Introduction to Java Programming Language Notes By Adil Aslam Output is: 11 Adil 11 Adil
  55. 55. Copy Constructor(By Assigning the Values ) • We can copy the values of one object into another by assigning the objects values to another object. In this case, there is no need to create the constructor. • Let we see an example in next slide Introduction to Java Programming Language Notes By Adil Aslam
  56. 56. Copy Constructor(By Assigning the Values )-1 class Student{ int id; String name; Student(int i, String n){ id = i; name = n; } Student(){ } void display() { System.out.println(id+" "+name); } Introduction to Java Programming Language Notes By Adil Aslam
  57. 57. Copy Constructor(By Assigning the Values )-2 public static void main(String args[]) { Student s1 = new Student(11,"Adil"); Student s2 = new Student(); //assign values of object s1 to object s2 using reference s2.id=s1.id; s2.name=s1.name; s1.display(); s2.display(); } } Introduction to Java Programming Language Notes By Adil Aslam Output is: 11 Adil 11 Adil
  58. 58. Points to be Note • Q) Does Constructor Return any Value? • Answer: yes, that is current class instance (we cannot use return type yet it returns a value). • Q) Can Constructor Perform other tasks Instead of Initialization? • Answer: yes, like object creation, starting a thread, calling method etc. We can perform any operation in the constructor as you perform in the method. Introduction to Java Programming Language Notes By Adil Aslam
  59. 59. Point to Remember about Constructor in Java Class • First and most important point is that, name of the constructor should be same as that of class name • And next important point is, constructor don’t have any return type unlike methods (not even void) • Every concrete class and abstract class has a constructor • Constructor in interfaces is not allowed • It can have all Java statements and logic but shouldn’t return any value • Constructor can have zero arguments which are called default constructor (or no-arg constructor) • Constructor can have one or more input parameters which are called as parametrized constructor Introduction to Java Programming Language Notes By Adil Aslam
  60. 60. Point to Remember about Constructor in Java Class • Constructor cannot be inherited therefore it can’t be overridden • A class can have more than one constructor i.e.; Constructor Overloading • All four access modifier i.e.; private, default, protected, public are allowed (no restriction on access modifiers) • Private constructor are used for singleton design pattern • Non-access modifier like static, final, synchronized, abstract, strictfp, transient, volatile are not allowed Introduction to Java Programming Language Notes By Adil Aslam
  61. 61. Point to Remember about Constructor in Java Class • Duplicate Constructors not allowed. If you keep duplicate constructors, we will get compile time error. Introduction to Java Programming Language Notes By Adil Aslam class A{ A(int i) { // Duplicate Constructor } A(int i) { // Duplicate Constructor } }
  62. 62. Point to Remember about Constructor in Java Class • Multiple arguments of the constructors can’t have same name. If the two arguments have the same name, we will get compile time error. Introduction to Java Programming Language Notes By Adil Aslam class A { A(int i, int i) { // Duplicate Arguments Passed. It gives compile time error } }
  63. 63. Point to Remember about Constructor in Java Class • Only public, protected and private keywords are allowed before a constructor name. If you keep any other keyword before a constructor name, it gives compile time error. Introduction to Java Programming Language Notes By Adil Aslam class A{ final A() { //Constructor can not be final } static A() { //Constructor can not be static } abstract A() { //Constructors can not be abstract } }
  64. 64. Constructor Chaining • In object-oriented programming, constructor chaining is the technique of creating an instance of a class with multiple constructors, then using one constructor to call another. The primary use of constructor chaining is to make a program simpler, with fewer repeated lines of code. Introduction to Java Programming Language Notes By Adil Aslam We will Cover this topic in “use of this keyword” in Detail
  65. 65. Some Question with Answer • Q) What is Constructor in Java? • Constructor is a special type of method that is used to initialize an object • Every class has a constructor which is invoked at the time of object creation and provides values • As this provide values at the time of object creation that is why it is called as constructor (constructing default/initial values for object) • Q) Is it Mandatory to Define Constructor in Class? • It is not mandatory to define constructor in class because compiler inserts a default no-arg constructor during compilation • Note: compiler inserts default no-arg constructor when there is no constructor explicitly defined by programmer in class Introduction to Java Programming Language Notes By Adil Aslam
  66. 66. Some Question with Answer • Q) What are the Rules for Defining Constructor in a Class? • Name of the constructor should be same as that of class name • Constructor don’t have any return type unlike methods (not even void) • Q) Generally, What is the Name of Constructor in Java Class and Why it is so? • The name of constructor should be (must be) same as that of class name • It is just a syntax or convention followed in Java and requires no extra keyword Introduction to Java Programming Language Notes By Adil Aslam
  67. 67. Some Question with Answer • Q) What are the Types of Constructor in Java? • There are two types constructor • Default constructor (no-arg constructor) • Parametrized constructor • Q) What is no-arg Constructor? • Constructor which takes zero parameter is called as default constructor • Or, constructor with no argument is known as default constructor • It is also known as no-arg constructor Introduction to Java Programming Language Notes By Adil Aslam
  68. 68. Some Question with Answer • What is Default Constructor and why it is called Default Constructor. Reasons? • Constructor which takes zero parameter is called as default constructor • Compiler always inserts a no-arg constructor during compilation process if there is no other constructor defined explicitly by programmer • During such compilation process, compiler initializes all instance data members to default values like • 0 for int • null for String • false for Boolean • etc. • Since it is provides default values, it is alternatively called as default constructor (other is no-argument constructor) Introduction to Java Programming Language Notes By Adil Aslam
  69. 69. Some Question with Answer • Q) What is Parametrized Constructor? • Constructor which takes one or more parameters is called as parametrized constructor • Or, constructor with arguments is known as parametrized constructor • Q) What Happens, if we don’t Specify any Constructor Explicitly in Class? • If there is no constructor defined explicitly by programmer, then compiler inserts a default no-arg constructor during compilation • Q) When Compiler Provides Default Constructor? • If there is no constructor defined explicitly by programmer, then compiler inserts a default no-arg constructor during compilation Introduction to Java Programming Language Notes By Adil Aslam
  70. 70. Some Question with Answer • Q) Will Compiler Provides Default Non-Argument Constructor, when we Explicitly Defined Constructor in Class? • Compiler won’t provide/inserts default no-arg constructor during compilation process, if programmer defines constructor explicitly (whether it is default or parametrized constructor) • What Happens, when there is one Parametrized Constructor Explicitly Defined? • Compilation succeeds • But, if we try to create new object using default constructor then compiler throws error Introduction to Java Programming Language Notes By Adil Aslam
  71. 71. Some Question with Answer • Q) If we Define a Constructor in c]Class, then will it have Default Constructor? • No, there won’t be any default constructor • Programmer needs to define explicitly, if required • Q) Can we have both Default Constructor and Parametrized Constructor in Java class? • Yes, constructor overloading is possible • Q) Why return type is not Allowed for Constructor? • When we add return type to constructor, then compiler treats this as method with method name same as that of class name • Error: Compilation error will be thrown Introduction to Java Programming Language Notes By Adil Aslam
  72. 72. Some Question with Answer • Q) Whether class Compiles Successfully, if we add return-type to Constructor? • Compilation error will be thrown • To be precise, if we add return-type then compiler treats this as method with method name same as that of class name • Q) Can Constructor return any value, Although there is no return type? • As such there is no return type for constructor and it doesn’t return values • But constructor return values in the form of instances after initialization Introduction to Java Programming Language Notes By Adil Aslam
  73. 73. Some Question with Answer • Q) Can Constructor be final? • No, we cannot mark constructor as final • Non-access modifiers like final, static, transient, synchronized, volatile, strictfp are not allowed in constructor • Q) Is it valid to add ‘final’ to Constructor in Java? (Non-access modifier) • final keyword is not allowed in constructor • Non-access modifiers like final, static, transient, synchronized, volatile, strictfp are not allowed in constructor Introduction to Java Programming Language Notes By Adil Aslam
  74. 74. Some Question with Answer • Q) Can we Declare Constructor as ‘static’? • Non-access modifiers like final, static, transient, synchronized, volatile, strictfp are not allowed in constructor • Q) Why do we Overload Constructor? • Constructor provides a way to create object implicitly of any class using ‘new’ keyword • So, overloaded constructor serves many ways to create distinct objects using different types of data of same class • Q) How JVM Differentiates Between Constructor and Methods in Java during Compilation? • With the help of return type • Constructor is a special type of method which has no return type Introduction to Java Programming Language Notes By Adil Aslam
  75. 75. Introduction to Java Programming Language Notes By Adil Aslam Access Modifiers in java Private Default Protected Public
  76. 76. Access Modifiers in java • There are two types of modifiers in java: access modifiers and non-access modifiers. • The access modifiers in java specifies accessibility (scope) of a data member, method, constructor or class. • There are 4 Types of Java Access Modifiers: • private • default • protected • public • There are many non-access modifiers such as static, abstract, synchronized, native, volatile, transient etc. Here, we will learn access modifiers. Introduction to Java Programming Language Notes By Adil Aslam
  77. 77. Access Modifiers in java • Access Control Modifiers • Java provides a number of access modifiers to set access levels for classes, variables, methods and constructors. The four access levels are − • Visible to the package, the default. No modifiers are needed. • Visible to the class only (private). • Visible to the world (public). • Visible to the package and all subclasses (protected). Introduction to Java Programming Language Notes By Adil Aslam
  78. 78. Access Modifiers in java • Non-Access Modifiers • Java provides a number of non-access modifiers to achieve many other functionality. • The static modifier for creating class methods and variables. • The final modifier for finalizing the implementations of classes, methods, and variables. • The abstract modifier for creating abstract classes and methods. • The synchronized and volatile modifiers, which are used for threads. Introduction to Java Programming Language Notes By Adil Aslam
  79. 79. Access Modifiers in java Introduction to Java Programming Language Notes By Adil Aslam Private Default Protected Public Accessibility More Restrictive Less Restrictive
  80. 80. Access Modifiers in java • 1) private Access Modifier • The private access modifier is accessible only within class. • Methods, variables, and constructors that are declared private can only be accessed within the declared class itself. • Private access modifier is the most restrictive access level. Class and interfaces cannot be private. • Variables that are declared private can be accessed outside the class, if public getter methods are present in the class. • Using the private modifier is the main way that an object encapsulates itself and hides data from the outside world. Introduction to Java Programming Language Notes By Adil Aslam
  81. 81. Private Access Modifier public class Test{ private int data=40; public static void main(String args[]){ Test ex = new Test(); System.out.println("Data is: "+ex.data); } } Introduction to Java Programming Language Notes By Adil Aslam
  82. 82. Private Access Modifier public class Test{ private int data=40; public static void main(String args[]){ Test ex = new Test(); System.out.println("Data is: "+ex.data); } } Introduction to Java Programming Language Notes By Adil Aslam Here the data variable of the Example class is private and this Variable Accessed from same class itself
  83. 83. Private Access Modifier public class Test{ private int data=40; public static void main(String args[]){ Test ex = new Test(); System.out.println("Data is: "+ex.data); } } Introduction to Java Programming Language Notes By Adil Aslam Data Variable is Assess in the Same class where it is Defined
  84. 84. Private Access Modifier public class Test{ private int data=40; public static void main(String args[]){ Test ex = new Test(); System.out.println("Data is: "+ex.data); } } Introduction to Java Programming Language Notes By Adil Aslam Output is: Data is: 40
  85. 85. Private Access Modifier public class Test{ private int data; public static void main(String args[]){ ex.data=40; Test ex = new Test(); System.out.println("Data is: "+ex.data); } } Introduction to Java Programming Language Notes By Adil Aslam Output is: Data is: 40 Same Program as Previous but single Modification Now we set the value of the Variable here using the object of Example class
  86. 86. Private Access Modifier class A{ private int data=40; private void msg() { System.out.println("Hello java");} } public class Test{ public static void main(String args[]){ A obj=new A(); System.out.println(obj.data); //Compile Time Error obj.msg(); //Compile Time Error } } Introduction to Java Programming Language Notes By Adil Aslam
  87. 87. Private Access Modifier class A{ private int data=40; private void msg() { System.out.println("Hello java");} } public class Test{ public static void main(String args[]){ A obj=new A(); System.out.println(obj.data); //Compile Time Error obj.msg(); //Compile Time Error } } Introduction to Java Programming Language Notes By Adil Aslam This is first class where we Declare a private Variable and Define private Method
  88. 88. Private Access Modifier class A{ private int data=40; private void msg() { System.out.println("Hello java");} } public class Test{ public static void main(String args[]){ A obj=new A(); System.out.println(obj.data); //Compile Time Error obj.msg(); //Compile Time Error } } Introduction to Java Programming Language Notes By Adil Aslam This is Second class where we try to Access private Variable and Method
  89. 89. Private Access Modifier class A{ private int data=40; private void msg() { System.out.println("Hello java");} } public class Test{ public static void main(String args[]){ A obj=new A(); System.out.println(obj.data); //Compile Time Error obj.msg(); //Compile Time Error } } Introduction to Java Programming Language Notes By Adil Aslam Instance Variable is Private Here
  90. 90. Private Access Modifier class A{ private int data=40; private void msg() { System.out.println("Hello java");} } public class Test{ public static void main(String args[]){ A obj=new A(); System.out.println(obj.data); //Compile Time Error obj.msg(); //Compile Time Error } } Introduction to Java Programming Language Notes By Adil Aslam Private Method is Here
  91. 91. Private Access Modifier class A{ private int data=40; private void msg() { System.out.println("Hello java");} } public class Test{ public static void main(String args[]){ A obj=new A(); System.out.println(obj.data); //Compile Time Error obj.msg(); //Compile Time Error } } Introduction to Java Programming Language Notes By Adil Aslam Here, the data Variable of the A class is Private, so there's no way for other Classes to Retrieve or set its value Directly.
  92. 92. Private Access Modifier • So, if we want to make this variable available to the outside world, we defined two public methods: • getter(), which returns the value of variable, and • setter(parameter), which sets its value of the variable. Introduction to Java Programming Language Notes By Adil Aslam class A { private int data; public int getA() { return this.data; } public void setA(int data) { this.data=data; } }
  93. 93. Private Access Modifier class A{ private int data; public int getA() { return this.data; } public void setA(int data) { this.data=data; } } public class Test{ public static void main(String args[]){ A obj=new A(); obj.setA(12); System.out.println("Data is: "+obj.getA()); } } Introduction to Java Programming Language Notes By Adil Aslam
  94. 94. Private Access Modifier class A{ private int data; public void setA(int data) { this.data=data; } public int getA() { return this.data; } } public class Test{ public static void main(String args[]){ A obj=new A(); obj.setA(12); System.out.println("Data is: "+obj.getA()); } } Introduction to Java Programming Language Notes By Adil Aslam Private Instance Variable
  95. 95. Private Access Modifier class A{ private int data; public void setA(int data) { this.data=data; } public int getA() { return this.data; } } public class Test{ public static void main(String args[]){ A obj=new A(); obj.setA(12); System.out.println("Data is: "+obj.getA()); } } Introduction to Java Programming Language Notes By Adil Aslam Public Setter Method
  96. 96. Private Access Modifier class A{ private int data; public void setA(int data) { this.data=data; } public int getA() { return this.data; } } public class Test{ public static void main(String args[]){ A obj=new A(); obj.setA(12); System.out.println("Data is: "+obj.getA()); } } Introduction to Java Programming Language Notes By Adil Aslam Public Getter Method
  97. 97. Private Access Modifier class A{ private int data; public void setA(int data) { this.data=data; } public int getA() { return this.data; } } public class Test{ public static void main(String args[]){ A obj=new A(); obj.setA(12); System.out.println("Data is: "+obj.getA()); } } Introduction to Java Programming Language Notes By Adil Aslam Here we Set the Value of the Private Variable
  98. 98. Private Access Modifier class A{ private int data; public void setA(int data) { this.data=data; } public int getA() { return this.data; } } public class Test{ public static void main(String args[]){ A obj=new A(); obj.setA(12); System.out.println("Data is: "+obj.getA()); } } Introduction to Java Programming Language Notes By Adil Aslam Here we Get the Value of the Private Variable
  99. 99. Private Access Modifier class A{ private int data; public void setA(int data) { this.data=data; } public int getA() { return this.data; } } public class Test{ public static void main(String args[]){ A obj=new A(); obj.setA(12); System.out.println("Data is: "+obj.getA()); } } Introduction to Java Programming Language Notes By Adil Aslam Output is: Data is: 12 Accessing possible
  100. 100. Role of Private Constructor • The private modifier when applied to a constructor works in much the same way as when applied to a normal method or even an instance variable. • Defining a constructor with the private modifier says that only the native class (as in the class in which the private constructor is defined) is allowed to create an instance of the class, and no other caller is permitted to do so. • There are two possible reasons why one would want to use a private constructor – the first is that you don’t want any objects of your class to be created at all, and the second is that you only want objects to be created internally – as in only created in your class. Introduction to Java Programming Language Notes By Adil Aslam
  101. 101. Role of Private Constructor • 1.Private Constructors can be used in the Singleton Pesign pattern • Why would you want objects of your class to only be created internally? • This could be done for any reason, but one possible reason is that you want to implement a singleton. A singleton is a design pattern that allows only one instance of your class to be created, and this can be accomplished by using a private constructor. Introduction to Java Programming Language Notes By Adil Aslam
  102. 102. Role of Private Constructor • 2.Private Constructors can Prevent Creation of Objects • The other possible reason for using a private constructor is to prevent object construction entirely. When would it make sense to do something like that? Of course, when creating an object doesn’t make sense – and this occurs when the class only contains static members. And when a class contains only static members, those members can be accessed using only the class name – no instance of the class needs to be created. Introduction to Java Programming Language Notes By Adil Aslam
  103. 103. Role of Private Constructor • Java always provides a default, no-argument, public constructor if no programmer-defined constructor exists. Creating a private no-argument constructor essentially prevents the usage of that default constructor, thereby preventing a caller from creating an instance of the class. Note that the private constructor may even be empty. • Let see an example in the next slide if we make any class constructor private, we cannot create the instance of that class from outside the class Introduction to Java Programming Language Notes By Adil Aslam
  104. 104. Role of Private Constructor class A{ private A(){ //private constructor } void msg(){ System.out.println("Hello java");} } public class Test{ public static void main(String args[]){ A obj=new A(); //Compile Time Error } } Introduction to Java Programming Language Notes By Adil Aslam
  105. 105. Access Modifiers in java • 2) public Access Modifier • The public access modifier is accessible everywhere. It has the widest scope among all other modifiers. • A class, method, constructor, interface, etc. declared public can be accessed from any other class. Therefore, fields, methods, blocks declared inside a public class can be accessed from any class belonging to the Java Universe. • However, if the public class we are trying to access is in a different package, then the public class still needs to be imported. Because of class inheritance, all public methods and variables of a class are inherited by its subclasses. Introduction to Java Programming Language Notes By Adil Aslam Note: About package we Learn Later in Detail.. 
  106. 106. public Access Modifier class A{ public int data=40; } public class Test{ public static void main(String args[]){ A obj=new A(); System.out.println("Data is: "+obj.data); } } Introduction to Java Programming Language Notes By Adil Aslam
  107. 107. public Access Modifier class A{ public int data=40; } public class Test{ public static void main(String args[]){ A obj=new A(); System.out.println("Data is: "+obj.data); } } Introduction to Java Programming Language Notes By Adil Aslam public Instance Variable and Accessible in other Classes
  108. 108. public Access Modifier class A{ public int data=40; } public class Test{ public static void main(String args[]){ A obj=new A(); System.out.println("Data is: "+obj.data); } } Introduction to Java Programming Language Notes By Adil Aslam Output is: Data is: 40
  109. 109. Access Modifiers in java • 3) protected Access Modifier • 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. • Protected access gives the subclass a chance to use the helper method or variable, while preventing a nonrelated class from trying to use it. Introduction to Java Programming Language Notes By Adil Aslam
  110. 110. protected Access Modifier class A{ protected int data=40; } public class Test{ public static void main(String args[]){ A obj=new A(); System.out.println("Data is: "+obj.data); } } Introduction to Java Programming Language Notes By Adil Aslam
  111. 111. protected Access Modifier class A{ protected int data=40; } public class Test{ public static void main(String args[]){ A obj=new A(); System.out.println("Data is: "+obj.data); } } Introduction to Java Programming Language Notes By Adil Aslam Protected Instance Variable
  112. 112. protected Access Modifier class A{ protected int data=40; } public class Test{ public static void main(String args[]){ A obj=new A(); System.out.println("Data is: "+obj.data); } } Introduction to Java Programming Language Notes By Adil Aslam Output is: Data is: 40 Access Protected Instance Variable in Other class
  113. 113. protected Access Modifier class AudioPlayer { protected boolean openSpeaker(Speaker sp) { // implementation details } } class StreamingAudioPlayer { boolean openSpeaker(Speaker sp) { // implementation details } } Introduction to Java Programming Language Notes By Adil Aslam Here, if we define openSpeaker() method as private, then it would not be accessible from any other class other than AudioPlayer. If we define it as public, then it would become accessible to all the outside world. But our intention is to expose this method to its subclass only, that’s why we have used protected modifier.
  114. 114. Access Modifiers in java • 4) default Access Modifier • Default access modifier means we do not explicitly declare an access modifier for a class, field, method, etc. • A variable or method declared without any access control modifier is available to any other class in the same package. The fields in an interface are implicitly public static final and the methods in an interface are by default public. • The default modifier is accessible only within package. Introduction to Java Programming Language Notes By Adil Aslam
  115. 115. default Access Modifier class MyCalculator { int Add(int x,int y) { return x+y; } } class Test { public static void main(String arg[]) { MyCalculator M = new MyCalculator(); //Calling Add() through Object System.out.println("The sum is : " + M.Add(10,20)); } } Introduction to Java Programming Language Notes By Adil Aslam
  116. 116. default Access Modifier class MyCalculator { int Add(int x,int y) { return x+y; } } class Test { public static void main(String arg[]) { MyCalculator M = new MyCalculator(); //Calling Add() through Object System.out.println("The sum is : " + M.Add(10,20)); } } Introduction to Java Programming Language Notes By Adil Aslam We do not Explicitly Declare an Access Modifier Output is: The sum is : 30
  117. 117. Access Modifiers in java public private protected < unspecified > class allowed not allowed not allowed allowed constructor allowed allowed allowed allowed variable allowed allowed allowed allowed method allowed allowed allowed allowed Introduction to Java Programming Language Notes By Adil Aslam class subclass package outside private allowed not allowed not allowed not allowed protected allowed allowed allowed not allowed public allowed allowed allowed allowed < unspecified > allowed not allowed allowed not allowed
  118. 118. this keyword in java Introduction to Java Programming Language Notes By Adil Aslam
  119. 119. This keyword in java • this is a reference variable that refers to the current object. It is a keyword in java language represents current class object. Introduction to Java Programming Language Notes By Adil Aslam this State Behavior Object Reference variable
  120. 120. This keyword in java • Usage of this keyword • It can be used to refer current class instance variable. • this() can be used to invoke current class constructor. • It can be used to invoke current class method (implicitly) • It can be passed as an argument in the method call. • It can be passed as argument in the constructor call. • It can also be used to return the current class instance. Introduction to Java Programming Language Notes By Adil Aslam
  121. 121. This keyword in java • Why use this keyword in java ? • The main purpose of using this keyword is to differentiate the formal parameter and data members of class, whenever the formal parameter and data members of the class are similar then jvm get ambiguity (no clarity between formal parameter and member of the class) • To differentiate between formal parameter and data member of the class, the data member of the class must be preceded by "this". • "this" keyword can be use in two ways. • this . (this dot) • this() (this off) Introduction to Java Programming Language Notes By Adil Aslam
  122. 122. This keyword in java • Usage of this keyword • It can be used to refer current class instance variable. • this() can be used to invoke current class constructor. • It can be used to invoke current class method (implicitly) • It can be passed as an argument in the method call. • It can be passed as argument in the constructor call. • It can also be used to return the current class instance. Introduction to Java Programming Language Notes By Adil Aslam
  123. 123. This keyword in java • this . (this dot) • which can be used to differentiate variable of class and formal parameters of method or constructor. • "this" keyword are used for two purpose, they are • It always points to current class object. • Whenever the formal parameter and data member of the class are similar and JVM gets an ambiguity (no clarity between formal parameter and data members of the class). • To differentiate between formal parameter and data member of the class, the data members of the class must be preceded by "this". Introduction to Java Programming Language Notes By Adil Aslam
  124. 124. This keyword in java • Syntax • Note: If any variable is preceded by "this" JVM treated that variable as class variable. Introduction to Java Programming Language Notes By Adil Aslam this.data member of current class. This is dot Operator
  125. 125. Example Without using this keyword-1 class Student{ int id; String name; Student(int id, String name){ id = id; name = name; } void display() { System.out.println(id+" "+name); } Introduction to Java Programming Language Notes By Adil Aslam
  126. 126. Example Without using this keyword-1 class Student{ int id; String name; Student(int id, String name){ id = id; name = name; } void display() { System.out.println(id+" "+name); } Introduction to Java Programming Language Notes By Adil Aslam Parameter (Formal Arguments) and Instance Variables are Same
  127. 127. Example Without using this keyword-1 class Student{ int id; String name; Student(int id, String name){ id = id; name = name; } void display() { System.out.println(id+" "+name); } Introduction to Java Programming Language Notes By Adil Aslam Local Variable and Instance Variable Name are Same Parameter (Formal Arguments) and Instance Variables are Same
  128. 128. Example Without using this keyword-2 public static void main(String args[]){ Student s1 = new Student(11,"Adil"); Student s2 = new Student (22,"Hina"); s1.display(); s2.display(); } } Introduction to Java Programming Language Notes By Adil Aslam Output is: 0 null 0 null In the Above Example, Parameter (formal arguments) and Instance Variables are same that is why we are using "this" keyword to Distinguish Between Local Variable and instance Variable.
  129. 129. Example Without using this keyword-2 public static void main(String args[]){ Student s1 = new Student(11,"Adil"); Student s2 = new Student (22,"Hina"); s1.display(); s2.display(); } } Introduction to Java Programming Language Notes By Adil Aslam Default Values of Instance Variables Output is: 0 null 0 null In the Above Example, Parameter (formal arguments) and Instance Variables are same that is why we are using "this" keyword to Distinguish Between Local Variable and instance Variable.
  130. 130. Solution of The Previous Problem by this Keyword-1 class Student{ int id; String name; Student(int id, String name){ this.id = id; this.name = name; } void display() { System.out.println(id+" "+name); } Introduction to Java Programming Language Notes By Adil Aslam
  131. 131. Solution of The Previous Problem by this Keyword-1 class Student{ int id; String name; Student(int id, String name){ this.id = id; this.name = name; } void display() { System.out.println(id+" "+name); } Introduction to Java Programming Language Notes By Adil Aslam Using this keyword to Distinguish Between Local Variables and Instance Variables.
  132. 132. Solution of The Previous Problem by this Keyword-1 public static void main(String args[]){ Student s1 = new Student(11,"Adil"); Student s2 = new Student (22,"Hina"); s1.display(); s2.display(); } } Introduction to Java Programming Language Notes By Adil Aslam Output is: 11 Adil 22 Hina
  133. 133. This keyword in java Note for Previous Example • Note 1: The scope of "this" keyword is within the class. • Note 2: The main purpose of using "this" keyword in real life application is to differentiate variable of class or formal parameters of methods or constructor (it is highly recommended to use the same variable name either in a class or method and constructor while working with similar objects). Introduction to Java Programming Language Notes By Adil Aslam
  134. 134. Program Where this Keyword is Not Required-1 class Student{ int id; String name; Student(int i, String n){ id = i; name = n; } void display() { System.out.println(id+" "+name); } Introduction to Java Programming Language Notes By Adil Aslam
  135. 135. Program Where this Keyword is Not Required-1 class Student{ int id; String name; Student(int i, String n){ id = i; name = n; } void display() { System.out.println(id+" "+name); } Introduction to Java Programming Language Notes By Adil Aslam Local Variables(Formal Arguments) and Instance Variables are Different, there is no Need to use this Keyword
  136. 136. Program Where this Keyword is Not Required-1 public static void main(String args[]){ Student s1 = new Student(11,"Adil"); Student s2 = new Student (22,"Hina"); s1.display(); s2.display(); } } Introduction to Java Programming Language Notes By Adil Aslam Output is: 11 Adil 22 Hina
  137. 137. Another Example of this keyword-1 class Student { int Roll; String Name; double Marks; //Parameterize Constructor 1 Student(int R, double Mks, String Nm) { Roll = R; Name = Nm; Marks = Mks; } Introduction to Java Programming Language Notes By Adil Aslam
  138. 138. Another Example of this keyword-2 //Parameterize Constructor 2 Student(String Name, double Marks, int Roll) { Roll = Roll; Name = Name; Marks = Marks; } //Parameterize Constructor 3 Student(int Roll, String Name, double Marks) { this.Roll = Roll; this.Name = Name; this.Marks = Marks; } Introduction to Java Programming Language Notes By Adil Aslam
  139. 139. Another Example of this keyword-3 void Display() { System.out.println("Roll : " + Roll); System.out.println("Name : " + Name); System.out.println("Marks : " + Marks); } public static void main(String[] args) { Student S1 = new Student(1,89.63,"Adil Aslam"); Student S2 = new Student("Asif Aslam",78.53,2); Student S3 = new Student(3,"Hina Ameen",68.94); System.out.println("Details of Student 1 : "); S1.Display(); System.out.println("Details of Student 2 : "); S2.Display(); System.out.println("Details of Student 3 : "); S3.Display(); } } Introduction to Java Programming Language Notes By Adil Aslam
  140. 140. Output of Previous Program Details of Student 1 : Roll : 1 Name : Adil Aslam Marks : 89.63 Details of Student 2 : Roll : 0 Name : null Marks : 0.0 Details of Student 3 : Roll : 3 Name : Hina Ameen Marks : 68.94 Introduction to Java Programming Language Notes By Adil Aslam
  141. 141. Explanation of Previous Program • In constructor 1, variables declared in argument list different from variables declared as class data members. When compiler doesn't find Roll, Name, Marks as local variable, then it will find Roll, Name, Marks in class scope and assign values to them. In this case no 'this' keyword is required because both local variables and data members have different names. • But Constructor 2 will not initialize class data members. When we pass values to constructor 2, it will initialize values to itself local variables because variables declared in argument list and variable declared as data members are of same name. • In this situation, we use 'this' keyword to differentiate local variable and class data members as shown in constructor 3. Introduction to Java Programming Language Notes By Adil Aslam
  142. 142. This keyword in java • Usage of this keyword • It can be used to refer current class instance variable. • this() can be used to invoke current class constructor. • It can be used to invoke current class method (implicitly) • It can be passed as an argument in the method call. • It can be passed as argument in the constructor call. • It can also be used to return the current class instance. Introduction to Java Programming Language Notes By Adil Aslam
  143. 143. This keyword in java • this () • which can be used to call one constructor within the another constructor without creation of objects multiple time for the same class. • The this() constructor call can be used to invoke the current class constructor (constructor chaining). • This approach is better if you have many constructors in the class and want to reuse that constructor. • Syntax Introduction to Java Programming Language Notes By Adil Aslam this(); // call no parametrized or default constructor this(value1,value2,.....) //call parametrize constructor
  144. 144. this() Used to Invoked Current Class Constructor-1 //Program of this() constructor call (constructor chaining) class Student{ int id; String name; Student() { System.out.println("default constructor is invoked"); } Student(int id, String name) { this (); this.id = id; this.name = name; } Introduction to Java Programming Language Notes By Adil Aslam
  145. 145. this() Used to Invoked Current Class Constructor-1 //Program of this() constructor call (constructor chaining) class Student{ int id; String name; Student() { System.out.println("default constructor is invoked"); } Student(int id, String name) { this (); this.id = id; this.name = name; } Introduction to Java Programming Language Notes By Adil Aslam Here this() Used to Invoked Current class Constructor.
  146. 146. this() Used to Invoked Current Class Constructor-1 void display(){ System.out.println(id+" "+name); } public static void main(String args[]){ Student e1 = new Student(11,"Adil"); Student e2 = new Student(22,"Hina"); e1.display(); e2.display(); } } Introduction to Java Programming Language Notes By Adil Aslam Output is: default constructor is invoked default constructor is invoked 11 Adil 22 Hina
  147. 147. Where to Use this() Constructor Call? • The this() constructor call should be used to reuse the constructor in the constructor. It maintains the chain between the constructors i.e. • it is used for constructor chaining. Let's see the example given in next slide that displays the actual use of this keyword. Introduction to Java Programming Language Notes By Adil Aslam
  148. 148. Where to Use This() Constructor Call?-1 class Student{ int id; String name; String city; Student(int id, String name){ this.id = id; this.name = name; } Student(int id, String name, String city){ this(id , name); //now no need to initialize id and name this.city=city; } Introduction to Java Programming Language Notes By Adil Aslam
  149. 149. Where to Use This() Constructor Call?-1 void display(){ System.out.println(id+" "+name+" "+city); } public static void main(String args[]){ Student e1 = new Student(11,"Adil"); Student e2 = new Student(22,"Hina",“FSD"); e1.display(); e2.display(); } } Introduction to Java Programming Language Notes By Adil Aslam Output is: 11 Adil null 22 Hina FSD
  150. 150. Call to this() Must be the First Statement in Constructor-1 class Student{ int id; String name; String city; Student(int id, String name){ this.id = id; this.name = name; } Student(int id, String name, String city){ this.city=city; this(id , name); } Introduction to Java Programming Language Notes By Adil Aslam Call to this() must be the first Statement in Constructor Compiler Error
  151. 151. this() Used to Invoked Current Class Constructor class Student{ int id; String name; String city; Student(int id, String name){ this.id = id; this.name = name; } Student(int id, String name){ this.city=city; this(id); } Introduction to Java Programming Language Notes By Adil Aslam class Student{ int id; String name; String city; Student(int id, String name){ this.id = id; this.name = name; } Student(int id, String name){ this(id); this.city=city; } Correct use of “this()” Incorrect use of “this()”
  152. 152. this() Used to Invoked Current Class Constructor class Student{ int id; String name; String city; Student(int id, String name){ this.id = id; this.name = name; } Student(int id, String name){ this.city=city; this(id); } Introduction to Java Programming Language Notes By Adil Aslam class Student{ int id; String name; String city; Student(int id, String name){ this.id = id; this.name = name; } Student(int id, String name){ this(id); this.city=city; } Correct use of “this()” Incorrect use of “this()”
  153. 153. This keyword in java • Usage of this keyword • It can be used to refer current class instance variable. • this() can be used to invoke current class constructor. • It can be used to invoke current class method (implicitly) • It can be passed as an argument in the method call. • It can be passed as argument in the constructor call. • It can also be used to return the current class instance. Introduction to Java Programming Language Notes By Adil Aslam
  154. 154. This keyword in java • By using this keyword you can invoke the method of the current class. If you do not use the this keyword, compiler automatically adds this keyword at time of invoking of the method. Introduction to Java Programming Language Notes By Adil Aslam class Student { void show() {} void marks() { show(); } } public static void main( String args[]){ Student s = new Student(); s.marks(); } } class Student { void show() {} void marks() { this.show(); } } public static void main( String args[]){ Student s = new Student(); s.marks(); } } Compiler
  155. 155. This keyword in java • By using this keyword you can invoke the method of the current class. If you do not use the this keyword, compiler automatically adds this keyword at time of invoking of the method. Introduction to Java Programming Language Notes By Adil Aslam class Student { void show() {} void marks() { show(); } } public static void main( String args[]){ Student s = new Student(); s.marks(); } } class Student { void show() {} void marks() { this.show(); } } public static void main( String args[]){ Student s = new Student(); s.marks(); } } Compiler “this” is Added by Compiler
  156. 156. this Keyword Used to Invoke Current Class Method (Implicitly)-1 class Student { void show() { System.out.println("Hina got A+"); } void marks() { //no need to use this here because compiler does it. this.show(); } void display() { show(); //compiler act marks() as this.marks() } Introduction to Java Programming Language Notes By Adil Aslam
  157. 157. this Keyword Used to Invoke Current Class Method (Implicitly)-2 public static void main(String args[]) { Student s = new Student(); s.display(); } } Introduction to Java Programming Language Notes By Adil Aslam Output is: Hina got A+
  158. 158. This keyword in java • Usage of this keyword • It can be used to refer current class instance variable. • this() can be used to invoke current class constructor. • It can be used to invoke current class method (implicitly) • It can be passed as an argument in the method call. • It can be passed as argument in the constructor call. • It can also be used to return the current class instance. Introduction to Java Programming Language Notes By Adil Aslam
  159. 159. This keyword in java • As Argument in a Method • this keyword can also be passed as an argument to some method in a class. It is used to represent an object of that class. • Let see an Example in next slide. Introduction to Java Programming Language Notes By Adil Aslam
  160. 160. this Keyword can be Passed As an Argument class Student{ void method1(Student m1){ System.out.println("This is method 1"); } void method2(){ method1(this); } public static void main (String[] args) { Student m = new Student(); m.method2(); } } Introduction to Java Programming Language Notes By Adil Aslam
  161. 161. this Keyword can be Passed As an Argument class Student{ void method1(Student m1){ System.out.println("This is method 1"); } void method2(){ method1(this); } public static void main (String[] args) { Student m = new Student(); m.method2(); } } Introduction to Java Programming Language Notes By Adil Aslam Here Calling Method1 And “this” is Passing as a Argument Here
  162. 162. this Keyword can be Passed As an Argument class Student{ void method1(Student m1){ System.out.println("This is method 1"); } void method2(){ method1(this); } public static void main (String[] args) { Student m = new Student(); m.method2(); } } Introduction to Java Programming Language Notes By Adil Aslam In the this example, method1 is called inside method2. Since method1 has object 'm1' of class Student as its parameter, so while calling it inside method2, we passed this keyword as its argument. So, it will pass the current instance of the class Method with which we are dealing at that time.
  163. 163. this Keyword can be Passed As an Argument class Student{ void method1(Student m1){ System.out.println("This is method 1"); } void method2(){ method1(this); } public static void main (String[] args) { Student m = new Student(); m.method2(); } } Introduction to Java Programming Language Notes By Adil Aslam Output is: This is method 1
  164. 164. This keyword in java • Usage of this keyword • It can be used to refer current class instance variable. • this() can be used to invoke current class constructor. • It can be used to invoke current class method (implicitly) • It can be passed as an argument in the method call. • It can be passed as argument in the constructor call. • It can also be used to return the current class instance. Introduction to Java Programming Language Notes By Adil Aslam
  165. 165. This keyword in java • The this keyword Can be Passed 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 an example in next slide. Introduction to Java Programming Language Notes By Adil Aslam
  166. 166. this Passed As Argument in The Constructor Call-1 class B{ Student obj; B(Student obj){ this.obj=obj; } void display(){ System.out.println("Value is: "obj.data); } } Introduction to Java Programming Language Notes By Adil Aslam This is first class
  167. 167. this Passed As Argument in The Constructor Call-2 class Student{ int data=22; Student(){ B b=new B(this); b.display(); } public static void main(String args[]){ Student a=new Student(); } } Introduction to Java Programming Language Notes By Adil Aslam This is second class
  168. 168. this Passed As Argument in The Constructor Call-2 class Student{ int data=22; Student(){ B b=new B(this); b.display(); } public static void main(String args[]){ Student a=new Student(); } } Introduction to Java Programming Language Notes By Adil Aslam Output is: Value is: 22
  169. 169. This keyword in java • Usage of this keyword • It can be used to refer current class instance variable. • this() can be used to invoke current class constructor. • It can be used to invoke current class method (implicitly) • It can be passed as an argument in the method call. • It can be passed as argument in the constructor call. • It can also be used to return the current class instance. Introduction to Java Programming Language Notes By Adil Aslam
  170. 170. This keyword in java • this keyword is used to represent the current object. As in the “this as argument in a method” example, since method1 has object of class as parameter, so when it was called inside method2, we passed this keyword as its argument in place of the object of the class. • Similarly, we can return this keyword instead of returning object of any class. • We can return the this keyword as an statement from the method. In such case, return type of the method must be the class type (non-primitive). • Syntax of this that can be Returned as a Statement Introduction to Java Programming Language Notes By Adil Aslam return_type method_name(){ return this; }
  171. 171. this Use to Return Object Of Class-1 class Rectangle{ int length, breadth; Rectangle(int l, int b){ length = l; breadth = b; } Rectangle getObj(){ return this; } } Introduction to Java Programming Language Notes By Adil Aslam
  172. 172. this Use to Return Object Of Class-1 class Rectangle{ int length, breadth; Rectangle(int l, int b){ length = l; breadth = b; } Rectangle getObj(){ return this; } } Introduction to Java Programming Language Notes By Adil Aslam Here this keyword is used to Represent object r1. Thus by Writing return this, we are Returning Object r1
  173. 173. this Use to Return Object Of Class-1 class Test{ public static void main (String[] args){ Rectangle r1 = new Rectangle(15,20); Rectangle r2; r2 = r1.getObj(); System.out.println("length: " + r1.length + "breadth: " + r1.breadth); System.out.println("length: " + r2.length + "breadth: " + r2.breadth); } } Introduction to Java Programming Language Notes By Adil Aslam Output is: length: 15 breadth: 20 length: 15 breadth: 20
  174. 174. Explanation of Previous Program • In Previous program example we returned this in getObj() method. • Now, since object r1 called the 'getObj' method and this keyword represents the current object, here this keyword is used to represent object r1. • Thus by writing return this, we are returning object r1 and by writing r2 = r1.getObj(), we are assigning object r1 to object r2. Thus the length and breadth of r2 also becomes 15 and 20 respectively. Introduction to Java Programming Language Notes By Adil Aslam
  175. 175. Proving this keyword class Test{ void m(){ //prints reference ID System.out.println(this); } public static void main(String args[]){ Test obj=new Test(); //prints the reference ID System.out.println(obj); obj.m(); } } Introduction to Java Programming Language Notes By Adil Aslam
  176. 176. Proving this keyword class Test{ void m(){ //prints reference ID System.out.println(this); } public static void main(String args[]){ Test obj=new Test(); //prints the reference ID System.out.println(obj); obj.m(); } } Introduction to Java Programming Language Notes By Adil Aslam Output is: test.Test@15db9742 test.Test@15db9742 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.
  177. 177. Interview Questions on This Keyword • What is this keyword ? • this is reference variable that refers to the current object. • Why use this keyword ? • this keyword can be used to refer current class instance variable and this keyword can also be used to return the current class instance. • What are the uses of this keyword in constructor ? • this can be passed as argument in the constructor call. Introduction to Java Programming Language Notes By Adil Aslam
  178. 178. Interview Questions on This Keyword • Can we call methods using this keyword ? • Yes we can use this keyword to call current class non static methods. • Uses of this keyword with constructor ? • Used to invoke current class constructor. • What is the difference between this. (this dot) and this() (this off). ? • this. can be used to differentiate variable of class and formal parameters of method or constructor. this() can be used to call one constructor within the another constructor without creation of objects multiple time for the same class. Introduction to Java Programming Language Notes By Adil Aslam
  179. 179. static keyword in java Introduction to Java Programming Language Notes By Adil Aslam
  180. 180. Static keyword in java • The static keyword is used in java mainly for memory management. It is used with variables, methods, blocks and nested class. It is a keyword that are used for share the same variable or method of a given class. This is used for a constant variable or a method that is the same for every instance of a class. The main method of a class is generally labeled static. • No object needs to be created to use static variable or call static methods, just put the class name before the static variable or method to use them. Static method can not call non-static method. • In java Language Static Keyword can be used for Following • Variable (also Known as Class Variable) • method (also Known as Class Method) • Block • Nested Class Introduction to Java Programming Language Notes By Adil Aslam
  181. 181. Static keyword in java • 1) Java Static Variable • If we declare any variable as static, it is known static variable. • The static variable can be used to refer the common property of all objects (that is not unique for each object). For Example company name of employees, college name of students etc. Name of the college is common for all students. • The static variable allocate memory only once in class area at the time of class loading. • Advantage of Static Variable • It makes your program memory efficient (i.e. it saves memory). Introduction to Java Programming Language Notes By Adil Aslam
  182. 182. Static keyword in java • 1) Java Static Variable • When and Why we Use Static Variable • Suppose we want to store record of all employee of any company, in this case employee id is unique for every employee but company name is common for all. When we create a static variable as a company name then only once memory is allocated otherwise it allocate a memory space each time for every employee. Introduction to Java Programming Language Notes By Adil Aslam
  183. 183. Static keyword in java • Understanding Problem Without Static Variable • Suppose there are 500 students in my college, now all instance data members will get memory each time when object is created. All student have its unique roll-no and name so instance data member is good. Here, college refers to the common property of all objects. If we make it static, this field will get memory only once. Introduction to Java Programming Language Notes By Adil Aslam class Student{ int roll-no; String name; String university="SAC"; }
  184. 184. Static keyword in java • Understanding Problem Without Static Variable • Suppose there are 500 students in my college, now all instance data members will get memory each time when object is created. All student have its unique roll-no and name so instance data member is good. Here, college refers to the common property of all objects. If we make it static, this field will get memory only once. Introduction to Java Programming Language Notes By Adil Aslam class Student{ int roll-no; String name; String university="SAC"; } Note: Java Static Property is Shared to all Objects.
  185. 185. Static keyword in java • Applicable to • The Static keyword can be Applied to • Method • Variable • Class Nested Within Another Class • Initialization Block • Not Applicable to • The Static keyword can not be Applied to • Class (Not Nested) • Constructor • Interfaces • Method Local Inner Class(Difference then Nested Class) • Inner Class Methods • Instance Variables • Local Variables etc. Introduction to Java Programming Language Notes By Adil Aslam
  186. 186. Static keyword in java • Static Keyword Rules • Variable or Methods marked static belong to the Class rather then to any particular Instance. • Static Method or Variable can be used without creating or referencing any instance of the Class. • If there are instances, a static variable of a Class will be shared by all instances of that class, This will result in only one copy. • A static Method can’t access a non static variable nor can directly invoke non static Method (It can invoke or access Method or variable via instances). Introduction to Java Programming Language Notes By Adil Aslam
  187. 187. Static keyword in java • Static Variables Rules • Static variables are also known as Class Variables. • Such variables get default values based on the data type. • Data stored in static variables is common for all the objects( or instances ) of that Class. • Memory allocation for such variables only happens once when the class is loaded in the memory. • These variables can be accessed in any other class using class name. Introduction to Java Programming Language Notes By Adil Aslam
  188. 188. Static keyword in java • Syntax for Declare Static Variable: • Example Introduction to Java Programming Language Notes By Adil Aslam public static variableName; public static double PI=3.1415
  189. 189. Example of Static Variable-1 class Student{ int roll-no; String name; static String college =“SBC"; Student(int r, String n){ roll-no = r; name = n; } void display (){ System.out.println(roll-no+" "+name+" "+college); } Introduction to Java Programming Language Notes By Adil Aslam
  190. 190. Example of Static Variable-1 class Student{ int roll-no; String name; static String college =“SBC"; Student(int r, String n){ roll-no = r; name = n; } void display (){ System.out.println(roll-no+" "+name+" "+college); } Introduction to Java Programming Language Notes By Adil Aslam This College Variable is Commonly sharable by both S1 and S2 Objects.
  191. 191. Example of Static Variable-1 public static void main(String args[]){ Student s1 = new Student(11,"Adil"); Student s2 = new Student(22,"Hina"); s1.display(); s2.display(); } } Introduction to Java Programming Language Notes By Adil Aslam Output is: 11 Adil SBC 22 Hina SBC
  192. 192. Static Variable Introduction to Java Programming Language Notes By Adil Aslam S2 S1 Id=22; name=Hina; Id=11; name=Adil; College=SBC Java Stack Class Area
  193. 193. Program of Counter Without Static Variable class Counter{ //will get memory when instance is created int count=0; Counter(){ count++; System.out.println(count); } public static void main(String args[]){ Counter c1=new Counter(); Counter c2=new Counter(); Counter c3=new Counter(); } } Introduction to Java Programming Language Notes By Adil Aslam
  194. 194. Program of Counter Without Static Variable class Counter{ //will get memory when instance is created int count=0; Counter(){ count++; System.out.println(count); } public static void main(String args[]){ Counter c1=new Counter(); Counter c2=new Counter(); Counter c3=new Counter(); } } Introduction to Java Programming Language Notes By Adil Aslam 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 to other objects. So each objects will have the value 1 in the count variable.
  195. 195. Program of Counter Without Static Variable class Counter{ //will get memory when instance is created int count=0; Counter(){ count++; System.out.println(count); } public static void main(String args[]){ Counter c1=new Counter(); Counter c2=new Counter(); Counter c3=new Counter(); } } Introduction to Java Programming Language Notes By Adil Aslam Output is: 1 1 1
  196. 196. Program of Counter By Static Variable class Counter{ //will get memory when instance is created static int count=0; Counter(){ count++; System.out.println(count); } public static void main(String args[]){ Counter c1=new Counter(); Counter c2=new Counter(); Counter c3=new Counter(); } } Introduction to Java Programming Language Notes By Adil Aslam
  197. 197. Program of Counter By Static Variable class Counter{ //will get memory when instance is created static int count=0; Counter(){ count++; System.out.println(count); } public static void main(String args[]){ Counter c1=new Counter(); Counter c2=new Counter(); Counter c3=new Counter(); } } Introduction to Java Programming Language Notes By Adil Aslam Static Variable will get the Memory only Once, if any Object Changes the value of the Static Variable, it will retain its value. Output is: 1 2 3
  198. 198. Difference Between Static and Non-Static Variable in Java • These variables should not be proceeded by any static keyword • Memory is allocated for these variables whenever an object is created. • Memory is allocated is multiple times whenever a new object is created. Introduction to Java Programming Language Notes By Adil Aslam • These variables are proceeded by any static keyword • Memory is allocated for these variables at the time of loading of the class. • Memory is allocated for these variables only once in the program. class A { int a; } class A { static int a; } Non-Static Variable Static Variable
  199. 199. Difference Between Static and Non-Static Variable in Java • Non-static variable also known as instance variable while because memory is allocated whenever is created. • Non-static variable are specific to an object. • Non-static variable can access with object reference. • Syntax Introduction to Java Programming Language Notes By Adil Aslam • Memory is allocated at the time of loading of class so that these are also known as class variables. • Static variable are common for every object that mean these memory location can be shareable by every object reference or same class. • static variable can access with class reference. • Syntax Non-Static Variable Static Variable Obj_ref.variable_name class_name.variable_name
  200. 200. Static keyword in java • 2) Java Static Method • If you apply static keyword with any method, it is known as static method. • A static method belongs to the class rather than object of a class. • A static method can be invoked without the need for creating an instance of a class. • static method can access static data member and can change the value of it. Introduction to Java Programming Language Notes By Adil Aslam
  201. 201. Static keyword in java • 2) Java Static Method (Important Points) • Static methods neither use instance variable within it nor non-static method call inside it. • Static methods can not use instance variable directly, it can use instance variables by creating the object of that class. • We can not override the static method in java. Just method hiding is there in case of static method. • We can overload the static method in java. • We have best example, public static void main(String []args) method is also declared as static because it is called from outside of the class without creating the object. Introduction to Java Programming Language Notes By Adil Aslam
  202. 202. Static keyword in java • 2) Java Static Method (Important Points) • A static method can access static variables directly and it cannot access non-static variables. • A static method can only call a static method directly and it cannot call a non-static method from it. • super and this keyword cannot be used in a static method. • A static method can be directly called by using the class name <<ClassName>>.<<MethodName>> rather than object. This is the main reason we have declared our main() method as static. If not the JVM has to create object first and call the main() method which causes the problem of having extra memory allocation. Introduction to Java Programming Language Notes By Adil Aslam
  203. 203. Static keyword in java • Methods Declared as Static have Several Restrictions: • They can only call other static methods • They must only access static data. • They cannot use this or super in anyway (Super is a keyword used in Inheritance ). • Syntax for Declare Static Method: Introduction to Java Programming Language Notes By Adil Aslam public static void methodName() { ....... ....... }
  204. 204. Static Method Example class Cube{ static void cube(){ int x=5*5*5; System.out.println("Cube is: "+x); } public static void main(String args[]){ cube(); } } Introduction to Java Programming Language Notes By Adil Aslam
  205. 205. Static Method Example class Cube{ static void cube(){ int x=5*5*5; System.out.println("Cube is: "+x); } public static void main(String args[]){ cube(); } } Introduction to Java Programming Language Notes By Adil Aslam Static Method
  206. 206. Static Method Example class Cube{ static void cube(){ int x=5*5*5; System.out.println("Cube is: "+x); } public static void main(String args[]){ cube(); } } Introduction to Java Programming Language Notes By Adil Aslam Calling Static Method Without Using the Object of the Cube Class Output is: Cube is: 125
  207. 207. Another Static Method Example class Cube{ static int cube(int x){ return x*x*x; } public static void main(String args[]){ int result=Cube.cube(5); System.out.println("Cube is: "+ result); } } Introduction to Java Programming Language Notes By Adil Aslam int result=cube(5); Both Valid For Static Method
  208. 208. Another Static Method Example class Cube{ static int cube(int x){ return x*x*x; } public static void main(String args[]){ int result=Cube.cube(5); System.out.println("Cube is: "+ result); } } Introduction to Java Programming Language Notes By Adil Aslam int result=cube(5); Both Valid For Static Method Output is: Cube is: 125
  209. 209. Another Static Method Example-1 //Program of changing the common property of all objects (static field). class Student{ int rollno; String name; static String college = "SBC"; static void change(){ college = "AAA"; } Student(int r, String n){ rollno = r; name = n; } Introduction to Java Programming Language Notes By Adil Aslam
  210. 210. Another static Method Example-1 //Program of changing the common property of all objects (static field). class Student{ int rollno; String name; static String college = "SBC"; static void change(){ college = "AAA"; } Student(int r, String n){ rollno = r; name = n; } Introduction to Java Programming Language Notes By Adil Aslam Static Variable Static Method
  211. 211. Another Static Method Example-2 void display (){ System.out.println(rollno+" "+name+" "+college); } public static void main(String args[]){ Student.change(); Student s1 = new Student (11,"Adil"); Student s2 = new Student (22,"Hina"); s1.display(); s2.display(); } } Introduction to Java Programming Language Notes By Adil Aslam Here Calling Static Method Without using Object Reference Output is: 11 Adil AAA 22 Hina AAA
  212. 212. Properties of static Methods • Multiple Arguments. Like a normal function, a Java static method can take on more than one argument, and therefore can have more than one parameter variable. • Multiple Methods. We can define as many static methods as you want in a .java file. These methods are independent and can appear in any order in the file. A static method can call any other static method in the same file or any static method in a Java library such as Math. • Overloading. Static methods with different signatures are different methods. whose signatures differ are different static methods. Using the same name for two static methods whose signatures differ is known as overloading. • Multiple Return Statements. We can put return statements in a method wherever you need them: control goes back to the calling program as soon as the first return statement is reached. Introduction to Java Programming Language Notes By Adil Aslam

×