Constructors in java





  • Constructors will be executed when the object is created.
  • Constructors should have same name of class name.
  • Executed once per object.
  • Basically used to assign instance variables
  • We can overload constructors.
  • We can call super class constructor form sub class constructor.






  1. package instanceofjava;
  2. class A{
  3. A(){
  4. }
  5. }
  6. }

  • while creating object constructor will be executed so we can assign instance variables to some default values.

  1. package instanceofjava;
  2. class A{
  3. int a,b
  4. A(int x, int y){
  5. a=x;
  6. b=y;
  7. }
  8.  
  9. public static void main(String[] args){
  10.  A a=new A(10,20);

  11. }
  12. }

Types of constructors:

  • There are two types of constructors 
  • Default constructors
  • Parameterized constructor.

Default constructor:

  •  Default constructor will not have any arguments.
  • If we not defined any constructor in our class. JVM automatically defines a default constructor to our class.
  1. package instanceofjava;
  2. class Sample{
  3. int a,b
  4. Sample(){
  5. a=37;
  6. b=46;
  7. }
  8.  
  9. public static void main(String[] args){
  10.  
  11.  Sample obj=new Sample();
  12.   System.out.println(obj.a);
  13.   System.out.println(obj.b);
  14.  
  15. }
  16. }

Output:

  1. 37
  2. 46

Parameterized constructor


  1. package instanceofjava;
  2. class Sample{
  3. int a,b
  4. Sample(int x, int y){
  5. a=x;
  6. b=y;
  7. }
  8.  
  9. public static void main(String[] args){
  10.  
  11.  Sample obj=new Sample(37,46);
  12.   System.out.println(obj.a);
  13.   System.out.println(obj.b);
  14.  
  15. }
  16. }

Output:

  1. 37
  2. 46

Constructor overloading:

  1. package instanceofjava;
  2. class Sample{
  3. int a,b 
  4. Sample(){
  5. this(1,2);
  6.  System.out.println("Default constructor");
  7.  
  8. }
  9. Sample(int x , int y){
  10.  
  11. this(1,2,3); 
  12. a=x;
  13. b=y;
  14.  System.out.println("Two argument constructor");
  15.  
  16. }
  17.  
  18. Sample(int a , int b,int c){
  19.  System.out.println("Three argument constructor")
  20. }
  21. public static void main(String[] args){
  22.  
  23.  Sample obj=new Sample();
  24.   System.out.println(obj.a);
  25.   System.out.println(obj.b);
  26.  
  27. }
  28. }


Output:

  1. Three argument constructor
  2. Two argument constructor
  3. Default argument constructor
  4. 1
  5. 2





This and Super Keywords


  • this keyword used to store current object reference.
  • super keyword used to store super class reference in subclass object.

this keyword:

  • Predefined instance variable to hold current object reference.

It must used explicitly if non-static variable and local variable name is same.

 

 





  1. package com.instanceofjava;
  2.  
  3. public class ThisDemo {
  4.     int a, b;
  5.  
  6.  ThisDemo(int a, int b){
  7.  
  8.         a=a;
  9.         b=b;
  10.  }
  11.  
  12.     public static void main(String[] args){
  13.  
  14.         ThisDemo obj= new ThisDemo(1,2);
  15.         
  16.         System.out.println(obj.a);
  17.         System.out.println(obj.b);
  18. }
  19. }

Output:

  1. 0
  2. 0
  • Without this keyword if variable names are same we can not assign instance variables so this problem will solve by using this keyword

  1. package com.instanceofjava;
  2.  
  3. public class ThisDemo {
  4.     int a, b;
  5.  
  6.  ThisDemo(int a, int b){
  7.  
  8.         this.a=a;
  9.        this.b=b;
  10.  }
  11.  
  12.     public static void main(String[] args){
  13.  
  14.         ThisDemo obj= new ThisDemo(1,2);
  15.         
  16.         System.out.println(obj.a);
  17.         System.out.println(obj.b);
  18. }
  19. }

Output:

  1. 1
  2. 2

Used to invoke current class constructor:

  1. package com.instanceofjava;
  2.  
  3. public class ThisDemo {
  4.     int a, b;
  5.  
  6. ThisDemo(){
  7. System.out.println("Default constructor called");
  8. }

  9.  ThisDemo(int a, int b){
  10.        this();
  11.         this.a=a;
  12.        this.b=b;
  13.  }
  14.  
  15.     public static void main(String[] args){
  16.  
  17.         ThisDemo obj= new ThisDemo(1,2);
  18.         
  19.         System.out.println(obj.a);
  20.         System.out.println(obj.b);
  21. }
  22. }

Output:

  1. Default constructor called
  2. 1
  3. 2

Used to call current class method:

 

  1. package com.instanceofjava;
  2.  
  3. public class Sample{
  4.     int a, b;
  5.  

  6.  Sample(int a, int b){
  7.       
  8.        this.a=a;
  9.        this.b=b;
  10.  }
  11.  
  12. void show(){
  13.  
  14. System.out.println("Show() method called");
  15.    
  16. }
  17.  
  18. void print(){
  19.  
  20.     this.show();
  21.     System.out.println(obj.a);
  22.     System.out.println(obj.b);
  23.  
  24.  }
  25.     public static void main(String[] args){
  26.  
  27.         Sample obj= new Sample(1,2);
  28.         
  29.       
  30.         obj.print()
  31. }
  32. }



Output:

  1. Show() method called
  2. 1
  3. 2

super keyword:

  • Predefined instance variable used to hold super class object reference through sub class object.

 

Used to call super class constructor:



  1. package com.instanceofjava;
  2.  
  3. public class A{
  4.     int a, b;
  5.  
  6.  A(int a, int b){
  7.  
  8.         a=a;
  9.         b=b;
  10. System.out.println("super class constructor called");
  11.  
  12.  }
  13.  
  14. }


  1. package com.instanceofjava;
  2.  
  3. public class B extends A{
  4.     int a, b;
  5.  
  6.  A(int a, int b){
  7.     super(a,b);
  8.         a=a;
  9.         b=b;
  10. }
  11. public static void main(String[] args){
  12.  
  13.         B obj= new B(1,2);
  14.         
  15.     
  16. }
  17.  
  18.  }
  19.  
  20. }

Output:

  1. super class constructor called
  2. 1
  3. 2

Used to call super class methods from subclass:


  1. package com.instanceofjava;
  2.  
  3. public class A{
  4.     int a, b;
  5.  
  6.  A(int a, int b){
  7.  
  8.         a=a;
  9.         b=b;
  10. System.out.println("super class constructor called");
  11.  
  12.  }
  13.  
  14. void add(){
  15. System.out.println("super class method called");
  16. }
  17.  
  18. }


  1. package com.instanceofjava;
  2.  
  3. public class B extends A{
  4.     int a, b;
  5.  
  6.  A(int a, int b){
  7.     super(a,b);
  8.         a=a;
  9.         b=b;
  10. }
  11. void print(){ 
  12. super.add();
  13. System.out.println(this.a);
  14. System.out.println(this.b);
  15.  


  16. }
  17. public static void main(String[] args){
  18.  
  19.         B obj= new B(1,2);
  20.         
  21.        obj.print();
  22. }
  23.  
  24.  }
  25.  
  26. }

Output:

  1. super class method called
  2. 1
  3. 2

Abstraction

  • Abstraction is fundamental principle of modeling. A system model is created at different levels, starting at the higher levels and adding more levels with more details as more is understood about the system. When complete, the model can be viewed at several levels.
  • So abstraction is about,
  • Looking only at the information that is relevant at that time
  • Hiding details so as not to confuse the bigger picture


  • Abstraction is a process of developing a class by hiding or removing non essential details relevant to user. here non essential details means method body and logic 
  • Basically Abstraction provides a contract between a service provider and clients.
  • we can achieve this by using abstract class

  1. package Abstraction;
  2. public abstract class AbstractDemo {
  3.  
  4.     abstract void add(); // abstract method
  5.  
  6.  void show(){ // normal method
  7.         System.out.println("this is concrete method present in abstract class");
  8.  }
  9. }
  • Abstract class can not be instantiated directly.
  • Means we can not create object for abstract class directly

  1. package Abstraction;
  2. public abstract class AbstractDemo {
  3.  
  4.     abstract void add(); // abstract method
  5.  
  6.  void show(){ // normal method
  7.         System.out.println("this is concrete method present in abstract class");
  8.  }
  9.  
  10. public static void main(String[] args){
  11.  
  12. AbstractDemo   obj= new AbstractDemo(); 
  13. // ERROR: Cannot instantiate the type AbstractDemo
  14.  
  15. }
  16. }

Can we declare abstract methods as static?

  1. package Abstraction;
  2. public abstract class AbstractDemo {
  3.  
  4.     static abstract void add(); // ERROR: illegal combination of modifiers
  5.  
  6.  void show(){ // normal method
  7.         System.out.println("this is concrete method present in abstract class");
  8.  }
  9. }
  • No, we are not allowed to declare method as static . It leads to compile time error.

Can we declare abstract methods as final?


  1. package Abstraction;
  2. public abstract class AbstractDemo {
  3.  
  4.     final abstract void add(); // ERROR: illegal combination of modifiers
  5.  
  6.  void show(){ // normal method
  7.         System.out.println("this is concrete method present in abstract class");
  8.  }
  9. }
  • No, we are not allowed to declare method as static . It leads to compile time error.
  • Because it should be inherited to sub class.


Can we declare abstract methods as private?

  1. package Abstraction;
  2. public abstract class AbstractDemo {
  3.  
  4.     final abstract void add(); // ERROR: illegal combination of modifiers
  5.  
  6.  void show(){ // normal method
  7.         System.out.println("this is concrete method present in abstract class");
  8.  }
  9. }
  • No, we are not allowed to declare method as static . It leads to compile time error.
  • Because it should be inherited to sub class.

 Legal modifiers allowed in combination with abstract

 1.native

  1. package Abstraction;
  2. public abstract class AbstractDemo {
  3.  
  4.     native abstract void add(); // ERROR: illegal combination of modifiers
  5.  
  6.  void show(){ // normal method
  7.         System.out.println("this is concrete method present in abstract class");
  8.  }
  9. }

 2.protected

  1. package Abstraction;
  2. public abstract class AbstractDemo {
  3.  
  4.     protected abstract void add();
  5.  
  6.  void show(){ // normal method
  7.         System.out.println("this is concrete method present in abstract class");
  8.  }
  9. }

 3.public

  1. package Abstraction;
  2. public abstract class AbstractDemo {
  3.  
  4.    public abstract void add();
  5.  
  6.  void show(){ // normal method
  7.         System.out.println("this is concrete method present in abstract class");
  8.  }
  9. }



 4.default

  1. package Abstraction;
  2. public abstract class AbstractDemo {
  3.  
  4.   abstract void add();
  5.  
  6.  void show(){ // normal method
  7.         System.out.println("this is concrete method present in abstract class");
  8.  }
  9. }


How it works:

  1. package Abstraction;
  2. public abstract class AbstractDemo {
  3.  
  4.   abstract void add();
  5.  
  6.  void show(){ // normal method
  7.         System.out.println("this is concrete method present in abstract class");
  8.  }
  9. }


  1. package Abstraction;
  2. public abstract class Example extends AbstractDemo {
  3.  
  4.   abstract void add(){
  5.   System.out.println("this is implemented method in sub class");
  6. }
  7.  
  8.  
  9. }

Polymorphism


  • Defining multiple methods with same name
  • Static polymorphism and dynamic polymorphism

Static polymorphism:

  • Its a process of defining multiple methods with the same name and with different parameter types or list or order is called static polymorphism
  • Compile time itself we can say which method is going to get executed based on parameters types.
  • So its also called compile time polymorphism.
  • This will be achieved by method overloading.
  • Method overloading means defining multiple methods with same name and different parameters.
  • If two methods have same method name , But different parameter types those methods are considered as overloaded methods.
  • Will see example program on method overloading.

 Example program on method overloading:


  1. package instanceofjava;
  2.  
  3. public class OverloadingDemo {
  4.  
  5. void add(){
  6.     System.out.println("No-arg method");
  7. }
  8.  
  9. void add(int i){
  10.     System.out.println("int-arg method");
  11. }    
  12.  
  13. void add(String str){
  14.     System.out.println("String-arg method");
  15. }
  16.  
  17. void add(float d){
  18.     System.out.println("float-arg method");
  19. }
  20.  
  21. void add(int a, int b){
  22.     System.out.println("2 int-arg method");
  23. }
  24.  
  25. public static void main(String[] args){
  26.  
  27.     OverloadingDemo obj= new OverloadingDemo();
  28.  
  29.     obj.add();
  30.     obj.add(10);
  31.     obj.add(1.2f);
  32.     obj.add("java");
  33.     obj.add(1, 2);    
  34.  
  35. }
  36. }

Output


  1. No-arg method
  2. int-arg method
  3. float-arg method
  4. String-arg method
  5. 2 int-arg method

Method overloading with reference types:

  • We can also overload method with reference types, check below program.

  1. package instanceofjava;
  2. public class Test {
  3.  
  4. void show(){
  5.  
  6.         System.out.println("test class show() method");
  7. }
  8.  
  9. }

  1. package instanceofjava;
  2.  
  3. public class Example {
  4.  
  5. void method(String s){
  6.  
  7.        System.out.println("String-arg");
  8.  
  9. }
  10.  
  11. void method(Test obj){
  12.  
  13.     System.out.println("method(Test obj)-arg");    
  14.    obj.show();
  15.  
  16. }
  17.  
  18.  public static void main(String[] args){
  19.  
  20.     Example obj= new Example();
  21.     obj.method("polymorphism definition in oops");
  22.     obj.method(new Test());
  23.  
  24.     }
  25. }

Output:


  1. String-arg
  2. method(Test obj)-arg
  3. test class show() method

Dynamic polymorphism:

  • Redefining the super class method in sub class is called "method overriding" .
  • Method overriding is a language feature that allows a sub class to provide a specific implementation of a method that is already provided by one of its super class.
  • The implementation in the sub class overrides the implementation in the super class.
  • This is also called dynamic polymorphism / runtime polymorphism.

  1. package instanceofjava;
  2.  
  3. public class A{
  4.  
  5. void show(String s){
  6.  
  7.   System.out.println("super class method");
  8.  
  9. }
  10.  
  11. }

  1. package instanceofjava;
  2.  
  3. public class B extends A{
  4.  
  5. void show(String s){
  6.  
  7.   System.out.println("sub class method");
  8.  
  9. }
  10.  public static void main(String[] args){
  11. B obj =new B();
  12. obj.show();
  13. }
  14. }

Output:

  1. sub class method

We can not override static methods:

  • Actually static variables and static methods are class level. they are not instance level.
  • So if you try to override a static method will throw compile error
  1. package instanceofjava;
  2. public class Super {
  3.     int a,b;
  4.     static void add(){
  5.         System.out.println("super class add() method");
  6.     }
  7. }


  1. package instanceofjava;
  2. public class Sub extends Super {
  3.  
  4.  void add(){ // ERROR:This instance method cannot override the static method
  5.         System.out.println("this is sub class add() method");
  6. }
  7.  
  8.     public static void main(String [] args){

  9.         Sub obj= new Sub();
  10.  
  11.     } 
  12. }



  • Static methods are class level so we need to access by using class name.

  1. package instanceofjava;
  2. public class Sub extends Super {
  3.  
  4.  static void add(){// works fine
  5.         System.out.println("this is sub class add() method");
  6. }
  7.  
  8. public static void main(String [] args){

  9.    Super.add();
  10.    Sub.add();
  11.  
  12.  
  13.     } 
  14. }

Output:


  1. super class add() method
  2. sub class add() method

Method Overriding - Exceptions:

  •  When we overriding a method from super class to sub class. we need to follow some rules
  • Whenever sub class method throws checked exception then super class method must be declared throws with same exception or super class of that checked exception.
  1. package instanceofjava;
  2. public class Super {
  3.     int a,b;
  4.     void add(){
  5.         System.out.println("super class add() method");
  6.     }
  7. }


  1. package instanceofjava;
  2. public class Sub extends Super {
  3.  
  4.  void add() throws IOException{ // ERROR:     - Exception IOException is not compatible with
  5.                                                       //throws clause in  Super.add()
  6.         System.out.println("this is sub class add() method");
  7. }
  8.  
  9.     public static void main(String [] args){

  10.         Sub obj= new Sub();
  11.  
  12.     } 
  13. }



  1. package instanceofjava;
  2. public class Super {
  3.     int a,b;
  4.     void add()throws IOException{
  5.         System.out.println("super class add() method");
  6.     }
  7. }


  1. package instanceofjava;
  2. public class Sub extends Super {
  3.  
  4.  void add() throws IOException{// works fine
  5.         System.out.println("this is sub class add() method");
  6. }
  7.  
  8.     public static void main(String [] args){

  9.         Sub obj= new Sub();
  10.  
  11.     } 
  12. }

Inheritance Definition and Programs

  • Getting the properties from one class object to other class is known as inheritance.
  • In this inheritance will have parent class and child class so getting the properties of parent class object to child class object known as inheritance.
  • Inheritance means to take something that already made.
  • Inheritance can be implemented in java by using "extends" and "implements' keywords
  • In this we have two types.
  • Multilevel inheritance
  • Multiple inheritance

Multilevel inheritance:

  • Getting the properties from super class object to sub class object level wise with different priorities known as multiple inheritance.

Super class:

  1. package instanceofjava; 

  2. public class Super {
  3.  
  4.     int a,b;
  5.  
  6. void add(){
  7.  
  8.     System.out.println((a+b));
  9.  
  10. }
  11.  
  12. }

Sub class:

  1. package instanceofjava;
  2.  
  3. public class Sub extends Super {
  4.  
  5. void show(){
  6.  
  7.       System.out.println("this is sub class show() method");
  8.  
  9. }
  10.  
  11. public static void main(String [] args){
  12.  
  13.        Sub obj= new Sub();
  14.  
  15.         obj.a=1;
  16.         obj.b=2;
  17.  
  18.         obj.add();
  19.         obj.show();
  20.  
  21.     }
  22. }



Output:

  1. 3
  2. this is sub class show() method

Example program #2:

  1. package instanceofjava;
  2.  
  3. public class A {
  4.  
  5.     int a,b;
  6.  
  7. public void show(){
  8.  
  9.   System.out.println("A class show method");
  10.  
  11. }
  12.  
  13. }



  1. package instanceofjava;
  2.  
  3. public class B extends A{
  4.  
  5.  
  6. public void print(){
  7.  
  8.   System.out.println("B class print method");
  9.  
  10. }
  11.  
  12. }

  1. package instanceofjava;
  2.  
  3. public class C extends B{
  4.  
  5.  
  6. public void display(){
  7.  
  8.   System.out.println("C class display method");
  9.  
  10. }
  11. public static void main(String [] args){
  12.  
  13.  C obj= new C();
  14.  
  15.    obj.print();
  16.    obj.show();
  17.    obj.display();

  18. }
  19.  
  20. }

Output:

  1. B class print() method
  2. A class show method
  3. Class C display method

Multiple inheritance:

  • Multiple inheritance means getting the properties from one class object to multiple class object with different priority.
  • Multiple inheritance concept is not supported by java

  1. package instanceofjava;
  2.  
  3. public class A {

  4.  
  5. public void show(){
  6.  
  7.   System.out.println("A class show method");
  8.  
  9. }
  10.  
  11. }

  1. package instanceofjava;
  2.  
  3. public class b {
  4.  
  5. public void show(){
  6.  
  7.   System.out.println("B class show method");
  8.  
  9. }
  10.  
  11. }


  1. package instanceofjava;
  2.  
  3. public class C extends A,B {  // not supported by java
  4.  
  5.  
  6.  
  7. public void print(){
  8.  
  9.   System.out.println("C class print method");
  10.  
  11. }
  12.  
  13. }


You Might Like:

1. Java Interview Programs On Core Java

2. Java Interview Programs On Collections 

3. What is The Output Of Following Programs Java Interview:

4. Java Concept and Example Program

Encapsulation in java with example program

What is meant by encapsulation in java?
  • Binding the data with its related functionalities known as encapsulation
  • Here data means variables and functionalities means methods.
  • So keeping the variable and related methods in one place.
  • That place is "class". class is the base for encapsulation.
  • Lets see example program on encapsulation, how the variables and methods defined in a class



What is encapsulation in object oriented programming?
 
Basic java example program on data encapsulation:
  1. package com.instanceofjava;
  2.  
  3. public class EncapsulationDemo {
  4.  
  5.   String name;
  6.   int rno;
  7.   String address;
  8.  
  9. public String getName() {
  10.        return name;
  11.  }
  12.  
  13. public void setName(String name) {
  14.         this.name = name;

  15. public int getRno() {
  16.        return rno;
  17. }
  18.  
  19. public void setRno(int rno) {
  20.      this.rno = rno;
  21. }
  22.  
  23. public String getAddress() {
  24.         return address;
  25. }
  26.  
  27.  public void setAddress(String address) {
  28.     this.address = address;
  29. }
  30.  
  31. public void showInfo(){
  32.  
  33.       System.out.println("Name: "+getName());
  34.       System.out.println("R.No: "+getRno());
  35.       System.out.println("Name: "+getAddress());
  36.  
  37.     }
  38. }


Class:

  • The above example program shows how the variables and methods will be there in a class.
  • So class is the base for encapsulation
  • class is user defined data type in java means by using class we can structure our own programs.
  • Lest see a example program on class.

  1. package com.instanceofjava;
  2.  
  3. public class ClassDemo {
  4.  
  5.     //variables of a class
  6.    String empName;
  7.    int empId;
  8.    String Designation;
  9.  
  10.  //getter and setter methods for variables 
  11.  //by using these methods we can set the value to the variable and gat the value from the
  12.  //variables
  13.  
  14.  public String getEmpName() {
  15.         return empName;
  16. }
  17.  
  18.  public void setEmpName(String empName) {
  19.       this.empName = empName;
  20. }
  21.  
  22. public int getEmpId() {
  23.        return empId;
  24. }
  25.  
  26. public void setEmpId(int empId) {
  27.         this.empId = empId;
  28. }

  29. public String getDesignation() {
  30.         return Designation;
  31. }
  32.  
  33.  public void setDesignation(String designation) {
  34.         Designation = designation;
  35. }

  36. }

Object:

  • Instance of class is known as object.
  • Instance means dynamic memory allocation. So dynamic memory allocation to class is called object.
  • By using "new" keyword the object will be created dynamically.
  • Class is a template. By using object we will get memory for all variables so that we can use them.

  • We can create number of objects for one class based on our requirements.
  • Below an example program on class and object.


  1. package com.instanceofjava; 
  2.  
  3. public class User {
  4.  
  5.    String Name;
  6.     int Id;
  7.     String address;
  8.  
  9.  public String getName() {
  10.      return Name;
  11. }
  12.  
  13. public void setName(String name) {
  14.         Name = name;
  15. }
  16.  
  17. public int getId() {
  18.       return Id;
  19. }
  20.  
  21. public void setId(int id) {
  22.        Id = id;
  23. }
  24.  
  25. public String getAddress() {
  26.         return address;
  27. }
  28.  
  29. public void setAddress(String address) {
  30.         this.address = address;
  31. }
  32.  
  33. public static void main(String [] args){
  34.  
  35.        User obj= new User();
  36.  
  37.         obj.setName("sai");
  38.         obj.setId(1);
  39.         obj.setAddress("xyz");
  40.  
  41.         System.out.println(obj.getName());
  42.         System.out.println(obj.getId());
  43.         System.out.println(obj.getAddress());
  44.  
  45.     }
  46. }

Output:

  1. sai
  2. 1
  3. xyz


encapsulation in java

Select Menu