Core Java Questions And Answers -Part-7

What happens, if sub class extending abstract class doesn’t override abstract methods?
–> Compiler throws error to implement all abstract methods
–> Compiler-time error: The type AbstractExampleMain must implement the inherited abstract method AbstractExample.myAbstractMethod()







What all options available for sub class extending abstract class to not to override abstract methods?
–> There are 2 options; either implements all abstract methods or make extending class as abstract
–> This way, next extending class must provide implementation or else again it can be marked as abstract
–> Options:
Add unimplemented methods
Make type ‘ExtendingClass’ abstract


Can we define constructor inside abstract class?
–> Yes, we can define constructor inside abstract class
–> Both default & parametrized constructors are allowed inside abstract class


Why abstract classes cannot be instantiated, if constructor can be defined inside abstract class?
–> True, an abstract class cannot be instantiated; still having instance data members and constructor
–> This is to instruct compiler that no one should create an object of type abstract class
–> The reason is, every object has got some default behavior and specific behavior. In this case, abstract class is apt
–> So, we can put more common & general behavior with concrete method implementation and later extending (sub-classing) class can provide specific implementation for abstract methods in their own way


What are all modifiers allowed for abstract method declaration?
–> pubic and protected access modifiers are allowed for abstract method declaration


What are all modifiers allowed for abstract class declaration?
–> private, static and final modifiers are NOT allowed for abstract method declaration


Can we define private constructor inside abstract class?
–> Yes, it is allowed to have private constructor inside abstract class


Is it ok to declare abstract method inside non-abstract class?
–> No, it is not allowed to have abstract method inside concrete class
–> If there any abstract method, then class must be marked with abstract modifier


Can we declare static fields inside abstract class?
–> Yes, static fields and static methods are allowed to declare inside abstract class.

Can we define static methods giving concrete implementation inside abstract class?
–> Yes, static methods are allowed inside abstract class.


Key points about Java Abstract Class,
An abstract class must have an abstract method.
Abstract classes can have Constructors, Member variables and Normal methods.
Abstract classes are never instantiated.
When you extend Abstract class with abstract method, you must define the abstract method in the child class, or make the child class abstract.


Key points about Java Interface,
By default, variables defined inside Java Interface are “public static final” –> means constants
Rules for using Interface

Methods inside Interface must not be static, final, native or strictfp.
All variables declared inside interface are implicitly public static final variables(constants).
All methods declared inside Java Interfaces are implicitly public and abstract, even if you don't use public or abstract keyword.
Interface can extend one or more other interface.
Interface cannot implement a class.
Interface can be nested inside another interface.

Do Interfaces supports Multiple Inheritance?
Though classes in java doesn't suppost multiple inheritance, but a class can implement more than one interface.

interface Moveable
{
 boolean isMoveable();
}

interface Rollable
{
 boolean isRollable
}

class Tyre implements Moveable, Rollable
{
 int width;

 boolean isMoveable()
 {
  return true;
 }

 boolean isRollable()
 {
  return true;
 }
 public static void main(String args[])
 {
  Tyre tr=new Tyre();
  System.out.println(tr.isMoveable());
  System.out.println(tr.isRollable());
 }
}
Output :

true
true


What is Aggregation in java?
Aggregation (HAS-A)
HAS-A relationship is based on usage, rather than inheritance. In other words, class A has-a relationship with class B, if code in class A has a reference to an instance of class B.

Example

class Student
{
 String name;
 Address ad;
}
Here you can say that Student has-a Address.

Student class has an instance variable of type Address. Student code can use Address reference to invoke methods on the Address, and get Address behavior.

Aggregation allow you to design classes that follow good Object Oriented practices. It also provide code reusability.

Example of Aggregation

class Author
{
 String authorName;
 int age;
 String place;
 Author(String name,int age,String place)
 {
  this.authorName=name;
  this.age=age;
  this.place=place;
 }
 public String getAuthorName()
 {
  return authorName;
 }
 public int getAge()
 {
  return age;
 }
 public String getPlace()
 {
  return place;
 }
}

class Book
{
 String name;
 int price;
 Author auth;
 Book(String n,int p,Author at)
 {
  this.name=n;
  this.price=p;
  this.auth=at;
 }
 public void showDetail()
 {
  System.out.println("Book is"+name);
  System.out.println("price "+price);
  System.out.println("Author is "+auth.getAuthorName());
 }
}

class Test
{
 public static void main(String args[])
 {
  Author ath=new Author("Me",22,"India");
  Book b=new Book("Java",550,ath);
  b.showDetail();
 }
}


Output :
Book is Java.
price is 550.
Author is me.


What is Composition in java?
Composition is restricted form of Aggregation. For example a class Car cannot exist without Engine.

class Car
{
 private Engine engine;
 Car(Engine en)
 {
  engine = en;
 }
}


When to use Inheritance and Aggregation?
When you need to use property and behaviour of a class without modifying it inside your class. In such case Aggregation is a better option. Whereas when you need to use and modify property and behaviour of a class inside your class, its best to use Inheritance.


instanceof operator
In Java, instanceof operator is used to check the type of an object at runtime. It is the means by which your program can obtain run-time type information about an object. instanceof operator is also important in case of casting object at runtime. instanceof operator return boolean value, if an object reference is of specified type then it return true otherwise false.

Example of instanceOf

public class Test
{
    public static void main(String[] args)
    {
      Test t= new Test();
      System.out.println(t instanceof Test);
      }
}
Output : true


What is Encapsulation in Java?
Encapsulation is a practice to bind related functionality (Methods) & Data (Variables) in a protective wrapper (Class) with required access modifiers (public, private, default & protected) so that the code can be saved from unauthorized access by outer world and can be made easy to maintain.

We can achieve complete encapsulation in java by making members of a class private and access them outside the class only through getters and setters. Although a lesser degree of encapsulation can be achieved by making the members public or protected. Encapsulation makes it possible to maintain code that is frequently changeable by took that in one place and not scatter everywhere.

So, we can conclude our discussion saying that, Encapsulation is reflected with a well defined class having all related data and behavior in a single place and than access/restrict it using appropriate access modifiers.


What is the difference between Abstraction and Encapsulation?
Abstraction is a technique for managing complexity by separating interface or interaction details away from lower-level implementation details.
Consider, as one simplistic example, making a phone call. Most commonly today, you probably use the touchscreen of your smartphone to select a contact and place a call. You don't care about the phone number, position of cell towers, code on your phone's operating system, etc. Go back in time a bit and you dialed the number using a keypad or actual pulse dial. Still, you didn't care about the underlying poles and cables, telephony circuitry, voltage levels or hardware making this possible. Go back even farther and you rang an operator to physically connect a circuit for you.

As someone who wants to make a call, you simply know who you want to call - you don't need to think about how to actually manipulate the technologies making telephony possible. Effectively, the interaction of making  a phone call is abstracted for you, away from the implementation details which actually make the action possible.

Encapsulation, on the other hand, as it relates to computer science, deals with one (or both) of two different things:
Restricting access to certain components of some object.
Somehow combining/bundling/coupling data with the functions that operate on that data.


What is JAR and WAR and EAR file?

a) JAR File (Java ARchive)
JAR file is like winzip file compressed with JDK software. The problem of popular winzip file is it should be unzipped on Windows OS only. winzip is platform-dependent. A winzip file cannot be opened or unzipped from Linux. For that matter, all zipping algorithms are platform-dependent. The interesting point with JAR file is it can be zipped and unzipped by JVM irrespective of OS. That is, wherever Java is working, the JAR file can be created or unzipped. It can be said, JAR is platform-independent way of creating a zip file.

A JAR file extension is .jar and is created with jar command from command prompt (like javac command is executed). Generally, a JAR file contains Java related resources like libraries, classes etc.; but need not be. It can contain any non-sense (non-related) files like .txt, .doc, .gif etc., just like a winzip can contain.
All the options of JAR command, security aspects, creating JAR file with unzipping are discussed with examples at JAR (Java ARchive) Files.

b) WAR File (Web Application ARchive)
A WAR file is simply a JAR file but contains only Web related Java files (but not Web unrelated files) like Servlets, JSP, HTML, Database Java Beans, web.xml file, Property bundles, JavaScript, shopping carts etc. necessary to develop Web applications. The advantage of WAR file is it can be deployed easily on client machine in a Web server environment. The extension of WAR file is .war but ofcourse created with JAR command only.
To execute a WAR file, a Web server or Web container is required, for example, Tomcat or Weblogic or Websphere. To execute a JAR file, simple JDK is enough.
The IDE tools like Eclipse, JBOSS etc. maintain a directory hierarchy structure for WAR files like WEB-INF folder etc.

c) EAR File (Enterprise Application ARchive)
EAR file contains Enterprise application related files (J2EE) like XML, EJB modules etc. Ir is also created with JAR command only but with extension .ear. EAR file is deployed in an application server.


Advantages JAR, EAR and EAR files
With JAR, EAR and EAR files, the deployment of software is easy on client machines. At a stretch all the related files of an application are installed. For example, Oracle comes with JAR files for distributing Oracle database on CDs etc. IBM uses JAR for installation and documentation for WebSphere.
Easy development and testing



What is a Wrapper class in Java?
Wrapper classes allows us to convert the primitive types into an object type.
java is not 100% object oriented programming language because of the 8 primitive types. Then wrapper classes are introduced to give the primitive types an object form. So the primitive types can also be stored as an object of its respective wrapper class

The 8 primitive types and its wrapper classes are,
byte.         - Byte
int             - Integer
short        - Short
long          - Long
float         - Float
double     - Double
char          - Character
boolean   - Boolean

all this wrapper classes are available in java.lang package
Now if you want to store an integer as an object type you can write it as
Integer i=new Integer(10);
This is known as Boxing, converting a primitive type into an object.
Now to get that integer value back,
int a=i.intValue();
This operation is known as Unboxing converting the value of a wrapper class object into a primitive type.
After java 1.5/5 Boxing and Unboxing became automatic. You can directly assign the primitive as an object of wrapper class.


What is Object Cloning?
The object cloning is a way to create exact copy of an object. For this purpose, clone() method of Object class is used to clone an object.
The java.lang.Cloneable interface must be implemented by the class whose object clone we want to create. If we don't implement Cloneable interface, clone() method generates CloneNotSupportedException.
The clone() method is defined in the Object class. Syntax of the clone() method is as follows:

Why use clone() method ?
The clone() method saves the extra processing task for creating the exact copy of an object. If we perform it by using the new keyword, it will take a lot of processing to be performed that is why we use object cloning.

Advantage of Object cloning
Less processing task.

Example of clone() method (Object cloning)
Let's see the simple example of object cloning

class Student18 implements Cloneable{ 
int rollno; 
String name; 
 
Student18(int rollno,String name){ 
this.rollno=rollno; 
this.name=name; 
 
public Object clone()throws CloneNotSupportedException{ 
return super.clone(); 
 
public static void main(String args[]){ 
try{ 
Student18 s1=new Student18(101,"amit"); 
 
Student18 s2=(Student18)s1.clone(); 
 
System.out.println(s1.rollno+" "+s1.name); 
System.out.println(s2.rollno+" "+s2.name); 
 
}catch(CloneNotSupportedException c){}  
 

Output:101 amit
       101 amit
        

As you can see in the above example, both reference variables have the same value. Thus, the clone() copies the values of an object to another. So we don't need to write explicit code to copy the value of an object to another.

If we create another object by new keyword and assign the values of another object to this one, it will require a lot of processing on this object. So to save the extra processing task we use clone() method.

Arrays:
Java array is an object the contains elements of similar data type. It is a data structure where we store similar elements. We can store only fixed set of elements in a java array.
Array in java is index based, first element of the array is stored at 0 index.

Advantage of Java Array
Code Optimization: It makes the code optimized, we can retrieve or sort the data easily.
Random access: We can get any data located at any index position.

Disadvantage of Java Array
Size Limit: We can store only fixed size of elements in the array. It doesn't grow its size at runtime. To solve this problem, collection framework is used in java.

Example of single dimensional java array
Let's see the simple example of java array, where we are going to declare, instantiate, initialize and traverse an array.

class Testarray{ 
public static void main(String args[]){ 
 
int a[]=new int[5];//declaration and instantiation 
a[0]=10;//initialization 
a[1]=20; 
a[2]=70; 
a[3]=40; 
a[4]=50; 
 
//printing array 
for(int i=0;i<a.length;i++)//length is the property of array 
System.out.println(a[i]); 
 
}} 

Output: 10
       20
       70
       40
       50
     


Multidimensional array in java
In such case, data is stored in row and column based index (also known as matrix form).

Example of Multidimensional java array
Let's see the simple example to declare, instantiate, initialize and print the 2Dimensional array.

class Testarray3{ 
public static void main(String args[]){ 
 
//declaring and initializing 2D array 
int arr[][]={{1,2,3},{2,4,5},{4,4,5}}; 
 
//printing 2D array 
for(int i=0;i<3;i++){ 
 for(int j=0;j<3;j++){ 
   System.out.print(arr[i][j]+" "); 
 } 
 System.out.println(); 
 
}} 



Call by Value and Call by Reference in Java
There is only call by value in java, not call by reference. If we call a method passing a value, it is known as call by value. The changes being done in the called method, is not affected in the calling method.

Example of call by value in java
In case of call by value original value is not changed. Let's take a simple example:
class Operation{ 
 int data=50; 
 
 void change(int data){ 
 data=data+100;//changes will be in the local variable only 
 } 
    
 public static void main(String args[]){ 
   Operation op=new Operation(); 
 
   System.out.println("before change "+op.data); 
   op.change(500); 
   System.out.println("after change "+op.data); 
 
 } 

Output:
before change 50
after change 50  


Java Strictfp Keyword:

Java strictfp keyword ensures that you will get the same result on every platform if you perform operations in the floating-point variable. 

No comments:

Post a Comment