OOP Interview Questions

Class, Object

Class

A class is a Template for creating multiple objects. A class defines state and behavior that an object can exhibit.

Object

Object is an instance of class. We can create multiple objects using the same class.

class vs object

Class is a template. Object is the instance created by the template.

Different ways of creating object in Java

  • Use the new keyword: The most common should be using the new keyword to create a new instance of class
  • Use New Instance: If we know the name of the class and the class has a public default constructor, we can use Class.forName to load the class. Then use the newInstace method to create an object
  • Clone method
  • Deserialization

 

Encapsulation, Abstraction, Inheritance, Polymorphism

Encapsulation

  • Encapsulation is a process of binding or wrapping the data and the codes that operates on the data into a single entity. This keeps the data safe from outside interface and misuse.
  • Implementation: access modifiers for data like private, protected and operation methods like get and set.

Abstraction

  • Abstraction is the concept of hiding irrelevant details. In other words make complex system simple by hiding the unnecessary detail from the user.
  • implementation: Abstract class and Interface.

Inheritance

  • One class is allow to inherit the features(fields and methods) of another class.

Polymorphism

  • Same code but have different behavior.
  • Example: Animal, Cat, Dog. Run()

 Access Modifier

Default(No Access Modifiers)

only within the same package (No subclass in different package)

private

!not for class and interface

only in the same class(No subclass, no same package)

protected

all class in the same package, subclass in different package

public

everywhere

Non-Access Modifiers

static

  • static variables
  • static method
  • static block

final

  • final variable
  • final method
  • final class

abstract

An abstract class can never be instantiated. If a class is declared as abstract then the sole purpose is for the class to be extended.

synchronized

The synchronized keyword used to indicate that a method can be accessed by only one thread at a time. The synchronized modifier can be applied with any of the four access level modifiers.

transient

An instance variable is marked transient to indicate the JVM to skip the particular variable when serializing the object containing it.

This modifier is included in the statement that creates the variable, preceding the class or data type of the variable.

volatile

The volatile modifier is used to let the JVM know that a thread accessing the variable must always merge its own private copy of the variable with the master copy in the memory.

Accessing a volatile variable synchronizes all the cached copied of the variables in the main memory. Volatile can only be applied to instance variables, which are of type object or private. A volatile object reference can be null.

native

Super, This

super

  1. The sub class and parent class have the same variable and method. super.variable or method name to get the method or variable in the parent class
  2. super() call constructor of parent class. Must put in the first line.

this

  1. get the method or variable of this class
  2. create the instance of this class for return or use as parameter in method or argument in constructor.

Override, Overload

 

Object Class

equals()

toString()

hashCode()

clone()

finalize()

Association, Composition, Aggregation

Association

Association is relation between two separate classes which establishes through their Objects. Association can be one-to-one, one-to-many, many-to-one, many-to-many.
In Object-Oriented programming, an Object communicates to other Object to use functionality and services provided by that object. Composition and Aggregation are the two forms of association.

Aggregation

It is a special form of Association where:

  • It is a special form of Association where:
  • It is a unidirectional association i.e. a one way relationship. For example, department can have students but vice versa is not possible and thus unidirectional in nature.
  • In Aggregation, both the entries can survive individually which means ending one entity will not effect the other entity

Composition

Composition is a restricted form of Aggregation in which two entities are highly dependent on each other.

  • It represents part-of relationship.
  • In composition, both the entities are dependent on each other.
  • When there is a composition between two entities, the composed object cannot exist without the other entity.

Aggregation VS Composition

    1. Dependency: Aggregation implies a relationship where the child can exist independently of the parent. For example, Bank and Employee, delete the Bank and the Employee still exist. whereas Composition implies a relationship where the child cannot exist independent of the parent. Example: Human and heart, heart don’t exist separate to a Human
    2. Type of Relationship: Aggregation relation is “has-a” and composition is “part-of” relation.
    3. Type of association: Composition is a strong Association whereas Aggregation is a weak Association.
Advertisements

461. Hamming Distance

The Hamming distance between two integers is the number of positions at which the corresponding bits are different.

Given two integers x and y, calculate the Hamming distance.

Note:
0 ≤ x, y < 231.

Example:

Input: x = 1, y = 4

Output: 2

Explanation:
1 (0 0 0 1)
4 (0 1 0 0)
↑ ↑

The above arrows point to positions where the corresponding bits are different.

My Code:

public class Solution {
    public int hammingDistance(int x, int y) {
        int xor = x ^ y;
        int count = 0;
        while(xor != 0){
            xor = xor & (xor - 1);
            count++;
        }
        return count;
    }
}

Idea:
1. xor to get different bits;
2. count the bits which is one;

Skills:
How to count bits that is one
1) x & (x – 1)to remove the last one。count x & (x – 1) until the number to be zero, to get the count of how many one has been removed.
2)

</pre>
<span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i=<span class="hljs-number">0</span>;i<<span class="hljs-number">32</span>;i++) <span class="hljs-keyword">count</span> += (xor >> i) & <span class="hljs-number">1</span>;

3)

</pre>
<span class="hljs-keyword">return</span> Integer.bitCount(x ^ y);

Two Sum I II III

1. Two Sum 1
Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
不排序,给特定target,问数组里是否有两数之和与target相等。
利用hashmap, key存每个数或者target与数的差值,value存index

public class Solution {
    public int[] twoSum(int[] nums, int target) {
        Map<Integer, Integer> map = new HashMap<>();
        int[] result = new int[2];
        for(int i = 0; i < nums.length; i++){
            if(map.containsKey(target - nums[i])){
                result[0] = map.get(target - nums[i]);
                result[1] = i;
                break;
            }else{
                map.put(nums[i], i);
            }
        }
        return result;
    }
}

2. Two Sum II
Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number.

The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.

You may assume that each input would have exactly one solution and you may not use the same element twice.

Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2
简单方法利用双指针,比和大,尾指针–,比和小头指针++;提高效率可以结合binary search,比和大,判断中点加头指针,如果仍然比头大,尾指针直接移到中点,另一半同理。

public class Solution {
    public int[] twoSum(int[] numbers, int target) {
        int start = 0;
        int end = numbers.length - 1;
        int[] result = new int[2];
        while(start + 1< end){
            int middle = start + (end - start)/2;
            if((numbers[start] + numbers[end]) < target){
                if((numbers[middle] + numbers[end]) == target){
                    start = middle;
                    break;
                }else if(numbers[middle] + numbers[end] < target){
                    start = middle + 1;
                }else{
                    start++;
                }
                
            }else if((numbers[start] + numbers[end]) > target){
                if((numbers[start] + numbers[middle]) == target){
                    end = middle;
                    break;
                }else if(numbers[middle] + numbers[start] > target){
                    end = middle - 1;
                }else{
                    end--;
                }
            }else{
                break;
            }
        }
        result[0] = start + 1;
        result[1] = end + 1;
        return result;
    }
}

3.Two Sum III
Design and implement a TwoSum class. It should support the following operations: add and find.

add – Add the number to an internal data structure.
find – Find if there exists any pair of numbers which sum is equal to the value.

For example,
add(1); add(3); add(5);
find(4) -> true
find(7) -> false
利用一个hashmap,key是每一个数,value是每个数出现的次数。当要组成target的两个数相等是,要确定这个是是不是在map里有不止一个

public class TwoSum {

    /** Initialize your data structure here. */
    Map<Integer, Integer> map;
    public TwoSum() {
        map = new HashMap<Integer, Integer>();
    }
    
    /** Add the number to an internal data structure.. */
    public void add(int number) {
        if(map.containsKey(number)){
            map.put(number, map.get(number) + 1);
        }else{
            map.put(number, 1);
        }
    }
    
    /** Find if there exists any pair of numbers which sum is equal to the value. */
    public boolean find(int value) {
        for(Map.Entry<Integer, Integer> entry : map.entrySet()){
            int i = entry.getKey();
            int j = value - i;
            if((i == j && entry.getValue() > 1) || (i != j && map.containsKey(j))){
                return true;
            }
        }
        return false;
    }
}

Delete Node in a LinkedList

Linked List

easy

If we want to delete the given node directly, we need to know the previous node. Obviously, we cannot get such information. Thus we copy the value of the next node to the current node and delete the next node.

/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public void deleteNode(ListNode node) {
node.val = node.next.val;
node.next = node.next.next;
}
}