OOPS Concept

Question – What are the principle concepts of OOPS?

There are four principle concepts upon which object oriented design and programming rest.
They are:

  • 1. Abstraction
  • 2. Polymorphism
  • 3. Inheritance
  • 4. Encapsulation

(i.e. easily remembered as A-PIE).

Question – What is Encapsulation?

Encapsulation is the technique of making the fields in a class private and providing access to the fields 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 gives maintainability, flexibility and extensibility to our code.

Example:
Let us look at an example that depicts encapsulation:

/* File name : myJava.java */
public class myJava{
   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 myJava{

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

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

This would produce following result:

Name : Anand 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 data type of a field, and users of the class do not need to change any of their code.

Question – What is Abstraction?

Abstraction refers to the act of representing essential features without including the background details or explanations.
Abstraction is nothing but hiding the complex logic and give public access to that methods.
E.g – While connecting to data base we use data base connectivity jar like
1) mysql-connectivity.jar
2) oracal-connectivity.jar
We are least bother about the implementation logic. We are just using API’s to connect database.

Question – What is Inheritance?

Inheritance is the process by which objects of one class acquire the properties of objects of another class.

  • A class that is inherited is called a superclass.
  • The class that does the inheriting is called a subclass.
  • Inheritance is done by using the keyword extends.
  • The two most common reasons to use inheritance are:

a. To promote code reuse
b. To use polymorphism

Question – What is Polymorphism?

Polymorphism is briefly described as “one interface, many implementations.”
Polymorphism is a characteristic of being able to assign a different meaning or usage to something in different contexts – specifically,
to allow an entity such as a variable, a function, or an object to have more than one form.

Question – How does Java implement polymorphism?

(Inheritance, Overloading and Overriding are used to achieve Polymorphism in java).
Polymorphism manifests itself in Java in the form of multiple methods having the same name.In some cases,
multiple methods have the same name, but different formal argument lists (overloaded methods).
In other cases, multiple methods have the same name, same return type, and same formal argument list (overridden methods).

Question – What is an abstract class?

Abstract classes are classes that contain one or more abstract methods. An abstract method is a method that is declared, but contains no implementation.
Note:
If even a single method is abstract, the whole class must be declared abstract.
Abstract classes may not be instantiated, and require subclasses to provide implementations for the abstract methods.
You can’t mark a class as both abstract and final.

Question – Can we instantiate an abstract class?

An abstract class can never be instantiated. Its sole purpose is to be extended (subclassed).

Question – What is Constructor?

1. A constructor is a special method whose task is to initialize the object of its class.
2. It is special because its name is the same as the class name.
3. They do not have return types, not even void and therefore they cannot return values.
4. They cannot be inherited, though a derived class can call the base class constructor.
5. Constructor is invoked whenever an object of its associated class is created.

if you specify a parameterized constructor like ConstructorExample (int a) ,and want to use the default constructor ConstructorExample (),
it is mandatory for you to specify it.
In other words, in case your Constructor is overridden , and you want to use the default constructor , its need to be specified.

E.g.

package com.javainterviewquestion.in;
/**
 * @author info@javainterviewquestion.in
 * 
 */
public class ConstructorExample {
	int jiq1;
	int jiq2;

	/*ConstructorExample() {
		jiq1 = 10;
		jiq2 = 20;
		System.out.println("Inside 1st Constructor");
	}*/
	ConstructorExample(int a) {
		jiq1 = a;
		System.out.println("Inside 2nd Constructor");
	}
	ConstructorExample(int a, int b) {
		jiq1 = a;
		jiq2 = b;
		System.out.println("Inside 3rd Constructor");
	}
	public void display() {
		System.out.println("Print jiq1 === " + jiq1);
		System.out.println("Print jiq2 === " + jiq2);
	}
	public static void main(String[] args) {
		
		ConstructorExample consExObj1 = new ConstructorExample();

		ConstructorExample consExObj2 = new ConstructorExample(30);
		ConstructorExample consExObj3 = new ConstructorExample(30, 40);

		consExObj1.display();
		consExObj2.display();
		consExObj3.display();
	}// Close main method
}// Close class

OutPut –
Error = ?. Try and debug the error before proceeding to next step.
Solution – Un-comment line # 10-14. Save , Compile & Run the code.

Question – How does the Java default constructor be provided?

If a class defined by the code does not have any constructor, compiler will automatically provide one no-parameter-constructor (default-constructor) for the class in the byte code.
The access modifier (public/private/etc.) of the default constructor is the same as the class itself.
If no user defined constructor is provided for a class, compiler initializes member variables to its default values.

numeric data types are set to 0
char data types are set to null character(‘’)
reference variables are set to null

E.g. Compiler provide defined constructor if no default constructor available

package com.javainterviewquestion.in;
/**
 * @author info@javainterviewquestion.in
 */
public class ConstructorExample {
	
	int jiq1;
	char jiq2;
	String jiq3;
	
	public void display() {
		System.out.println("Print int jiq1 --> " + jiq1);
		System.out.println("Print char jiq2 --> " + jiq2);
		System.out.println("Print String jiq3 --> " + jiq3);
	}
	
	public static void main(String[] args) {
		ConstructorExample consExObj1 = new ConstructorExample();
		consExObj1.display();
	}// Close main method
	
}// Close class

OutPut –

Print int jiq1 –> 0
Print char jiq2 –>
Print String jiq3 –> null

Question – Can constructor be inherited?

No, constructor cannot be inherited, though a derived class can call the base class constructor.

Question – What restrictions are placed on method overloading?

Overloading deals with multiple methods in the same class with the same name but different signatures Overloading lets you define a similar operation in different ways for different data

Question – Give me example of method overloading in java ?

In Java it is possible to define two or more methods within the same class that share the same name, as long as their parameter declarations are different.
When this is the case, the methods are said to be overloaded, and the process is referred to as method overloading.
Method overloading is one of the ways that Java implements polymorphism.
OverloadDemo.java

package com.javainterviewquestion.Overloading;

public class OverloadDemo {

	void test() {
		System.out.println("No parameters");
	}
	// Overload test for one integer parameter.
	void test(int a) {
		System.out.println("a: " + a);
	}
	// Overload test for two integer parameters.
	void test(int a, int b) {
		System.out.println("a and b: " + a + " " + b);
	}
	// overload test for a double parameter
	double test(double a) {
		System.out.println("double a: " + a);
		return a * a;
	}

}// close OverloadDemo class

OverloadMainClass.java

package com.javainterviewquestion.Overloading;

public class OverloadMainClass {

	public static void main(String args[]) {

		OverloadDemo ob = new OverloadDemo();
		double result;
		// call all versions of test()
		ob.test();
		ob.test(10);
		ob.test(10, 20);
		result = ob.test(123.2);
		System.out.println("Result of ob.test(123.2): " + result);
	}// close main method

}// close main class

This program generates the following output:
No parameters
a: 10
a and b: 10 20
double a: 123.2
Result of ob.test(123.2): 15178.24

Question – Define overriding. Explain it with an example ?

In a class hierarchy, when a method in a subclass has the same name and type signature as a method in its superclass,
then the method in the subclass is said to override the method in the superclass. When an overridden method is called from within a subclass,
it will always refer to the version of that method defined by the subclass. The version of the method defined by the superclass will be hidden.
SuperClassA.java

package com.javainterviewquestion.Overriding;

public class SuperClassA {
	int i, j;

	SuperClassA(int a, int b) {
		i = a;
		j = b;
	}

	// display i and j
	void show() {
		System.out.println("i and j: " + i + " " + j);
	}
}

SuperClassB.java

package com.javainterviewquestion.Overriding;

public class SuperClassB extends SuperClassA {
	int k;

	SuperClassB(int a, int b, int c) {
		super(a, b);
		k = c;
	}
	// display k - this overrides show() in A
	void show() {
		System.out.println("k: " + k);
	}
}

OverrideMainClass.java

package com.javainterviewquestion.Overriding;

public class OverrideMainClass {

	public static void main(String args[]) {
		SuperClassB superClassBObj = new SuperClassB(1, 2, 3);
		superClassBObj.show(); // this calls show() in SuperClassB
	}
}

The output produced by this program is shown here:
k: 3

Consider one more following example :
Animal.java

package com.javainterviewquestion.Overriding;
class Animal{

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

Dog.java

package com.javainterviewquestion.Overriding;
class Dog extends Animal{

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

TestDog.java

package com.javainterviewquestion.Overriding;
public class TestDog{

   public static void main(String args[]){
      Animal a = new Animal(); // Animal reference and object
      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
      b.bark();
   }
}

This would produce following result:
TestDog.java:30: cannot find symbol
symbol : method bark()
location: class Animal
b.bark();
^

This program will throw a compile time error since b’s reference type Animal doesn’t have a method 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 the sub class cannot be either private or public.
    However the access level can be less restrictive than the overridden method’s access level.
  • 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 public or protected.
  • An overriding method can throw any uncheck exceptions, regardless of whether the overridden method throws exceptions or not.
    However the overriding method should not throw 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.

Question – How do you know that your classes are badly designed?

  • If your application is fragile – when making a change, unexpected parts of the application can break.
  • If your application is rigid – it is hard to change one part of the application without affecting too many other parts.
  • If your application is immobile – it is hard to reuse the code in another application because it cannot be separated.

Overly complex design is as bad as no design at all. Get the granularity of your classes and objects right without overly complicating them.
Don’t apply too many patterns and principles to a simple problem. Apply them only when they are adequate.
Don’t anticipate changes in requirements ahead of time. Preparing for future changes can easily lead to overly complex designs.
Focus on writing code that is not only easy to understand, but also flexible enough so that it is easy to change if the requirements change.

Question – How to Improve Performance of java application?

This is a big topic to discuss as there are many approaches which involves to analyze peformance of an application starting from profiling application to finding bottleneck.
here I am putting some of the basic tricks for improving performance which I learnt in my early days in java , I will keep posted some approach , experience on performance improvement as and when time allows.

for now here are naive’s tips for making your program run faster.

1. Use bit shift operator for multiplying and divide by 2 , computers are very fast with bitwise operation.
2. Use stringbuffer in place of string if you are doing lots of string manipulation it will reduce memory by avoiding creating lots of string garbage.
If you are using java5 then consider stringbuilder but that is not synchronized so beware.
3. try to make variable , class , method final whenever possible that’s allow compiler to do lots of optimization
e.g. compile time binding so you will get faster output.
4. static methods are binded compile time while non static methods are resolved at runtime based on object
type so static method will be faster than non static.
5. don’t call methods in for loop for checking condition e.g. length() size() etc.
instead of doing this , use modified version

for(int i=0; i

One Response

Leave a Reply