Sunday, January 31, 2021

Access Specifiers

 There are four types of access specifiers in java:

1. Private:The private access modifier id accessible only within class.

2. Default: If you don't use any modifier, It is treated as default by-default. The default modifier is accessible only within package.

3. Protected: The protected access modifier is accessible within package and outside package but through inheritance only.

Note:The protected access modifier can be applied on the data member, method and constructor. It can't be applied on the class.

4. Public: The public access modifier is accessible everywhere. it has the widest scope among all other modifiers.

                            OR

public: Accessible to all. Other objects can also access this member variable or function.
private: Not accessible by other objects. Private members can be accessed only by the methods in the same class. Object accessible only in class in which they are declared.
protected: The scope of a protected variable is within the class which declares it and in the class which inherits from the class (Scope is class and subclass).
Default: Scope is Package Level. We do not need to explicitly mention default as when we do not mention any access specifier it is considered as default.

OOPS Concepts

Q. What is OOPS Concepts?

A: Object-oriented programming System(OOPs) is a programming paradigm based on the concept of “objects” that contain data and methods. The primary purpose of object-oriented programming is to increase the flexibility and maintainability of programs. 

Q. What is an Object?

A: Object: is a bundle of data and its behaviour(often known as methods).

Objects have two characteristics: They have states and behaviors.

Examples of states and behaviors
Example 1:
Object: House
State: Address, Color, Area
Behavior: Open door, close door

class House {
   String address;
   String color;
   double are;
   void openDoor() {
      //Write code here
   }
   void closeDoor() {
      //Write code here
   }
 ...
 ...
}

So if I had to write a class based on states and behaviours of House. I can do it like this: States can be represented as instance variables and behaviours as methods of the class.

Example 2:
Let’s take another example.
Object: Car
State: Color, Brand, Weight, Model
Behavior: Break, Accelerate, Slow Down, Gear change.

Object Oriented Programming features:

 a. Abstraction
 b. Encapsulation
 c. Inheritance
 d. Polymorphism
Abstraction: Abstraction is a process where you show only “relevant” data and “hide” unnecessary details of an object from the user.
Encapsulation:Encapsulation simply means binding object state(fields) and behavior(methods) together. If you are creating class, you are doing encapsulation.

Encapsulation example in Java

How to
1) Make the instance variables private so that they cannot be accessed directly from outside the class. You can only set and get values of these variables through the methods of the class.
2) Have getter and setter methods in the class to set and get the values of the fields.

class EmployeeCount
{
   private int numOfEmployees = 0;
   public void setNoOfEmployees (int count)
   {
       numOfEmployees = count;
   }
   public double getNoOfEmployees () 
   {
       return numOfEmployees;
   }
}
public class EncapsulationExample
{
   public static void main(String args[])
   {
      EmployeeCount obj = new EmployeeCount ();
      obj.setNoOfEmployees(5613);
      System.out.println("No Of Employees: "+(int)obj.getNoOfEmployees());
    }
}

Output:

No Of Employees: 5613
The class EncapsulationExample that is using the Object of class EmployeeCount will not able to get the NoOfEmployees directly. It has to use the setter and getter methods of the same class to set and get the value.
So what is the benefit of encapsulation in java programming
Well, at some point of time, if you want to change the implementation details of the class EmployeeCount, you can freely do so without affecting the classes that are using it.

Inheritance:The process by which one class acquires the properties and functionalities of another class is called inheritance. Inheritance provides the idea of reusability of code 

Types of Inheritance:
Single Inheritance:refers to a child and parent class relationship where a class extends the another class.
Multilevel Inheritance:refers to a child and parent class relationship where a class extends the child class. For example class A extends class B and class B extends class C.

Hierarchical inheritance: refers to a child and parent class relationship where more than one classes extends the same class. For example, class B extends class A and class C extends class A.

Multiple Inheritance:refers to the concept of one class extending more than one classes, which means a child class has two parent classes. Java doesn’t support multiple inheritance. Java doesn’t allow multiple inheritance to avoid the ambiguity caused by it.

Polymorphism: polymorphism is a object oriented programming feature that allows us to perform a single action in different ways. 
public abstract class Animal{
   ...
   public abstract void animalSound();
}
public class Lion extends Animal{
...
    @Override
    public void animalSound(){
        System.out.println("Roar");
    }
}

and

public class Dog extends Animal{

...
    @Override
    public void animalSound(){
        System.out.println("Woof");
    }
} 

Types of Polymorphism:

1. Method Overloading: Method Overloading is a feature that allows a class to have more than one method having the same name, if their argument lists are different.

2. Method Overriding: 

IS-A & HAS-A Relationships

A Car IS-A Vehicle and HAS-A License then the code would look like this:

public class Vehicle{ }
public class Car extends Vehicle{
   private License myCarLicense;
}

Note:Generalization is the process of extracting shared characteristics from two or more classes, and combining them into a generalized superclass. Shared characteristics can be attributes or methods.

Specialization means creating new subclasses from an existing class. If it turns out that certain attributes or methods only apply to some of the objects of the class, a subclass can be created.

Reference:https://beginnersbook.com/2013/04/oops-concepts/

Java 8 Features

 Q.  Java 8 features

A: There are many features of java 8.

  1.  Method references/Anonymous functions,
  2. Lambda expressions,
  3. Functional interfaces,
  4. Stream API,
  5. Default methods,
  6. Base64 Encode Decode,
  7. Static methods in interface,
  8. Optional class,
  9. Collectors class,
  10. ForEach() method,
  11. Parallel array sorting,
Method references/Anonymous functions

Java provides a new feature called method reference. Method reference is used to refer method of functional interface. It is compact and easy form of lambda expression. Each time when you are using lambda expression to just referring a method, you can replace your lambda expression with method reference.

Types of Method references:

There are following types of method references in java:
  1. Reference to a static method: Syntex:- ContainingClass::staticMethodName 

  1. interface Sayable{  
  2.     void say();  
  3. }  
  4. public class MethodReference {  
  5.     public static void saySomething(){  
  6.         System.out.println("Hello, this is static method.");  
  7.     }  
  8.     public static void main(String[] args) {  
  9.         // Referring static method  
  10.         Sayable sayable = MethodReference::saySomething;  
  11.         // Calling interface method  
  12.         sayable.say();  
  13.     }  
  14. }

In the following example, we are using predefined functional interface Runnable to refer static method.

  1. public class MethodReference2 {  
  2.     public static void ThreadStatus(){  
  3.         System.out.println("Thread is running...");  
  4.     }  
  5.     public static void main(String[] args) {  
  6.         Thread t2=new Thread(MethodReference2::ThreadStatus);  
  7.         t2.start();       
  8.     }  
  9. }  

Example 3

You can also use predefined functional interface to refer methods. In the following example, we are using BiFunction interface and using it's apply() method.

  1. import java.util.function.BiFunction;  
  2. class Arithmetic{  
  3. public static int add(int a, int b){  
  4. return a+b;  
  5. }  
  6. }  
  7. public class MethodReference3 {  
  8. public static void main(String[] args) {  
  9. BiFunction<Integer, Integer, Integer>adder = Arithmetic::add;  
  10. int result = adder.apply(1020);  
  11. System.out.println(result);  
  12. }  
  13. }  

Example 4

You can also override static methods by referring methods. In the following example, we have defined and overloaded three add methods.

  1. import java.util.function.BiFunction;  
  2. class Arithmetic{  
  3. public static int add(int a, int b){  
  4. return a+b;  
  5. }  
  6. public static float add(int a, float b){  
  7. return a+b;  
  8. }  
  9. public static float add(float a, float b){  
  10. return a+b;  
  11. }  
  12. }  
  13. public class MethodReference4 {  
  14. public static void main(String[] args) {  
  15. BiFunction<Integer, Integer, Integer>adder1 = Arithmetic::add;  
  16. BiFunction<Integer, Float, Float>adder2 = Arithmetic::add;  
  17. BiFunction<Float, Float, Float>adder3 = Arithmetic::add;  
  18. int result1 = adder1.apply(1020);  
  19. float result2 = adder2.apply(1020.0f);  
  20. float result3 = adder3.apply(10.0f, 20.0f);  
  21. System.out.println(result1);  
  22. System.out.println(result2);  
  23. System.out.println(result3);  
  24. }  
  25. }  
Reference to an instance method.:

like static methods, you can refer instance methods also. In the following example, we are describing the process of referring the instance method.

Syntax

  1. containingObject::instanceMethodName  

Example 1

In the following example, we are referring non-static methods. You can refer methods by class object and anonymous object.

  1. interface Sayable{  
  2.     void say();  
  3. }  
  4. public class InstanceMethodReference {  
  5.     public void saySomething(){  
  6.         System.out.println("Hello, this is non-static method.");  
  7.     }  
  8.     public static void main(String[] args) {  
  9.         InstanceMethodReference methodReference = new InstanceMethodReference(); // Creating object  
  10.         // Referring non-static method using reference  
  11.             Sayable sayable = methodReference::saySomething;  
  12.         // Calling interface method  
  13.             sayable.say();  
  14.             // Referring non-static method using anonymous object  
  15.             Sayable sayable2 = new InstanceMethodReference()::saySomething; // You can use anonymous object also  
  16.             // Calling interface method  
  17.             sayable2.say();  
  18.     }  
  19. }  
Test it Now

Output:

Hello, this is non-static method.
Hello, this is non-static method.

Example 2

In the following example, we are referring instance (non-static) method. Runnable interface contains only one abstract method. So, we can use it as functional interface.

  1. public class InstanceMethodReference2 {  
  2.     public void printnMsg(){  
  3.         System.out.println("Hello, this is instance method");  
  4.     }  
  5.     public static void main(String[] args) {  
  6.     Thread t2=new Thread(new InstanceMethodReference2()::printnMsg);  
  7.         t2.start();       
  8.     }  
  9. }  
Test it Now

Output:

Hello, this is instance method

Example 3

In the following example, we are using BiFunction interface. It is a predefined interface and contains a functional method apply(). Here, we are referring add method to apply method.

  1. import java.util.function.BiFunction;  
  2. class Arithmetic{  
  3. public int add(int a, int b){  
  4. return a+b;  
  5. }  
  6. }  
  7. public class InstanceMethodReference3 {  
  8. public static void main(String[] args) {  
  9. BiFunction<Integer, Integer, Integer>adder = new Arithmetic()::add;  
  10. int result = adder.apply(1020);  
  11. System.out.println(result);  
  12. }  
  13. }  
Reference to a constructor:

You can refer a constructor by using the new keyword. Here, we are referring constructor with the help of functional interface.

Syntax

  1. ClassName::new  

Example

  1. interface Messageable{  
  2.     Message getMessage(String msg);  
  3. }  
  4. class Message{  
  5.     Message(String msg){  
  6.         System.out.print(msg);  
  7.     }  
  8. }  
  9. public class ConstructorReference {  
  10.     public static void main(String[] args) {  
  11.         Messageable hello = Message::new;  
  12.         hello.getMessage("Hello");  
  13.     }  
  14. }  



3. Functional/SAM interface:Functional interfaces are those interfaces which can have only one abstract method. It can have any number of default, static methods but can contain only one abstract method.

Note: Java provides predefined functional interfaces to deal with functional programming by using lambda and method references.



String coding questioon

  How do you reverse a given string in place? ( solution ) How do you print duplicate characters from a string? ( solution ) How do you chec...