oop job interview questions

Upload: hamid-mahmood

Post on 02-Apr-2018

218 views

Category:

Documents


0 download

TRANSCRIPT

  • 7/27/2019 OOP Job Interview Questions

    1/33

  • 7/27/2019 OOP Job Interview Questions

    2/33

    Op=new operation();Int rsquare=op.square(radius); //code reusability.Return pi*rsquare;

    }

    Void main(){Circle c=new circle();Double result=c.area(5);

    }

    }

    When use aggregation ?

    Inheritance should be used only if the relation is-a is maintained throughout the lifetime of the

    object invoked; otherwise aggregation is the best choice.

    If new class is more or less original class (you need override) use inheritance

    If new class need same as the original class (no need to override)

    use aggregation

    Types of Inheritance:

    Does java supports multiple inheritance?

    Java only supports only single inheritance. This means that a class cannot extend more than oneclass. Therefore following is illegal:

    public class extends Animal, Mammal{}

  • 7/27/2019 OOP Job Interview Questions

    3/33

  • 7/27/2019 OOP Job Interview Questions

    4/33

    1) One of the main disadvantages of inheritance in Java (the same in other object-oriented languages) is the increased time/effort it takes the program to jumpthrough all the levels of overloaded classes. If a given class has ten levels ofabstraction above it, then it will essentially take ten jumps to run through afunction defined in each of those classes

    2) Main disadvantage of using inheritance is that the two classes (base andinherited class) get tightly coupled.This means one cannot be used independent of each other.

    3) Also with time, during maintenance adding new features both base as well asderived classes are required to be changed. If a method signature is changedthen we will be affected in both cases (inheritance & composition)

    4) If a method is deleted in the "super class" or aggregate, then we will have to re-factor in case of using that method.Here things can get a bit complicated in caseof inheritance because our programs will still compile, but the methods of the

    subclass will no longer be overriding superclass methods. These methods willbecome independent methods in their own right.

    Overriding:

    If a class inherits a method from its super class, then there is a chance to override the methodprovided that it is not marked final.

    The benefit of overriding is: ability to define a behavior that's specific to the sub class type.

    Which means a subclass can implement a parent class method based on its requirement.

    Example:

    Let us look at an example.

    class Animal{

    public void move(){System.out.println("Animals can move");

    }}

    class Dog extends Animal{

    public void move(){System.out.println("Dogs can walk and run");

    }}

    public class TestDog{

    public static void main(String args[]){Animal a = new Animal(); // Animal reference and object

  • 7/27/2019 OOP Job Interview Questions

    5/33

    Animal b = new Dog(); // Animal reference but Dog object

    a.move();// runs the method in Animal class

    b.move();//Runs the method in Dog class}

    }

    This would produce following result:

    Animals can moveDogs can walk and run

    In the above example you can see that the even though b is a type of Animal it runs the movemethod in the Dog class. The reason for this is : In compile time the check is made on the

    reference type. However in the runtime JVM figures out the object type and would run the

    method that belongs to that particular object.

    Therefore in the above example, the program will compile properly since Animal class has the

    method move. Then at the runtime it runs the method specific for that object.

    Consider the following example :

    class Animal{

    public void move(){System.out.println("Animals can move");

    }}

    class Dog extends Animal{

    public void move(){System.out.println("Dogs can walk and run");

    }public void bark(){

    System.out.println("Dogs can bark");}

    }

    public class TestDog{

    public static void main(String args[]){

    Animal a = new Animal(); // Animal reference and objectAnimal b = new Dog(); // Animal reference but Dog object

    a.move();// runs the method in Animal classb.move();//Runs the method in Dog classb.bark();

    }}

  • 7/27/2019 OOP Job Interview Questions

    6/33

    This would produce following result:

    TestDog.java:30: cannot find symbolsymbol : method bark()location: class Animal

    b.bark();

    ^

    This program will throw a compile time error since b's reference type Animal doesn't have amethod by the name of bark.

    Rules for method overriding:

    The argument list should be exactly the same as that of the overridden method.

    The return type should be the same or a subtype of the return type declared in the original

    overridden method in the super class.

    The access level cannot be more restrictive than the overridden method's access level. For

    example: if the super class method is declared public then the overridding method in thesub class cannot be either private or protected.

    Instance methods can be overridden only if they are inherited by the subclass.

    A method declared final cannot be overridden.

    A method declared static cannot be overridden but can be re-declared.

    If a method cannot be inherited then it cannot be overridden.

    A subclass within the same package as the instance's superclass can override any

    superclass method that is not declared private or final.

    A subclass in a different package can only override the non-final methods declared publicor protected.

    An overriding method can throw any uncheck exceptions, regardless of whether the

    overridden method throws exceptions or not. However the overriding method should notthrow checked exceptions that are new or broader than the ones declared by the

    overridden method. The overriding method can throw narrower or fewer exceptions than

    the overridden method.

    Constructors cannot be overridden.

    What is static method in java?Answer:

    A Static method in Java is one that belongs to a class rather than an object of a class. Normalmethods of a class can be invoked only by using an object of the class but a Static method can be

    invoked Directly.

    Example:

    public class A {

    .....public static int getAge(){

  • 7/27/2019 OOP Job Interview Questions

    7/33

    ....

    }

    }

    public class B {

    .....int age = A.getAge();}

    In class B when we wanted the age value we directly called the method using the instance of theclass instead of instantiating an object of the class.

    Tip:

    A static method can access only static variables. The reason is obvious. Something that iscommon to a class cannot refer to things that are specific to an object...

    static variable

    It is a variable which belongs to the class and not to object(instance)

    Static variables are initialized only once , at the start of the execution . These variables will be

    initialized first, before the initialization of any instance variables

    A single copy to be shared by all instances of the class

    A static variable can be accessed directly by the class nameand doesnt need any object

    Syntax : .

    static method

    It is a method which belongs to the class and not to the object(instance)

    A static method can access only static data. It can not access non-static data (instance variables)

    A static method can callonly other static methods and can not call a non-static method from it.

    A static method can be accessed directly by the class nameand doesnt need any object

    Syntax : .

    A static method cannot refer to this or super keywords in anyway

    Side Note:

    main method is static , since it must be be accessible for an application to run , before anyinstantiation takes place.

  • 7/27/2019 OOP Job Interview Questions

    8/33

    Polymorphism:

    An object may takes different forms.

    There are two types of polymorphism:

    1) Static (Compile Time) Polymorphism

    Method Overloading is an example of static polymorphism

    Methods having same names but different parameters is called method

    overloading.

    e.g

    class DemoOverload{public int add(int x, int y){ //method 1return x+y;}public int add(int x, int y, int z){ //method 2return x+y+z;}public int add(double x, int y){ //method 3return (int)x+y;}public int add(int x, double y){ //method 4

    return x+(int)y;}

    }class Test{

    public static void main(String[] args){DemoOverload demo=new DemoOverload();System.out.println(demo.add(2,3)); //method 1 calledSystem.out.println(demo.add(2,3,4)); //method 2 calledSystem.out.println(demo.add(2,3.4)); //method 4 calledSystem.out.println(demo.add(2.5,3)); //method 3 called}

    }

    At compile time, Java knows which method to invoke by checking the methodsignatures. So, this is called compile time polymorphismor static binding.

    2) Dynamic (Run Time) Polymorphism

    Suppose a sub class overrides a particular method of the super class. Lets say, in the

    program we create an object of the subclass and assign it to the super class reference.Now, if we call the overridden method on the super class reference then the sub class

    version of the method will be called.

  • 7/27/2019 OOP Job Interview Questions

    9/33

    Have a look at the following example.

    class Vehicle{public void move(){System.out.println(Vehicles can move!!);}

    }class MotorBike extends Vehicle{

    public void move(){System.out.println(MotorBike can move and accelerate too!!);}

    }class Test{

    public static void main(String[] args){Vehicle vh=new MotorBike();vh.move(); // prints MotorBike can move and accelerate too!!vh=new Vehicle();vh.move(); // prints Vehicles can move!!}

    }

    It should be noted that in the first call to move(), the reference type is Vehicle and the

    object being referenced is MotorBike. So, when a call to move() is made, Java waits untilruntime to determine which object is actually being pointed to by the reference. In this

    case, the object is of the class MotorBike. So, the move() method ofMotorBike class

    will be called. In the second call to move(), the object is of the class Vehicle. So, the

    move() method ofVehicle will be called.

    As the method to call is determined at runtime, this is called dynamic binding orlate

    binding.

    The final Modifier:

    final Variables:A final variable can be explicitly initialized only once. A reference variable declared finalcan never be reassigned to refer to a different object.

    However the data within the object can be changed. So the state of the object can be

    changed but not the reference.With variables, the finalmodifier often is used with static to make the constant a class

    variable.

    Example:public class Test{final int value = 10;// The following are examples of declaring constants:public static final int BOXWIDTH = 6;static final String TITLE = "Manager";

    public void changeValue(){value = 12; //will give an error

    }}

  • 7/27/2019 OOP Job Interview Questions

    10/33

  • 7/27/2019 OOP Job Interview Questions

    11/33

    abstract Methods:

    An abstract method is a method declared without any implementation. The methods

    body(implementation) is provided by the subclass. Abstract methods can never be final or strict.

    Any class that extends an abstract class must implement all the abstract methods of the superclass unless the subclass is also an abstract class.

    If a class contains one or more abstract methods then the class must be declared abstract. Anabstract class does not need to contain abstract methods.

    The abstract method ends with a semicolon. Example: public abstract sample();

    Example:

    public abstract class SuperClass{abstract void m(); //abstract method

    }

    class SubClass extends SuperClass{// implements the abstract methodvoid m(){

    .........}

    }

    Abstraction:

    Abstraction refers to the ability to make a class abstract in OOP. An abstract class is one thatcannot be instantiated. All other functionality of the class still exists, and its fields, methods, and

    constructors are all accessed in the same manner. You just cannot create an instance of the

    abstract class.

    If a class is abstract and cannot be instantiated, the class does not have much use unless it is

    subclassed. This is typically how abstract classes come about during the design phase. A parentclass contains the common functionality of a collection of child classes, but the parent class itself

    is too abstract to be used on its own.

    Abstract Class:Use the abstract keyword to declare a class abstract. The keyword appears in the class

    declaration somewhere before the class keyword.

    /* File name : Employee.java */public abstract class Employee{

    private String name;

  • 7/27/2019 OOP Job Interview Questions

    12/33

    private String address;private int number;public Employee(String name, String address, int number){

    System.out.println("Constructing an Employee");this.name = name;this.address = address;this.number = number;

    }public double computePay(){System.out.println("Inside Employee computePay");return 0.0;

    }public void mailCheck(){

    System.out.println("Mailing a check to " + this.name+ " " + this.address);

    }public String toString()

    {return name + " " + address + " " + number;

    }public String getName(){

    return name;}public String getAddress(){

    return address;}public void setAddress(String newAddress){

    address = newAddress;}public int getNumber(){return number;

    }}

    Notice that nothing is different in this Employee class. The class is now abstract, but it still has

    three fields, seven methods, and one constructor.

    Now if you would try as follows:

    /* File name : AbstractDemo.java */public class AbstractDemo{

    public static void main(String [] args){

    /* Following is not allowed and would raise error */Employee e = new Employee("George W.", "Houston, TX", 43);

    System.out.println("\n Call mailCheck using

  • 7/27/2019 OOP Job Interview Questions

    13/33

    Employee reference--");e.mailCheck();

    }}

    When you would compile above class then you would get following error:

    Employee.java:46: Employee is abstract; cannot be instantiatedEmployee e = new Employee("George W.", "Houston, TX", 43);

    ^1 error

    Extending Abstract Class:

    We can extend Employee class in normal way as follows:

    /* File name : Salary.java */public class Salary extends Employee{

    private double salary; //Annual salarypublic Salary(String name, String address, int number, double

    salary){

    super(name, address, number);setSalary(salary);

    }public void mailCheck(){

    System.out.println("Within mailCheck of Salary class ");System.out.println("Mailing check to " + getName()+ " with salary " + salary);

    }public double getSalary(){

    return salary;}public void setSalary(double newSalary){

    if(newSalary >= 0.0){

    salary = newSalary;}

    }public double computePay(){

    System.out.println("Computing salary pay for " + getName());return salary/52;

    }}

    Here we cannot instantiate a new Employee, but if we instantiate a new Salary object, the Salaryobject will inherit the three fields and seven methods from Employee.

  • 7/27/2019 OOP Job Interview Questions

    14/33

    /* File name : AbstractDemo.java */public class AbstractDemo{

    public static void main(String [] args){

    Salary s = new Salary("Mohd Mohtashim", "Ambehta, UP",3, 3600.00);

    Salary e = new Salary("John Adams", "Boston, MA",2, 2400.00);

    System.out.println("Call mailCheck usingSalary reference --");

    s.mailCheck();System.out.println("\n Call mailCheck using

    Employee reference--");e.mailCheck();

    }}

    This would produce following result:

    Constructing an EmployeeConstructing an EmployeeCall mailCheck using Salary reference --Within mailCheck of Salary classMailing check to Mohd Mohtashim with salary 3600.0

    Call mailCheck using Employee reference--Within mailCheck of Salary classMailing check to John Adams with salary 2400.

    Abstract Methods:

    If you want a class to contain a particular method but you want the actual implementation of thatmethod to be determined by child classes, you can declare the method in the parent class as

    abstract.

    The abstract keyword is also used to declare a method as abstract.An abstract methods consist of

    a method signature, but no method body.

    Abstract method would have no definition, and its signature is followed by a semicolon, not

    curly braces as follows:

    public abstract class Employee{

    private String name;private String address;private int number;

    public abstract double computePay();

    //Remainder of class definition

  • 7/27/2019 OOP Job Interview Questions

    15/33

    }

    Declaring a method as abstract has two results:

    The class must also be declared abstract. If a class contains an abstract method, the class

    must be abstract as well.

    Any child class must either override the abstract method or declare itself abstract.

    A child class that inherits an abstract method must override it. If they do not, they must beabstract,and any of their children must override it.

    Eventually, a descendant class has to implement the abstract method; otherwise, you would havea hierarchy of abstract classes that cannot be instantiated.

    If Salary is extending Employee class then it is required to implement computePay() method asfollows:

    /* File name : Salary.java */public class Salary extends Employee{

    private double salary; // Annual salary

    public double computePay(){

    System.out.println("Computing salary pay for " + getName());return salary/52;

    }

    //Remainder of class definition}

    Encapsulation:

    Encapsulation is one of the four fundamental OOP concepts. The other three are inheritance,

    polymorphism, and abstraction.

    Encapsulation is the technique of making the fields in a class private and providing access to thefields via public methods. If a field is declared private, it cannot be accessed by anyone outside

    the class, thereby hiding the fields within the class. For this reason, encapsulation is also referred

    to as data hiding.

    Encapsulation can be described as a protective barrier that prevents the code and data being

    randomly accessed by other code defined outside the class. Access to the data and code is tightly

    controlled by an interface.

    The main benefit of encapsulation is the ability to modify our implemented code without

    breaking the code of others who use our code. With this feature Encapsulation givesmaintainability, flexibility and extensibility to our code.

  • 7/27/2019 OOP Job Interview Questions

    16/33

    Example:

    Let us look at an example that depicts encapsulation:

    /* File name : EncapTest.java */

    public class EncapTest{

    private String name;private String idNum;private int age;

    public int getAge(){return age;

    }

    public String getName(){return name;

    }

    public String getIdNum(){return idNum;

    }

    public void setAge( int newAge){age = newAge;

    }

    public void setName(String newName){name = newName;

    }

    public void setIdNum( String newId){

    idNum = newId;}

    }

    The public methods are the access points to this class's fields from the outside java world.

    Normally these methods are referred as getters and setters. Therefore any class that wants to

    access the variables should access them through these getters and setters.

    The variables of the EncapTest class can be access as below::

    /* File name : RunEncap.java */public class RunEncap{

    public static void main(String args[]){EncapTest encap = new EncapTest();encap.setName("James");encap.setAge(20);encap.setIdNum("12343ms");

    System.out.print("Name : " + encap.getName()+" Age : "+ encap.getAge());

    }

  • 7/27/2019 OOP Job Interview Questions

    17/33

    }

    This would produce following result:

    Name : James Age : 20

    Benefits of Encapsulation:

    The fields of a class can be made read-only or write-only.

    A class can have total control over what is stored in its fields.

    The users of a class do not know how the class stores its data. A class can change the datatype of a field, and users of the class do not need to change any of their code.

    Interfaces:

    An interface is a collection of abstract methods. A class implements an interface, thereby

    inheriting the abstract methods of the interface.

    An interface is not a class. Writing an interface is similar to writing a class, but they are two

    different concepts. A class describes the attributes and behaviors of an object. An interface

    contains behaviors that a class implements.

    Unless the class that implements the interface is abstract, all the methods of the interface need to

    be defined in the class.

    An interface is similar to a class in the following ways:

    An interface can contain any number of methods. An interface is written in a file with a .java extension, with the name of the interface

    matching the name of the file.

    The bytecode of an interface appears in a .class file.

    Interfaces appear in packages, and their corresponding bytecode file must be in a

    directory structure that matches the package name.

    However, an interface is different from a class in several ways, including:

    You cannot instantiate an interface.

    An interface does not contain any constructors.

    All of the methods in an interface are abstract. An interface cannot contain instance fields. The only fields that can appear in an interface

    must be declared both static and final.

    An interface is not extended by a class; it is implemented by a class.

    An interface can extend multiple interfaces.

    Declaring Interfaces:

  • 7/27/2019 OOP Job Interview Questions

    18/33

    The interface keyword is used to declare an interface. Here is a simple example to declare an

    interface:

    Example:

    Let us look at an example that depicts encapsulation:

    /* File name : NameOfInterface.java */import java.lang.*;//Any number of import statements

    public interface NameOfInterface{

    //Any number of final, static fields//Any number of abstract method declarations\

    }

    Interfaces have the following properties:

    An interface is implicitly abstract. You do not need to use the abstract keyword whendeclaring an interface.

    Each method in an interface is also implicitly abstract, so the abstract keyword is not

    needed.

    Methods in an interface are implicitly public.

    Example:

    /* File name : Animal.java */

    interface Animal {

    public void eat();public void travel();

    }

    Implementing Interfaces:

    When a class implements an interface, you can think of the class as signing a contract, agreeing

    to perform the specific behaviors of the interface. If a class does not perform all the behaviors of

    the interface, the class must declare itself as abstract.

    Aclass uses the implements keyword to implement an interface. The implements keywordappears in the class declaration following the extends portion of the declaration.

    /* File name : MammalInt.java */public class MammalInt implements Animal{

    public void eat(){System.out.println("Mammal eats");

    }

  • 7/27/2019 OOP Job Interview Questions

    19/33

    public void travel(){

    System.out.println("Mammal travels");}

    public int noOfLegs(){return 0;

    }

    public static void main(String args[]){MammalInt m = new MammalInt();m.eat();m.travel();

    }}

    This would produce following result:

    Mammal eats

    Mammal travels

    When overriding methods defined in interfaces there are several rules to be followed:

    Checked exceptions should not be declared on implementation methods other than the

    ones declared by the interface method or subclasses of those declared by the interface

    method.

    The signature of the interface method and the same return type or subtype should be

    maintained when overriding the methods.

    An implementation class itself can be abstract and if so interface methods need not be

    implemented.

    When implementation interfaces there are several rules:

    A class can implement more than one interface at a time.

    A class can extend only one class, but implement many interface.

    An interface can extend another interface, similarly to the way that a class can extend

    another class.

    Extending Interfaces:

    An interface can extend another interface, similarly to the way that a class can extend another

    class. The extends keyword is used to extend an interface, and the child interface inherits themethods of the parent interface.

    The following Sports interface is extended by Hockey and Football interfaces.

    //Filename: Sports.javapublic interface Sports{

    public void setHomeTeam(String name);

  • 7/27/2019 OOP Job Interview Questions

    20/33

    public void setVisitingTeam(String name);}

    //Filename: Football.javapublic interface Football extends Sports{

    public void homeTeamScored(int points);public void visitingTeamScored(int points);public void endOfQuarter(int quarter);

    }

    //Filename: Hockey.javapublic interface Hockey extends Sports{

    public void homeGoalScored();public void visitingGoalScored();public void endOfPeriod(int period);public void overtimePeriod(int ot);

    }

    The Hockey interface has four methods, but it inherits two from Sports; thus, a class thatimplements Hockey needs to implement all six methods. Similarly, a class that implements

    Football needs to define the three methods from Football and the two methods from Sports.

    Extending Multiple Interfaces:

    A Java class can only extend one parent class. Multiple inheritance is not allowed. Interfaces arenot classes, however, and an interface can extend more than one parent interface.

    The extends keyword is used once, and the parent interfaces are declared in a comma-separated

    list.

    For example, if the Hockey interface extended both Sports and Event, it would be declared as:

    public interface Hockey extends Sports, Event

    Tagging Interfaces:

    The most common use of extending interfaces occurs when the parent interface does not contain

    any methods. For example, the MouseListener interface in the java.awt.event package extended

    java.util.EventListener, which is defined as:

    package java.util;public interface EventListener{}

    An interface with no methods in it is referred to as a tagging interface. There are two basicdesign purposes of tagging interfaces:

  • 7/27/2019 OOP Job Interview Questions

    21/33

    Creates a common parent: As with the EventListener interface, which is extended by dozens of

    other interfaces in the Java API, you can use a tagging interface to create a common parent

    among a group of interfaces. For example, when an interface extends EventListener, the JVMknows that this particular interface is going to be used in an event delegation scenario.

    Adds a data type to a class: This situation is where the term tagging comes from. A class thatimplements a tagging interface does not need to define any methods (since the interface does not

    have any), but the class becomes an interface type through polymorphism.

    What is a virtual function?

    0

    inShare digg

    What are virtual function/method and virtual class in java?

    Posted byadminon September 9, 2012 inArticles,JavaNo comments

    Virtual Function/Method in Java

    In Java there is no keyword names virtual.

    Definition of Virtual from wiki:

    In object-oriented programming, a virtual function or virtual method is a function or method

    whose behaviour can be overridden within an inheriting class by a function with the same

    signature to provide the polymorphic behavior.

    Therefore according to definition, every non-static method in JAVA is by default virtual method

    except final and private methods. The methods which cannot be inherited for polymorphic

    behavior is not a virtual method.

    public class Vehicle{

    public void fuel(){

    System.out.println(Fuel Vehicle);

    http://www.spjava.com/what-are-virtual-functionmethod-and-virtual-class-in-java/http://www.spjava.com/what-are-virtual-functionmethod-and-virtual-class-in-java/http://www.spjava.com/author/admin/http://www.spjava.com/author/admin/http://www.spjava.com/author/admin/http://www.spjava.com/category/articles/http://www.spjava.com/category/articles/http://www.spjava.com/category/articles/http://www.spjava.com/category/java/http://www.spjava.com/category/java/http://www.spjava.com/what-are-virtual-functionmethod-and-virtual-class-in-java/#respondhttp://www.spjava.com/what-are-virtual-functionmethod-and-virtual-class-in-java/#respondhttp://www.spjava.com/what-are-virtual-functionmethod-and-virtual-class-in-java/#respondhttp://www.spjava.com/what-are-virtual-functionmethod-and-virtual-class-in-java/#respondhttp://www.spjava.com/category/java/http://www.spjava.com/category/articles/http://www.spjava.com/author/admin/http://www.spjava.com/what-are-virtual-functionmethod-and-virtual-class-in-java/
  • 7/27/2019 OOP Job Interview Questions

    22/33

    }

    }

    public class Car extends Vehicle{

    public void fuel(){

    System.out.println(fuel Car);

    }

    }

    Here we are overriding fuel() method is virtual function/method in java.

    Virtual Class

    Abstract class is nothing but the pure virtual method equivalent in Java because all methods inabstract class are non private, non static and not final.

    What is a friend class?

    Question

    What is the difference between public, private, and protected keywords? Do I even need to use

    them?

    Answer

    We use these keywords to specify access levels for member variables, or for member functions

    (methods).

    Public variables, are variables that are visible to all classes.

    Private variables, are variables that are visible only to the class to which they belong.

    Protected variables, are variables that are visible only to the class to which they belong,

    and any subclasses.

    Deciding when to use private, protected, or public variables is sometimes tricky. You need to

    think whether or not an external object (or program), actually needs direct access to the

    information. If you do want other objects to access internal data, but wish to control it, youwould make it either private or protected, but provide functions which can manipulate the data in

    a controlled way.

    Take the following example :

  • 7/27/2019 OOP Job Interview Questions

    23/33

    public class bank_balance{

    public String owner;public int balance;

    public bank_balance( String name, int dollars ){

    owner = name;

    if (dollars >= 0)balance = dollars;

    elsedollars =0;

    }}

    We have declared our string and integer to be public. This means that any object in the system

    can change the balance (setting it to zero, or even giving us a negative balance). This could cause

    the program to fall over, even though we wrote code in our constructor to prevent negative

    balances.

    Instead, we should have provided a getBalance/setBalance method, and made our balance privateor proteced. Other objects can still access the data, but they can't put invalid data in.

    public class bank_balance{

    public String owner;private int balance;

    public bank_balance( String name, int dollars ){

    owner = name;

    if (dollars >= 0)balance = dollars;

    elsedollars =0;

    }

    public int getBalance(){

    return balance;}

    public void setBalance(int dollars)

    {if (dollars >= 0)

    balance = dollars;else

    dollars = 0;}

    }

    What is a Friend class ?

  • 7/27/2019 OOP Job Interview Questions

    24/33

    A friend class inC++, can access the "private" and "protected" members of the class in which itis declared as a friend. On declaration of friend class all member function of the friend class

    become friends of the class in which the friend class was declared. Friend status is not inherited;

    every friendship has to be explicitly declared. Friend classes can help in improvingEncapsulationif used wisely.

    Declaration

    Classes are declared as friends within the definition of the class who is giving access to others;this prevents a class from giving itself access to another's protected members, which enforces

    encapsulation. The friend class has the same level of access irrespective of whether the friend

    declaration appears in either the public, protected or private sections of the class definition.

    Friend status is granted by using the friend keyword:

    friend class ClassName;

    Example

    #include

    class B{

    // B declares A as a friend...friend class A;

    private:

    void privatePrint(){

    std::cout

  • 7/27/2019 OOP Job Interview Questions

    25/33

    Advantages of using friend class

    It provides additional functionality which is kept outside the class.

    It provides functions with data which is not normally used by the class.

    It provides a means of reducing algorithmic complexity by giving direct access to private and

    protected members to an external specified scope while not making the members more broadlyaccessible than necessary.

    Two classes accessing private data to each other

    Sometimes private data members are needed to be accessed and used by two different classes. In

    that case, friend class (orfriend function) can be used. Friend class can access all data members

    of both the classes, even private and protected data.

    For that purpose, each class should be declared as friend in the other class. They should not bemember of any one of the classes.

    Scope

    The class name which is introduced in the friend class declaration its scope is not in class

    granting friendship and also is not the member of the class granting access. If the name of the

    friend class is declared before the friend class declaration then the compiler searches for the classwith the same name as the friend class at the scope of friend declaration. If the name of the friend

    class is same as that of the enclosing class which is nested then the nested class is a friend of

    enclosing class.

    Exampleclass X{

    class Y{friend class Z;

    }}

    is equivalent to

    class Z;class X{

    class Y{friend class Z;

    };};

    Features

    Friendships are not corresponded If class A is a friend of class B, class B is not automatically a

    friend of class A.

    http://en.wikipedia.org/wiki/Friend_functionhttp://en.wikipedia.org/wiki/Friend_functionhttp://en.wikipedia.org/wiki/Friend_functionhttp://en.wikipedia.org/wiki/Friend_function
  • 7/27/2019 OOP Job Interview Questions

    26/33

    Friendships are not transitive If class A is a friend of class B, and class B is a friend of class C,

    class A is not automatically a friend of class C.

    Friendships are not inherited A friend of class Base is not automatically a friend of class

    Derived and vice versa; equally ifBase is a friend of another class, Derived is not

    automatically a friend and vice versa.

    Access due to friendship is inherited A friend ofDerived can access the restricted members

    ofDerived that were inherited from Base. Note though that a friend ofDerived only has

    access to members inherited from Base to which Derived has access itself, e.g. ifDerived

    inherits publicly from Base, Derived only has access to the protected (and public) members

    inherited from Base, not the private members, so neither does a friend.

    Friend and encapsulation

    It is said that friend classes violate encapsulation as it has an access to internals of the class in

    which it is declared. A friend allows a class a by hiding details that may be needed by anythingbut the friends of the class. It is also said that friend classes can also enhance encapsulation

    [1]as

    it allows library writers to write an interface which is not compromised in order to allow properinternal referencing.

    NOTES:

    Why Constructors cannot be final/static or abstract?

    Constructors aren't inherited so can't be overridden so whats the use to have final constructor??

    Constructor is called automatically when an instance of the class is created, it has access toinstance fields of the class. What will be the use of a static constructor??

    Constructor can't be overridden so what will you do with an abstract constructor??

    http://en.wikipedia.org/wiki/Friend_class#cite_note-1http://en.wikipedia.org/wiki/Friend_class#cite_note-1http://en.wikipedia.org/wiki/Friend_class#cite_note-1http://en.wikipedia.org/wiki/Friend_class#cite_note-1
  • 7/27/2019 OOP Job Interview Questions

    27/33

    There are two fundamental mechanisms for building new classes from existing ones:inheritance and aggregation---

    Inheritance: (IS-A)

    Wiki definition: inheritance is a way to form new classes (instances of which are calledobjects) using classes that have already been defined.

    Other definition: One class can use features from another class to extend its functionality(an Is a relationship) i.e., a Car is a Automobile.

    Inheritance is the inclusion of behaviour (i.e. methods) and state (i.e. variables) of a baseclass in a derivedclass so that they are accessible in that derived class. The key benefit of Inheritance is that

    it provides the formal mechanism for code reuse.

    The is a relationship is expressed with inheritance and has a relationship is expressedwith composition. Both inheritance and composition allow you to place sub-objects insideyour new class. Two of the main techniques for code reuse are class inheritance and objectcomposition.

    Inheritance is uni-directional. For example Car is a Vehicle. But Vehicle is not a Car.Inheritance uses extends key word. Composition: is used when Car has a Engine. It isincorrect to say Car is aEngine. Composition simply means using instance variables that refer to other objects. Theclass Car will have an instance variable, which refers to a Engine object.

    public class Vehicle{. . .}public class Car extends Vehicle{. . .}

    There are two types of inheritances:

    1. Implementation inheritance (aka class inheritance)2. Interface inheritance (aka type inheritance)

    Which one to use?

    Prefer interface inheritance to implementation inheritance because it promotes the design

  • 7/27/2019 OOP Job Interview Questions

    28/33

    concept of coding to an interface and reduces coupling. Interface inheritance can achievecode reuse with thehelp of object composition. If you look at Gang of Four (GoF) designpatterns, you can see that it favoursinterface inheritance to implementation inheritance.

    ASSOCIATION:(HAS-A)

    1. Composition2. Aggregation

    Composition:

    Composition is an association in which one class belongs to a collection. This is a part ofa whole relationship where a part CANNOT exist without a whole. If a whole is deleted then

    all parts are deleted.

    Wiki definition: object composition (not to be confused with function composition) is a wayto combine simple objects or data types into more complex ones.

    Other definition: Allowing a class to contain object instances in other classes so they can beused to perform actions related to the class (an has a relationship) i.e., a person has theability to walk.

    As we know, inheritance gives us an 'is-a' relationship. To make the understanding of

    composition easier, we can say that composition gives us a 'part-of' relationship.Composition is shown on a UML diagram as a filled diamond.

    If we were going to model a car, it would make sense to say that an engine is part-of a car.Within composition, the lifetime of the part (Engine) is managed by the whole (Car), in otherwords, when Car is destroyed, Engine is destroyed along with it.

    http://1.bp.blogspot.com/-Ix9XfiE69q8/T5aiNmGNQoI/AAAAAAAAFUM/3p3yhYcE1GU/s1600/composition.png
  • 7/27/2019 OOP Job Interview Questions

    29/33

    public classEngine

    {

    . . .}

    publicclassCar{

    Engine e = new Engine();.......

    }

    As you can see in the example code above, Car manages the lifetime of Engine.

    Which one to use?

    The guide is that inheritance should be only used when subclass is a superclass.

    Dont use inheritance just to get code reuse. If there is no is a relationship then usecomposition for code reuse. Overuse of implementation inheritance (uses theextends key word) can break all the subclasses, if the superclass is modified.

    Do not use inheritance just to get polymorphism. If there is no is a relationship andall you want is polymorphism then use interface inheritance with composition, whichgives you code reuse

    Aggregation:

    Aggregation is an association in which one class belongs to a collection. This is a part of awholerelationship where a part CAN exist without a whole.

    Just like composition, aggregation occurs when an object is composed of multiple objects.However, with composition, the internal objects (such as Tyre , Seat and Engine ) areowned by the main object ( Car ). If you destroy the Car , you also likely want the Tyre ,Seat and Engine instances destroyed because they are a composition which, together, forma single Car.

  • 7/27/2019 OOP Job Interview Questions

    30/33

    The Car instance certainly doesn't own the Driver and you probably shouldn't assume thatthe Driver is destroyed if the Car is destroyed. Further, the Driver exists independent of theCar . The Driver can leave this Car and sit in another one. This independence makes agreat deal of difference so this combination of objects is referred to as an aggregationinstead of composition. When designing your applications, it is important to note thatdifference

    publicclassCar{

    private Driver driver;

    public Car(Driver driver) // Constructor{

    this.driver = driver;}. . .

    }

    Car would then be used as follows:

    Driver driver = new Driver ();

    Car ford = new Car(driver);orCar ford = new Car(new Driver());

    Coupling is a back draw of Inheritance ?

    Inheritance causes strong coupling between classes this means that subclass depends upon

    parent class.

    http://2.bp.blogspot.com/-RsCyO-Gw2fM/T5aiVPCcq5I/AAAAAAAAFUU/Gk_Prq4NVq8/s1600/aggregation.png
  • 7/27/2019 OOP Job Interview Questions

    31/33

    For Example:

    Public class vehicle{

    Public void work(){System.out.println("Work of Animal");

    }

    }

    public class car extends vehicle{

    public void work(){

    System.out.println("Work of vehicle");

    }}

    subclass car overrides the function work(). If we change the signature of work() in vehicle,

    error occurs and program will not be compiled. As following

    Public class vehicle{

    Public int work(){ //void is replaced with int

    System.out.println("Work of Animal");

    Return 1;

    }}

    public class car extends vehicle{

    public void work(){ //program will not be compiled until we replace void with int. it is

    //coupling.

    System.out.println("Work of Animal");

    }

    }

  • 7/27/2019 OOP Job Interview Questions

    32/33

    When to prefer Inheritance?

    When there is a IS-A relationship and you have to use all the functions available in super class.

    When to prefer Aggregation over Inheritance?

    When you want to use some of the functions (part) of a class and there is Whole part

    relationship. It means that when the class A (whole) is using instance of class B (part), now ifclass A is destroyed, object of class B will not be destroyed.

    In the following example:

    public class Author {

    private String Name;

    private String email;

    private char gender;

    //-----------------------

    public Author(String name,String email,char gender){

    this.Name=name;

    this.email=email;

    this.gender=gender;

    }

    }

    public class Book {

    private String name;

    private Author author; // Aggregation, because we want to use authors information.

    private double price;

    private int qtyInStrock;

    //------------------------

    public Book(String name,Author auther,double price){

    this.name=name;

    this.author=author;

    this.price=price;

    }

  • 7/27/2019 OOP Job Interview Questions

    33/33

    public Book(String name,Author author,double price,int qtyInStock){

    this.name=name;

    this.author=author;

    this.price=price;

    this.qtyInStrock=qtyInStock;

    }

    }

    //--------------------------Main Code-------------------------

    public static void main(String[] args) {

    // Object of author is created at run time and not created in the class, so if object of

    //Book would be deleted the object of Author remains exist.

    Author anAuthor = new Author("Hamid","Java Practices",'M');

    Book aBook = new Book("Java for dummy", anAuthor, 19.95, 1000);

    // Use an anonymous instance of Author

    Book anotherBook = new Book("more Java for dummy", new Author("Hamid","Java Practices",'M'),

    29.95, 888);

    }