Constructors


  • Constructors are the functinalities which are going to be executed  automatically when the object is created.
  •  Can be executed only once with respect to object
  • Can't have any return type not even void.
  • Name of the constructor should and must be always name of the class.
  • Two types: default constructor and parametrized constructor

Default Constructor:

  • A Constructor that have no parameters is known as Default Constructor.

 Example program for default constructor :

  1. package com.instanceofjava;
  2.  
  3. public class MyDefaultConstructor{
  4.  
  5. public MyDefaultConstructor(){
  6.  
  7. System.out.println("I am inside default constructor");
  8.  
  9.  }
  10.  
  11. public static void main(String args[]){
  12.  
  13. MyDefaultConstructor mdc=new MyDefaultConstructor(); 
  14.  
  15. }
  16. }


Output:
  1. I am inside default constructor


Parameterized Constructor:
  • A Constructor that have parameters is known as Parameterized Constructor.
Program for Parameterized Constructor:


  1. package com.instanceofjava;
  2.  
  3. public class Employee{
  4.  
  5. private int id;
  6. private String name;
  7.  
  8. Employee(int id,String name){
  9.  this.id=id;
  10. this.name=name;
  11. }
  12.  
  13. public void display(){ 
  14.  
  15. System.out.println(id+" "+name); 
  16.  
  17. }
  18.  
  19. public static void  main (String args[]){
  20.  
  21. Emploee e=new Employee(1,"Indhu"); Employee e1=new Employee(2,"Sindhu"); e.display();
  22. e1.display();
  23.  
  24. }
  25. }


Output:
  1. 1 Indhu 
  2. 2 Sindhu


Inheritance

Inheritance:

  • The concept of getting properties of one class object to another class object.
  • Inheritance represents the IS-A relationship,also known as parent-child relationship.

Types of Inheritance:

  1. Multiple inheritance
  2. Multilevel inheritance.

How Inheritance can be implemented in java:

  • Inheritance can be implemented in JAVA using below two keywords:
  1. extends
  2. implements
  • extends is used for developing inheritance between two classes and two interfaces.
  • implements keyword is used to developed inheritance between interface and class.

Why Inheritance:

  • For Code Reusability.
  • For Method Overiding.

Syntax:

public class subclass extends superclass{

//all methods and varaibles declare here
}

Multilevel Inheritance:

Getting the properties from one class object to another class object level wise with different priorities.

Program:

public class A{

public void show(){
System.out.println("This is Super calss method");
}
}
public class B extends A{
public void display(){
System.out.println("This is sub class method");
}
}
public class C extends B{
public void add(){
System.out.println("This is another sub class method");
}
public static void main(String args[]){
C  c=new C();
c.show(); //super class method
c.display(); //sub class method
c.add(); //c Subclass method
}

}

Output:
This is Super calss method
This is sub class method
This is another sub class method

Diagram for multilevel inheritance:



Multilevel Inheritance



Multiple inheritance:

  • The concept of Getting the properties from multiple class objects to sub class object with same priorities is known as multiple inheritance.
  • Java Doesn't Support multiple Inheritance.
  •  In multiple inheritance there is every chance of multiple properties of multiple objects with  the same name available to the sub class object with same priorities leads for the ambiguity.
    also known as diamond problem. one class extending two super classes.
  • Because of multiple inheritance there is chance of the root object getting created more than once.
  • Always the root object i.e object of object class hast to be created only once.
  • Because of above mentioned reasons multiple inheritance would not be supported by java.
  • Thus in java a class can not extend more than one class simultaneously. At most a class can extend only one class.

Program :

public class A{
public void show(){
System.out.println("This is super class method");
}
}
public class B {
public void show(){
System.out.println("This is sub class method");
}
}
public class C extends A,B{
public static void main(String args[]){
C c=new C();
c.show(); //which method need to invoke.
}
}

Output:
Compile time Error.

Java doesn't support multiple inheritance why because java compiler don't know which method has to invoke.Class C is derived from A and B. If A and B classes have same method and you call it from child class object ,there will be ambiguity to call method of A or B classes.that's the reason only java doesn't support multiple Inheritance.
Since compile time errors are better than run time errors, java gives compile time error if you extend 2 classes. So whether you have same method or different, there will be compile time error now.
Multiple Inheritance

Polymorphism

  • Defining the multiple methods with same name associated with the same object is known as polymorphism.
  • There are two types of polymorphism
  1. Static polymorphism (Compile time polymorphism ).
  2. Dynamic polymorphism (Run time polymorphism ).

Static polymorphism:

  • The concept of defining multiple methods with same name and with different parameters within the same class is known as static polymorphism.
  • we can achieve method overloading by using this static polymorphism.
  •  When Java encounters a call to an overloaded method, it simply executes the method whose parameters match the arguments used in the call.
  • Overloaded methods may have different return types.
  • No two functions/methods could be defined with the same name and with the same parameters of same data types , even by changing the return data type of the methods
  • In java return data types are not considered with respect to static polymorphism.

 Example program:
 
public class Sample{
public void methodName(){
  System.out.println("no argument method");
    } 
public void methodName(int a, int b){
  System.out.println("two argument method");
    } 
public static void main(String args[]){
Sample s= new Sample();
s.methodNmae();
s.methodNmae(2,4);
}
}

Output:
no argument method
two argument method

Why static polymorphism is known as compile time polymorphism?

  • Out of multiple methods with same name which method is to get executed will be decided at the time of compilation itself.

Disadvantage of static polymorphism:  

  • There is every chance for polymorphism failing or breaking.
  • As long as there is a method defined to accept the same data type value there is no problem
  • If there are multiple alternative methods for whose parameters the value what we are passing as an argument matches with the same priority then JVM would not understand that it has to execute which method.
  • lets see example programs for above mentioned problem.
*  if  there are multiple methods able to accept same value:
package com.instanceofjavaforus;

public class poly {

    void method(A a){
       
        System.out.println("Method accepting object of class A a as an argument");
    }
   
  void method(B  a){
       
        System.out.println("Method accepting object of class B b as an argument");
    }
   
    public static void main(String args[]){
       
        poly obj= new poly();
        obj.method(null); // here compilation error will come
       
    }
    }
Output:
Gives a compilation error : "The method method(A a) is ambiguous for the type poly"

when we are passing a value which will be acceptable to all methods then jvm enters into tha state of ambiguity .
Same problem will occur when we are passing null value to println() method

Click here for explanation on System.out.println(null)

Dynamic polymorphism:

  • The concept of defining multiple methods with same name and with same signature in super class and sub class known as Dynamic polymorphism.
  • we can achieve method overriding by using this Dynamic polymorphism.
  • Dynamic (run time) polymorphism is the polymorphism existed at run-time.
  • Here, Java compiler does not understand which method is called at compilation time. 
  • Only JVM decides which method is called at run-time.

Program:

public class A{
public void methodA(){
System.out.println("Hello India"); //Base class
}
}
Public class B extends A{
public void methodA(){
System.out.println("Hello Indira"); //Derived Class
}
}
public class C{
public static void main(String args[]){
A a=new A();
A a1=new B(();
a.methodA();
a1.methodA();
}
}

Output:
Hello India
Hello Indira.


Why dynamic polymorphism is known as run time polymorphism?
Out of multiple methods with same name which method is to get executed will be decided at the time of runtime itself.




Class and object

Class

  • Class is a structure.
  • Binding the data with its related and corresponding functions.
  • Class is the base for encapsulation.
  • Class is a user defined data type in java.
  • Class will act as the base for encapsulation and implement the concept of encapsulation through objects.
  • Any java applications looks like collection of classes but where as c- application looks like collection of functions.
public class Example{

         //variable declaration
          int id;

      // methods
        public int getId() {
          return id;
         }

    public void setId(int id) {
        this.id = id;
    }

}

Object

  • Object is nothing but instance (dynamic memory allocation) of a class.
  • The dynamic memory allocated at run time for the members [non-static variables] of the class is known as object.

What is a Reference variable?

  • Reference variable is a variable which would be representing the address of the object.
  • Reference will act as a pointer and handler to the object.
  • Since reference variable always points an object.
  • In practice we call the reference variable also as an object.
  • We can create an object by using new operator.
  • If we want to call any method inside the class we need object
               Syntax: A obj= new A();

Example program:

      public class A {
         int a;
     public  void Print(){
        System.out.println("value of a="+a);
    }
    public static void main(String[] args) {
   A obj=new A();
  obj.print();
    }
}

Output: value of a=0
What Object Contains?
  • Object of any class contains only data.
  • Apart from the data object of a class would not contains anything else.
  • Object of a class would not contain any functionalities or logic.
  • Thus object of a class would be representing only data and not represent logic.

What is state of the Object?

  • The data present inside object of a class at that point of time is known as state of the object

What is behavior of the object? 

  • The functionalities associated with the object => Behavior of the object.
     The state of the object changes from time-to-time depending up on the functionaities that are executed on that object but whereas behavior of the object would not change.

Naming conventions for declaring a class:

  • Class name should be relevant.
  • Use UpperCamelCase for class names. //StudentDemoClass
  • For Methods names follow camelCase(); //getName();
  • Declare variables lowercase first letter. // int rollNumber
  • To declare final static variables means which will acts like constants
    MIN_WIDTH=10;
    MAX_AGE=18;

Reason for Data Insecurity

Reason for Data Insecurity

  • It is the  GLOBAL VARIABLES which leads to the data insecurity in c- programs 
  • GLOBAL VARIABLES would be available for both related and unrelated functions also.
  • Whenever an unrelated function accesses the data in a wrong way data corruption arises
Sample c -program  

#include <stdio.h>
 
/* global variable declaration */
int a = 20;
 
int main ()
{
  /* local variable declaration in main function */
  int a = 10;
  int b = 20;
  int c = 0; 
int mul=0;

  c = sum( a, b);
  printf ("a+b = %d\n",  c); 
 mul= sum( a, b);
  printf ("a*b= %d\n",  mul);  
 return 0;
}

/* function to add two integers */
int sum(int a, int b)
{
    

    return a + b;
}
/* function to multiply two integers */
int mul(int a, int b)
{


    return a * b;
} 

Java program:

 package com.instanceofjavaforus;

public class Student {
  
// variables
    int rno;
    String name;
    String clas;
  
//setter and getter methods of variables  
    public int getRno() {
        return rno;
    }

    public void setRno(int rno) {
        this.rno = rno;
    }
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getClas() {
        return clas;
    }

    public void setClas(String clas) {
        this.clas = clas;
    }

  
    //constructor
    Student(int rno,String name,String clas){
        this.rno=rno;
        this.name=name;
        this.clas=clas;
          }
  
    public static void main(String args[]){
      
        Student student= new Student(1, "sai", "class IV", "hyderabad", 1);
      
        System.out.println("Name: "+student.getName());
        System.out.println("Class: "+student.getClas());
        System.out.println("Rno: "+student.getRno());
       }
}

Encapsulation

Need for Encapsulation

Encapsulation in java

 

  • Any program of  any programming language contains only two parts.
    i.Data
    ii.Logic
  • Out of these two highest priority would be always given to data part.
  • Functions /logics would e giving output based on the data.
  • There is no proper security for the data part in the structured programming language programs like c - program.
  • There was no proper separation between the data and functions of different domains because of which complexity of the programming increases and data insecurity arises
  • The concept of proper binding is missing in structured programming languages  

Reason for Data Insecurity in C-Programing language:

  • It is the  GLOBAL VARIABLES which leads to the data insecurity in c- programs 
  • GLOBAL VARIABLES would be available for both related and unrelated functions also.
  • Whenever an unrelated function accesses the data in a wrong way data corruption arises

Sample c -program:

  1. #include <stdio.h>
  2.  
  3. /* global variable declaration */
  4. int a = 20;
  5.  
  6. int main ()
  7. {
  8.  
  9. /* local variable declaration in main function */
  10.   int a = 10;
  11.   int b = 20;
  12.   int c = 0;
  13. int mul=0;
  14.  
  15.  c = sum( a, b);
  16.  
  17.  printf ("a+b = %d\n",  c);
  18.  
  19. mul= sum( a, b);
  20.  
  21. printf ("a*b= %d\n",  mul); 
  22. return 0;
  23.  
  24. /* function to add two integers */
  25. int sum(int a, int b)
  26. {   
  27.     return a + b;
  28. }
  29.  
  30. /* function to multiply two integers */
  31. int mul(int a, int b)
  32. {
  33.     return a * b;
  34. }

What is Encapsulation?

  • The concept of binding the data along with its related and corresponding functions is known as Encapsulation.

 

 

Binding:

  • The concept of restricting the availability of the data only to its related areas and related functions it is known as binding.
  • Because of binding we can restrict the availability of dta to the unrelated functions
  • So that unrelated functions cannot access the data 
  • Class is the base for encapsulation


Example program:

  1. package com.instanceofjava;
  2.  
  3. public class Student {
  4.  
  5. // variables
  6.    int rno;
  7.     String name;
  8.     String clas;
  9.     String Address;
  10.     int rank;
  11.  
  12. //setter and getter methods of variables 
  13.  
  14.  public int getRno() {
  15.        return rno;
  16.     }
  17.  
  18. public void setRno(int rno) {
  19.        this.rno = rno;
  20. }
  21.  
  22. public String getName() {
  23.         return name;
  24. }
  25.  
  26.  public void setName(String name) {
  27.         this.name = name;
  28. }
  29.  
  30. public String getClas() {
  31.        return clas;
  32. }
  33.  
  34. public void setClas(String clas) {
  35.         this.clas = clas;
  36. }
  37.  
  38. public String getAddress() {
  39.        return Address;
  40. }
  41.  
  42. public void setAddress(String address) {
  43.       Address = address;
  44. }
  45.  
  46. public int getRank() {
  47.     return rank;
  48.  }
  49.  
  50. public void setRank(int rank) {
  51.         this.rank = rank;
  52.  }
  53.  
  54.     //constructor
  55.    Student(int rno,String name,String clas,String Address,int rank){
  56.  
  57.         this.rno=rno;
  58.         this.name=name;
  59.         this.clas=clas;
  60.  
  61.         this.Address=Address;
  62.         this.rank=rank;
  63.  
  64.     }
  65.  
  66.  public static void main(String args[]){
  67.  
  68.     Student student= new Student(1, "sai", "class IV", "hyderabad", 1); 
  69.  
  70.     System.out.println("Name: "+student.getName());
  71.     System.out.println("Class: "+student.getClas());
  72.     System.out.println("Rno: "+student.getRno());
  73.  
  74.     System.out.println("Rank: "+student.getRank());
  75.     System.out.println("Address: "+student.getAddress());
  76.  
  77.   }
  78. }

 

Output:

  1. Name: sai 
  2. Class: class IV 
  3. Rno: 1 
  4. Rank: 1 
  5. Address: hyderabad
Select Menu