You are on page 1of 23

CORE JAVA ASSINGMENT 2

1. Define array. Explain two types arrays with syntax,


initialization & programs.
An array in Java is a group of like-typed variables referred to by a common
name. Arrays in Java work differently than they do in C/C++. Following are
some important points about Java arrays.
 In Java, all arrays are dynamically allocated. (discussed below)
 Arrays are stored in contagious memory [consecutive memory
locations].
 Since arrays are objects in Java, we can find their length using the
object property length. This is different from C/C++, where we find
length using sizeof.
 A Java array variable can also be declared like other variables with
[] after the data type.
 The variables in the array are ordered, and each has an index
beginning from 0.
 Java array can also be used as a static field, a local variable, or a
method parameter.
 The size of an array must be specified by int or short value and not
long.
 The direct superclass of an array type is Object.
 Every array type implements the interfaces Cloneable
and java.io.Serializable .
 This storage of arrays helps us in randomly accessing the elements
of an array [Support Random Access].
 The size of the array cannot be altered(once initialized). However,
an array reference can be made to point to another array.
An array can contain primitives (int, char, etc.) and object (or non-primitive)
references of a class depending on the definition of the array. In the case of
primitive data types, the actual values are stored in contiguous memory
locations. In the case of class objects, the actual objects are stored in a heap
segment.
One-Dimensional Arrays:
The general form of a one-dimensional array declaration is
type var-name[];
OR
type[] var-name;
An array declaration has two components: the type and the
name. type declares the element type of the array. The element type
determines the data type of each element that comprises the array. Like an
array of integers, we can also create an array of other primitive data types
like char, float, double, etc., or user-defined data types (objects of a class).
Thus, the element type for the array determines what type of data the array
will hold.
Example:
// both are valid declarations
int intArray[];
or int[] intArray;

byte byteArray[];
short shortsArray[];
boolean booleanArray[];
long longArray[];
float floatArray[];
double doubleArray[];
char charArray[];

// an array of references to objects of


// the class MyClass (a class created by
// user)
MyClass myClassArray[];

Object[] ao, // array of Object


Collection[] ca; // array of Collection
// of unknown type
Although the first declaration establishes that intArray is an array
variable, no actual array exists. It merely tells the compiler that this variable
(intArray) will hold an array of the integer type. To link intArray with an actual,
physical array of integers, you must allocate one using new and assign it to
intArray.

Multidimensional Arrays:

Multidimensional arrays are arrays of arrays with each element of the array
holding the reference of other arrays. These are also known as Jagged
Arrays. A multidimensional array is created by appending one set of square
brackets ([]) per dimension.
int[][] intArray = new int[10][20]; //a 2D array or matrix
int[][][] intArray = new int[10][20][10]; //a 3D array
Example
 Java

public class multiDimensional {


public static void main(String args[])
{
// declaring and initializing 2D array
int arr[][]
= { { 2, 7, 9 }, { 3, 6, 1 }, { 7, 4, 2 } };

// 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();
}
}
}

2. Define Inheritance. List and explain different types of


inheritance with diagrams.
3. Inheritance is a mechanism of driving a new class from an existing class. The
existing (old) class is known as base class or super class or parent class. The
new class is known as a derived class or sub class or child class. It allows us
to use the properties and behavior of one class (parent) in another class
(child).
4. A class whose properties are inherited is known as parent class and a class
that inherits the properties of the parent class is known as child class. Thus, it
establishes a relationship between parent and child class that is known as
parent-child or Is-a relationship.

5. Suppose, there are two classes named Father and Child and we want to
inherit the properties of the Father class in the Child class. We can achieve this
by using the extends keyword

6. //inherits the properties of the Father class


7. class Child extends Father
8. {
9. //functionality
10. }

Types of Inheritance
Java supports the following four types of inheritance:

o Single Inheritance
o Multi-level Inheritance
o Hierarchical Inheritance
o Hybrid Inheritance

Note: Multiple inheritance is not supported in Java.

Let's discuss each with proper example.

Single Inheritance
In single inheritance, a sub-class is derived from only one super class. It inherits the
properties and behavior of a single-parent class. Sometimes it is also known
as simple inheritance.
In the above figure, Employee is a parent class and Executive is a child class. The
Executive class inherits all the properties of the Employee class.

Let's implement the single inheritance mechanism in a Java program.

Executive.java

1. class Employee
2. {
3. float salary=34534*12;
4. }
5. public class Executive extends Employee
6. {
7. float bonus=3000*6;
8. public static void main(String args[])
9. {
10. Executive obj=new Executive();
11. System.out.println("Total salary credited: "+obj.salary);
12. System.out.println("Bonus of six months: "+obj.bonus);
13. }
14. }

Output:

Total salary credited: 414408.0


Bonus of six months: 18000.0

Multi-level Inheritance
In multi-level inheritance, a class is derived from a class which is also derived from
another class is called multi-level inheritance. In simple words, we can say that a class
that has more than one parent class is called multi-level inheritance. Note that the
classes must be at different levels. Hence, there exists a single base class and single
derived class but multiple intermediate base classes.

In the above figure, the class Marks inherits the members or methods of the class
Students. The class Sports inherits the members of the class Marks. Therefore, the
Student class is the parent class of the class Marks and the class Marks is the parent
of the class Sports. Hence, the class Sports implicitly inherits the properties of the
Student along with the class Marks.

Let's implement the multi-level inheritance mechanism in a Java program.

MultilevelInheritanceExample.java

1. //super class
2. class Student
3. {
4. int reg_no;
5. void getNo(int no)
6. {
7. reg_no=no;
8. }
9. void putNo()
10. {
11. System.out.println("registration number= "+reg_no);
12. }
13. }
14. //intermediate sub class
15. class Marks extends Student
16. {
17. float marks;
18. void getMarks(float m)
19. {
20. marks=m;
21. }
22. void putMarks()
23. {
24. System.out.println("marks= "+marks);
25. }
26. }
27. //derived class
28. class Sports extends Marks
29. {
30. float score;
31. void getScore(float scr)
32. {
33. score=scr;
34. }
35. void putScore()
36. {
37. System.out.println("score= "+score);
38. }
39. }
40. public class MultilevelInheritanceExample
41. {
42. public static void main(String args[])
43. {
44. Sports ob=new Sports();
45. ob.getNo(0987);
46. ob.putNo();
47. ob.getMarks(78);
48. ob.putMarks();
49. ob.getScore(68.7);
50. ob.putScore();
51. }
52. }

Output:

registration number= 0987


marks= 78.0
score= 68.7

Hierarchical Inheritance
If a number of classes are derived from a single base class, it is called hierarchical
inheritance.

In the above figure, the classes Science, Commerce, and Arts inherit a single parent
class named Student.

Let's implement the hierarchical inheritance mechanism in a Java program.

HierarchicalInheritanceExample.java

1. //parent class
2. class Student
3. {
4. public void methodStudent()
5. {
6. System.out.println("The method of the class Student invoked.");
7. }
8. }
9. class Science extends Student
10. {
11. public void methodScience()
12. {
13. System.out.println("The method of the class Science invoked.");
14. }
15. }
16. class Commerce extends Student
17. {
18. public void methodCommerce()
19. {
20. System.out.println("The method of the class Commerce invoked.");
21. }
22. }
23. class Arts extends Student
24. {
25. public void methodArts()
26. {
27. System.out.println("The method of the class Arts invoked.");
28. }
29. }
30. public class HierarchicalInheritanceExample
31. {
32. public static void main(String args[])
33. {
34. Science sci = new Science();
35. Commerce comm = new Commerce();
36. Arts art = new Arts();
37. //all the sub classes can access the method of super class
38. sci.methodStudent();
39. comm.methodStudent();
40. art.methodStudent();
41. }
42. }

Output:

The method of the class Student invoked.


The method of the class Student invoked.
The method of the class Student invoked.

Hybrid Inheritance
Hybrid means consist of more than one. Hybrid inheritance is the combination of two
or more types of inheritance.

In the above figure, GrandFather is a super class. The Father class inherits the
properties of the GrandFather class. Since Father and GrandFather represents single
inheritance. Further, the Father class is inherited by the Son and Daughter class. Thus,
the Father becomes the parent class for Son and Daughter. These classes represent
the hierarchical inheritance. Combinedly, it denotes the hybrid inheritance.

Let's implement the hybrid inheritance mechanism in a Java program.

Daughter.java

1. //parent class
2. class GrandFather
3. {
4. public void show()
5. {
6. System.out.println("I am grandfather.");
7. }
8. }
9. //inherits GrandFather properties
10. class Father extends GrandFather
11. {
12. public void show()
13. {
14. System.out.println("I am father.");
15. }
16. }
17. //inherits Father properties
18. class Son extends Father
19. {
20. public void show()
21. {
22. System.out.println("I am son.");
23. }
24. }
25. //inherits Father properties
26. public class Daughter extends Father
27. {
28. public void show()
29. {
30. System.out.println("I am a daughter.");
31. }
32. public static void main(String args[])
33. {
34. Daughter obj = new Daughter();
35. obj.show();
36. }
37. }

Output:

I am daughter.
Multiple Inheritance (not supported)
Java does not support multiple inheritances due to ambiguity. For example, consider
the following Java program.

Demo.java

1. class Wishes
2. {
3. void message()
4. {
5. System.out.println("Best of Luck!!");
6. }
7. }
8. class Birthday
9. {
10. void message()
11. {
12. System.out.println("Happy Birthday!!");
13. }
14. }
15. public class Demo extends Wishes, Birthday //considering a scenario
16. {
17. public static void main(String args[])
18. {
19. Demo obj=new Demo();
20. //can't decide which classes' message() method will be invoked
21. obj.message();
22. }
23. }

The above code gives error because the compiler cannot decide which message()
method is to be invoked. Due to this reason, Java does not support multiple
inheritances at the class level but can be achieved through an interface.

3. Explain use of this and super keyword with syntax and


programs.
In java, super keyword is used to access methods of the parent
class while this is used to access methods of the current class.
this keyword is a reserved keyword in java i.e, we can’t use it as an
identifier. It is used to refer current class’s instance as well as static
members. It can be used in various contexts as given below:
 to refer instance variable of current class
 to invoke or initiate current class constructor
 can be passed as an argument in the method call
 can be passed as argument in the constructor call
 can be used to return the current class instance
Example
 Java

// Program to illustrate this keyword


// is used to refer current class
class RR {
// instance variable
int a = 10;

// static variable
static int b = 20;

void GFG()
{
// referring current class(i.e, class RR)
// instance variable(i.e, a)
this.a = 100;

System.out.println(a);

// referring current class(i.e, class RR)


// static variable(i.e, b)
this.b = 600;

System.out.println(b);
}

public static void main(String[] args)


{
// Uncomment this and see here you get
// Compile Time Error since cannot use
// 'this' in static context.
// this.a = 700;
new RR().GFG();
}
}
Output
100
600
super keyword
1. super is a reserved keyword in java i.e, we can’t use it as an
identifier.
2. super is used to refer super-class’s instance as well as static
members.
3. super is also used to invoke super-class’s method or
constructor.
4. super keyword in java programming language refers to the
superclass of the class where the super keyword is currently being
used.
5. The most common use of super keyword is that it eliminates the
confusion between the superclasses and subclasses that have
methods with same name.
super can be used in various contexts as given below:
 it can be used to refer immediate parent class instance variable
 it can be used to refer immediate parent class method
 it can be used to refer immediate parent class constructor.
Example
 Java

// Program to illustrate super keyword


// refers super-class instance

class Parent {
// instance variable
int a = 10;

// static variable
static int b = 20;
}

class Base extends Parent {


void rr()
{
// referring parent class(i.e, class Parent)
// instance variable(i.e, a)
System.out.println(super.a);

// referring parent class(i.e, class Parent)


// static variable(i.e, b)
System.out.println(super.b);
}

public static void main(String[] args)


{
// Uncomment this and see here you get
// Compile Time Error since cannot use 'super'
// in static context.
// super.a = 700;
new Base().rr();
}
}

Output
10
20
Similarities in this and super
We can use this as well as super anywhere except static area.

Example of this is already shown above where we use this as well
as super inside public static void main(String[]args) hence we get
Compile Time Error since cannot use them inside static area.
 We can use this as well as super any number of times in a
program.
 Both are non-static keyword.
Example
 Java

// Java Program to illustrate using this


// many number of times

class RRR {
// instance variable
int a = 10;

// static variable
static int b = 20;

void GFG()
{
// referring current class(i.e, class RR)
// instance variable(i.e, a)
this.a = 100;

System.out.println(a);
// referring current class(i.e, class RR)
// static variable(i.e, b)
this.b = 600;

System.out.println(b);

// referring current class(i.e, class RR)


// instance variable(i.e, a) again
this.a = 9000;

System.out.println(a);
}

public static void main(String[] args)


{
new RRR().GFG();
}
}

100
600
9000

4. Define Interface . Explain how to create the interface with


programs.
An interface in Java is a blueprint of a class. It has static constants and abstract methods.

The interface in Java is a mechanism to achieve abstraction

. There can be only abstract methods in the Java interface, not method body. It is used to
achieve abstraction and multiple inheritance in Java
.

In other words, you can say that interfaces can have abstract methods and variables. It cannot
have a method body.

Java Interface also represents the IS-A relationship.

There are mainly three reasons to use interface. They are given below.

o It is used to achieve abstraction.


o By interface, we can support the functionality of multiple inheritance.
o It can be used to achieve loose coupling.
An interface is declared by using the interface keyword. It provides total abstraction; means
all the methods in an interface are declared with the empty body, and all the fields are public,
static and final by default. A class that implements an interface must implement all the
methods declared in the interface.

Syntax:

1. interface <interface_name>{
2.
3. // declare constant fields
4. // declare methods that abstract
5. // by default.
6. }

Java 8 Interface Improvement


Since Java 8

, interface can have default and static methods which is discussed later.

Internal addition by the compiler


The Java compiler adds public and abstract keywords before the interface
method. Moreover, it adds public, static and final keywords before data members.

In other words, Interface fields are public, static and final by default, and the methods are
public and abstract.
The relationship between classes and
interfaces
As shown in the figure given below, a class extends another class, an interface
extends another interface, but a class implements an interface.

5 . Program to implement multiple inheritance in java.


Multiple Inheritance is a feature of an object-oriented concept, where a class
can inherit properties of more than one parent class. The problem occurs
when there exist methods with the same signature in both the superclasses
and subclass. On calling the method, the compiler cannot determine which
class method to be called and even on calling which class method gets the
priority.
Note: Java doesn’t support Multiple Inheritance
Example 1:
 Java

// Java Program to Illustrate Unsupportance of


// Multiple Inheritance

// Importing input output classes


import java.io.*;

// Class 1
// First Parent class
class Parent1 {

// Method inside first parent class


void fun() {

// Print statement if this method is called


System.out.println("Parent1");
}
}

// Class 2
// Second Parent Class
class Parent2 {

// Method inside first parent class


void fun() {
// Print statement if this method is called
System.out.println("Parent2");
}
}

// Class 3
// Trying to be child of both the classes
class Test extends Parent1, Parent2 {

// Main driver method


public static void main(String args[]) {

// Creating object of class in main() method


Test t = new Test();

// Trying to call above functions of class where


// Error is thrown as this class is inheriting
// multiple classes
t.fun();
}
}

Output: Compilation error is thrown

Conclusion: As depicted from code above, on calling the method fun()


using Test object will cause complications such as whether to call Parent1’s
fun() or Parent2’s fun() method.

6 . Difference between
a) Abstract class and interface
 Abstract class and interface both are used to achieve abstraction where we
can declare the abstract methods. Abstract class and interface both can't be
instantiated.
 But there are many differences between abstract class and interface that are
given below.

Abstract class Interface


1) Abstract class can have abstract and Interface can have only abstract methods. Since
non-abstract methods. Java 8, it can have default and static
methods also.

2) Abstract class doesn't support multiple Interface supports multiple inheritance.


inheritance.

3) Abstract class can have final, non-final, Interface has only static and final variables.
static and non-static variables.

4) Abstract class can provide the Interface can't provide the implementation of
implementation of interface. abstract class.

5) The abstract keyword is used to declare The interface keyword is used to declare
abstract class. interface.

6) An abstract class can extend another An interface can extend another Java interface
Java class and implement multiple Java only.
interfaces.

7) An abstract class can be extended using An interface can be implemented using


keyword "extends". keyword "implements".

8) A Java abstract class can have class Members of a Java interface are public by
members like private, protected, etc. default.

9)Example: Example:
public abstract class Shape{ public interface Drawable{
public abstract void draw(); void draw();
} }

b) Class and interface


Class Interface

The keyword used to create a class is The keyword used to create an interface is
“class” “interface”

A class can be instantiated i.e, objects An Interface cannot be instantiated i.e,


of a class can be created. objects cannot be created.

Classes does not support multiple Interface supports multiple inheritance.


Class Interface

inheritance.

It can be inherit another class. It cannot inherit a class.

It can be inherited by a class by using the


keyword ‘implements’ and it can be
It can be inherited by another class inherited by an interface using the keyword
using the keyword ‘extends’. ‘extends’.

It can contain constructors. It cannot contain constructors.

It cannot contain abstract methods. It contains abstract methods only.

Variables and methods in a class can be


declared using any access
specifier(public, private, default, All variables and methods in a interface are
protected) declared as public.

Variables in a class can be static, final


or neither. All variables are static and final.

7 . Short note on abstract class and abstract method with


programs.
An abstract class in Java is one that is declared with the abstract keyword. It
may have both abstract and non-abstract methods(methods with bodies).
An abstract is a java modifier applicable for classes and methods in java
but not for Variables.
Illustration: Abstract class
abstract class Shape
{
int color;
// An abstract function
abstract void draw();
}
In java, the following some important observations about abstract classes
are as follows:
1.An instance of an abstract class can not be created.
2.Constructors are allowed.
3.We can have an abstract class without any abstract method.
4.There can be a final method in abstract class but any abstract
method in class(abstract class) can not be declared as final or in
simpler terms final method can not be abstract itself as it will yield
an error: “Illegal combination of modifiers: abstract and final”
5. We can define static methods in an abstract class
6. We can use the abstract keyword for declaring top-level classes
(Outer class) as well as inner classes as abstract
7. If a class contains at least one abstract method then compulsory
should declare a class as abstract
8. If the Child class is unable to provide implementation to all abstract
methods of the Parent class then we should declare that Child
class as abstract so that the next level Child class should provide
implementation to the remaining abstract method
Let us elaborate on these observations and do justify them with help of clean
java programs as follows.
Observation 1: In Java, just likely in C++ an instance of an abstract class
cannot be created, we can have references to abstract class type though. It
is as shown below via the clean java program.
Example
 Java

// Java Program to Illustrate


// that an instance of Abstract
// Class can not be created

// Class 1
// Abstract class
abstract class Base {
abstract void fun();
}

// Class 2
class Derived extends Base {
void fun()
{
System.out.println("Derived fun() called");
}
}

// Class 3
// Main class
class Main {
// Main driver method
public static void main(String args[])
{

// Uncommenting the following line will cause


// compiler error as the line tries to create an
// instance of abstract class. Base b = new Base();

// We can have references of Base type.


Base b = new Derived();
b.fun();
}
}

Output
Derived fun() called

You might also like