• 검색 결과가 없습니다.

PROGRAMMING

문서에서 Java Interview Notes (페이지 38-50)

Polymorphism

Polymorphism is an ability of a class instance to take different forms based on the instance its acting upon.

Polymorphism is primarily achieved by subclassing or by implementing an interface. The derived classes can have its own unique implementation for certain feature and yet share some of the functionality through inheritance.

Behaviour of object depends specifically on its position in the class hierarchy.

Consider you have a Furniture class, which has addLegs() method; and a Chair and a Table class, both extend Furniture class and have their own implementation of addLegs() method. In this situation, the implementation of addLegs() method that gets called is determined by the runtime, depending whether you have a Chair or a Table instance.

public abstract class Furniture { public abstract void addLegs();

public void print(String message){

System.out.println(message);

} }

class Chair extends Furniture { @Override

public void addLegs() { print(“Chair Legs Added”);

} }

class Table extends Furniture{

@Override

public void addLegs() { print(“Table Legs Added”);

} }

Furniture furniture = new Chair();

// This prints “Chair Legs Added”

furniture.addLegs();

furniture = new Table();

// This prints “Table Legs Added”

furniture.addLegs();

Benefits of polymorphism

The real power and benefit of polymorphism can be achieved when you can code to an abstract base class or an interface. Based on the context, polymorphism enables the selection of most appropriate class implementation. Not only in production code, it also paves way to have an alternate implementation for testing.

Questions

What is Polymorphism?

What are different ways to achieve polymorphism?

How is inheritance useful to achieve polymorphism?

What are the benefits of polymorphism?

How is polymorphism concept useful for unit testing?

Parametric polymorphism

In Java, Generics facilitates implementation for Parametric polymorphism, which enables using the same code implementation with the values of different types, without

compromising on compile time type safety check.

In the example below, we added an upper bound to type parameter T such that it implements an interface that guarantees getWheelsCount() method in the type T.

interface Vehicle { int getWheelsCount();

}

class Car<T extends Vehicle> { private T vehicle;

public Car(T vehicle) { this.vehicle = vehicle;

}

public int getWheelsCount() { return vehicle.getWheelsCount();

} }

It takes parameter of type T and returns count of wheels, without worrying about what type T actually is.

Questions

What is Parametric Polymorphism?

How Generics is used to achieve Parametric Polymorphism?

How are Type Wildcards used to achieve Parametric Polymorphism?

Can you achieve Parametric Polymorphism without Generics?

Subtype polymorphism

In Subtype polymorphism, also known as inclusion polymorphism, the parameter definition of a function supports any argument of a type or its subtype.

In the code below, the method printWheelsCount() takes Vehicle as parameter and prints count of wheels in the Vehicle. The main method shows subtype polymorphic calls, passing objects of Car and Bike as arguments to the printWheelsCount() method. Every place where it expects a type as parameter, it also accepts subclass of that type as

parameter.

abstract class Vehicle{

public abstract int getWheelsCount();

}

class Car extends Vehicle{

@Override

public int getWheelsCount() { return 4;

} }

class Bike extends Vehicle{

@Override

public int getWheelsCount() { return 2;

} }

public void printWheelsCount(Vehicle vehicle) { print(vehicle.getWheelsCount());

}

public void main(String[] args) { printWheelsCount(new Car());

printWheelsCount(new Bike());

}

Questions

What is Subtype Polymorphism?

What is Inclusion Polymorphism?

What is the difference between Parametric Polymorphism and SubType Polymorphism?

Can you achieve SubType polymorphism using Generics?

Overriding

Method overriding is redefining the base class method to behave in a different manner than its implementation in the base class.

Method overriding is an example of dynamic or runtime polymorphism.

In dynamic polymorphism, runtime takes the decision to call an implementation, as compiler does not know what to bind at compile time.

Rules for method overriding

Method arguments and its order must be same in the overriding method.

Overriding method can have same return type or subtype of base class method’s return type.

Access modifier of overridden method cannot be more restrictive than its definition in base class.

Constructor, static and final method cannot be overridden.

Overridden method cannot throw checked exception if its definition in base class doesn’t, though overridden method can still throw unchecked exception.

Questions

What is method overriding?

What is dynamic polymorphism?

Why can’t you override static methods defined in super class or interface?

Can you override a final method defined in super class?

Can you override a public method in super class and mark it protected?

Why can’t you override constructor of super class?

Can an overriding method throw checked exception; when the overridden method in the super class does not? Why?

What are the benefits of method overriding?

@Override

@Override annotation is way to explicitly declare the intention of overriding the method implementation in the base class. Java performs compile time checking for all such

annotated methods. It provides an easy way to mistake proof against accidentally writing wrong method signature, when you want to override from base class.

If a derived class defines a method having the same signature as a method in the base class, the method in the derived class hides the one in the base class. By prefixing a

subclass’s method header with the @Override annotation, you can detect if an inadvertent attempt is made to overload instead of overriding a method.

Questions

What is the purpose of @Override annotation?

What happens if you define a method with the same signature as defined in the super class and not use @Override annotation?

What are the benefits of @Override annotation?

Overloading

Method overloading is defining more than one method with the same name, but with different parameters.

Method overloading is an example of static or compile-time polymorphism.

In static polymorphism, it’s while writing the code, decision is made to call a specific implementation.

Rules for method overloading

Method can be overloaded by defining method with the same name as an existing one, having

Different number of argument list.

Different datatype of arguments.

Different order of arguments.

Return type of the overloaded method can be different.

Method with the same name and exactly the same parameters cannot be defined, when they differ only by return type.

Overloading method is not required to throw same exception as the method its overloading.

Operator Overloading

Operator overloading is an ability to enhance the definition of language dependent

operators. For example, you can use

+

operator to add two integers and also to concat two strings.

Questions

Explain method overloading?

What is static polymorphism?

What is the difference between static and dynamic polymorphism?

Can you override a method such that all the parameters are same with the difference only in the return type?

What is operator overloading?

What are the benefits of method overloading?

What is the difference between overriding and overloading?

Abstraction

Abstraction helps to move the focus from the internal details of the concrete

implementation to the type and its behaviour. Abstraction is all about hiding details about the data, its internal representation and implementation.

The other related object oriented concept is encapsulation, which could be used to abstract the complexities and the internal implementation of a class.

Abstraction also helps making the software maintainable, secure and provides an ability to change implementation without breaking any client.

Questions

What is abstraction?

How abstraction is different from encapsulation?

What are the benefits of abstraction?

Can you achieve abstraction without encapsulation?

Inheritance

Inheritance is an object oriented design concept that deals with reusing an existing class definition (known as super class) and defining more special categories of class (know as sub class) by inheriting that class. It focuses on establishing IS-A relationship between sub class and its super class. Inheritance is also used as technique to implement

polymorphism; when a derived type implements method defined in the base type.

Rules for Inheritance

There can be a multiple level of inheritance, based on the requirements to create specific categories.

Only single class inheritance is allowed in Java, as multiple inheritance comes with its share of complexity; see Diamond Problem.

Class declared final cannot be extended.

Class method declared final cannot be overridden.

Constructor and private members of the base class are not inherited.

The constructor of base class can be called using super().

The base class’s overridden method should be called using super keyword, otherwise you will end up calling the overriding method in the sub class recursively.

Questions

Explain inheritance?

What is the purpose of inheritance?

What should be the criteria to decide inheritance relation between two classes?

How inheritance plays an important role in polymorphism?

Can you inherit final class?

What happens if you don’t use super keyword to call an overridden member?

Why can’t you inherit static members defined in the super class?

What are the challenges you can face if multiple inheritance is possible in Java?

Composition

Composition is an object oriented design concept that is closely related to inheritance, as it also deals with reusing classes; but it focuses on establishing HAS-A relationship between classes. So unlike Inheritance, which deals with extending features of a class, composition reuses a class by composing it. Composition is achieved by storing reference of another class as a member.

Inheritance vs Composition

Problem with inheritance is that it breaks encapsulation as the derived class becomes tightly coupled to the implementation of the base class. The problem becomes complex when a class is not designed keeping future inheritance scope and you have no control over the base class. There is possibility of breaking a derived class because of changes in the base class.

So, inheritance must be used only when there is perfect IS-A relationship between the base and the derived class definitions; and in case of any confusion prefer composition over inheritance.

Questions

Explain composition?

What is the difference between inheritance and composition?

What should be the criteria to decide composition relation between two classes?

Explain few problems with inheritance that can be avoided by using composition?

When would you prefer composition over inheritance and vice versa?

FUNDAMENTAL

문서에서 Java Interview Notes (페이지 38-50)

관련 문서