java
java
Topic: Arrays
Topic: Inheritance
Topic: Interfaces
16. Write short notes on super keyword and abstract classes. [7M]Jan2023
17. Describe the importance of super keyword in java programming.
[7M]Jan2023
//Initialize array
int [] arr = new int [] {25, 11, 7, 75, 56,66,55,35};
//Initialize max with first element of array.
int max = arr[0];
//Loop through the array
for (int i = 0; i < arr.length; i++) {
//Compare elements of array with max
if(arr[i] > max)
max = arr[i];
}
System.out.println("Largest element present in given array: " + max);
}
}
Output:
Array holds multiple values, whereas an Normal variable hold a single value. it is
true when the elements of the array are treated as individual entities, and when the
variable is a simple scalar variable such as an int.
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.
So, when you first create a variable, you are declaring it but not necessarily
initializing it yet.
Above, we declared an array using int[] age and initialized it by assigning the
values {25, 50, 23, 21}.
Example.
System.out.println(cars[0]);
// Outputs Volvo
In this program, we need to sort the given array in descending order such that
elements will be arranged from largest to smallest. This can be achieved through two
loops. The outer loop will select an element, and inner loop allows us to compare
selected element with rest of the elements.
Original Array
52871
Araay after Sorting
87521
Elements will be sorted in such a way that largest element will appear on extreme left
which in this case is 8. The smallest element will appear on extreme right which in
this case is 1.
System.out.println();
//Displaying elements of array after sorting
System.out.println("Elements of array sorted in descending order: ");
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
}
}
Output:
import java.util.Scanner;
public class MatrixMultiplicationExample {
Advantages of arrays :
Efficient access to elements: Arrays provide direct and efficient access to any
element in the collection. Accessing an element in an array is an O(1)
operation, meaning that the time required to access an element is constant and
does not depend on the size of the array.
Fast data retrieval: Arrays allow for fast data retrieval because the data is
stored in contiguous memory locations. This means that the data can be
accessed quickly and efficiently without the need for complex data structures
or algorithms.
Memory efficiency: Arrays are a memory-efficient way of storing data.
Because the elements of an array are stored in contiguous memory locations,
the size of the array is known at compile time. This means that memory can be
allocated for the entire array in one block, reducing memory fragmentation.
Versatility: Arrays can be used to store a wide range of data types, including
integers, floating-point numbers, characters, and even complex data structures
such as objects and pointers.
Easy to implement: Arrays are easy to implement and understand, making
them an ideal choice for beginners learning computer programming.
Compatibility with hardware: The array data structure is compatible with
most hardware architectures, making it a versatile tool for programming in a
wide range of environments.
Write a java program to find the minimum and maximum value present in an
array.
import java.util.*;
class ArrMinMax {
public static void main() {
Scanner inp = new Scanner(System.in);
System.out.print("\n Enter Size of Array: ");
int n = inp.nextInt();
int i, sum = 0;
int arr[] = new int[n]; //Creating N-size Array
for (i = 0; i < n; i++) { //Entering N numbers in array
System.out.print("\n Enter: ");
arr[i] = inp.nextInt();
}
int max_element = arr[0], min_element = arr[0]; //Initializing with first
element.
//Printing Result
System.out.println("\n Maximum Number: " + max_element);
System.out.println("\n Minimum Number: " + min_element);
}
6. Illustrate usage of arrays two–dimensional and three - dimensional with an
example program.
Usage of Arrays.
Easy to use: Arrays are easy to use and require less coding than traditional
data structures. This makes arrays a great choice for rapid development.
High performance: Arrays provide fast and efficient access to elements as
compared to other data structures such as linked lists, trees etc.
Flexible size: The size of arrays can be changed easily at runtime, making
them a very flexible type of data structure.
Memory efficient: Arrays are memory efficient as they can store multiple
values in the same location. This reduces the amount of RAM required to
store data and improves overall performance.
Random Access: Arrays support random access, meaning elements can be
accessed directly using their index. This makes arrays an ideal choice for
applications requiring fast data access.
Two dimensional Array in java:-
A Two Dimensional Array in Java is a collection of 1D Array. It consists of rows
and columns and looks like a table. A 2D array is also known as Matrix.
Example:-
int a[][]=new int[3][3];
import java.util.Scanner;
Multiple inheritance in java is the capability of creating a single class with multiple
super classes. Unlike some other popular object oriented programming languages
like C++, java doesn’t provide support for multiple inheritance in classes. Java
doesn’t support multiple inheritances in classes because it can lead to diamond
problem and rather than providing some complex way to solve it, there are better
ways through which we can achieve the same result as multiple inheritances.
“A class can extend only one class but it can implement multiple interfaces.”
For example, below inheritance using multiple classes is wrong as two classes
cannot be extended or inherited. Class C is inheriting class A and B.
Facilitating code reuse – Inheritance in Java programming allows for the reuse of
code, which can save time and effort when developing software.
Enhancing code modularity – By dividing code into parent and child classes,
inheritance can help to create more modular and organized code.
Promoting code flexibility – Inheritance can make code more flexible by allowing
developers to create new classes that inherit the characteristics of existing classes,
while also adding their own unique features.
class Shape {
public void display() {
System.out.println("Inside display");
}
}
class Rectangle extends Shape {
public void area() {
System.out.println("Inside area");
}
}
public class Tester {
public static void main(String[] arguments) {
Rectangle rect = new Rectangle();
rect.display();
rect.area();
}
}
Output:-
Inside display
Inside area
9.10.11. List out and explain the advantages of Inheritance. Discuss the types
of Inheritance supported by Java and explain the significance of ‘Super’
keyword.
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.
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
Types of Inheritance
o Single Inheritance
o Multi-level Inheritance
o Hierarchical Inheritance
o Hybrid Inheritance
Single Inheritance
o
o 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.
Example:-
class Employee
{
float salary=34534*12;
}
public class Executive extends Employee
{
float bonus=3000*6;
public static void main(String args[])
{
Executive obj=new Executive();
System.out.println("Total salary credited: "+obj.salary);
System.out.println("Bonus of six months: "+obj.bonus);
}
}
Output:-
Output:
Multi-level Inheritance
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.
MultilevelInheritanceExample.java
//super class
class Student
{
int reg_no;
void getNo(int no)
{
reg_no=no;
}
void putNo()
{
System.out.println("registration number= "+reg_no);
}
}
//intermediate sub class
class Marks extends Student
{
float marks;
void getMarks(float m)
{
marks=m;
}
void putMarks()
{
System.out.println("marks= "+marks);
}
}
//derived class
class Sports extends Marks
{
float score;
void getScore(float scr)
{
score=scr;
}
void putScore()
{
System.out.println("score= "+score);
}
}
public class MultilevelInheritanceExample
{
public static void main(String args[])
{
Sports ob=new Sports();
ob.getNo(0987);
ob.putNo();
ob.getMarks(78);
ob.putMarks();
ob.getScore(68.7);
ob.putScore();
}
}
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.
class Student
{
public void methodStudent()
{
System.out.println("The method of the class Student invoked.");
}
}
class Science extends Student
{
public void methodScience()
{
System.out.println("The method of the class Science invoked.");
}
}
class Commerce extends Student
{
public void methodCommerce()
{
System.out.println("The method of the class Commerce invoked.");
}
}
class Arts extends Student
{
public void methodArts()
{
System.out.println("The method of the class Arts invoked.");
}
}
public class HierarchicalInheritanceExample
{
public static void main(String args[])
{
Science sci = new Science();
Commerce comm = new Commerce();
Arts art = new Arts();
//all the sub classes can access the method of super class
sci.methodStudent();
comm.methodStudent();
art.methodStudent();
}
}
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.
Example:-
//parent class
class GrandFather
{
public void show()
{
System.out.println("I am grandfather.");
}
}
//inherits GrandFather properties
class Father extends GrandFather
{
public void show()
{
System.out.println("I am father.");
}
}
//inherits Father properties
class Son extends Father
{
public void show()
{
System.out.println("I am son.");
}
}
//inherits Father properties
public class Daughter extends Father
{
public void show()
{
System.out.println("I am a daughter.");
}
public static void main(String args[])
{
Daughter obj = new Daughter();
obj.show();
}
}
Output:
I am daughter.
Multiple Inheritance (not supported)
Java does not support multiple inheritances due to ambiguity. For example,
consider the following Java program.
class Wishes
{
void message()
{
System.out.println("Best of Luck!!");
}
}
class Birthday
{
void message()
{
System.out.println("Happy Birthday!!");
}
}
public class Demo extends Wishes, Birthday //considering a scenario
{
public static void main(String args[])
{
Demo obj=new Demo();
//can't decide which classes' message() method will be invoked
obj.message();
}
}
Super key word:-
Super Keyword in Java
The super keyword in Java is a reference variable which is used to refer immediate
parent class object.
Whenever you create the instance of subclass, an instance of parent class is created
implicitly which is referred by super reference variable.
Exmaple:-
class Animal{
String color="white";
}
class Dog extends Animal{
String color="black";
void printColor(){
System.out.println(color);//prints color of Dog class
System.out.println(super.color);//prints color of Animal class
}
}
class TestSuper1{
public static void main(String args[]){
Dog d=new Dog();
d.printColor();
}}
In other words, you can say that interfaces can have abstract methods and
variables.
Interfaces specify what a class must do and not how. It is the blueprint of the
behaviour.
Interface do not have constructor.
Represent behaviour as interface unless every sub-type of the class is
guarantee to have that behaviour.
An Interface is about capabilities like a Player may be an interface and any
class implementing Player must be able to (or must implement) move(). So it
specifies a set of methods that the class has to implement.
If a class implements an interface and does not provide method bodies for all
functions specified in the interface, then the class must be declared abstract.
Purpose of the interface
Provides communication − One of the uses of the interface is to provide
communication. Through interface you can specify how you want the
methods and fields of a particular type.
Multiple inheritance − Java doesn’t support multiple inheritance, using
interfaces you can achieve multiple inheritance
Example:-
interface MyInterface{
public void display();
public void setName(String name);
public void setAge(int age);
}
Programme:-
interface MyInterface1{
public static int num = 100;
public default void display() {
System.out.println("display method of MyInterface1");
}
}
interface MyInterface2{
public static int num = 1000;
public default void display() {
System.out.println("display method of MyInterface2");
}
}
public class InterfaceExample implements MyInterface1, MyInterface2{
public void display() {
System.out.println("This is the implementation of the display method");
}
public void show() {
MyInterface1.super.display();
MyInterface2.super.display();
}
public static void main(String args[]) {
InterfaceExample obj = new InterfaceExample();
obj.show();
}
}
Output
display method of MyInterface1
display method of MyInterface2
13. Write short notes on Interfaces, Nested interfaces and functional
interfaces in Java
Interfaces:-
class Test {
public static void main(String args[])
{
// create anonymous inner class object
new Thread(new Runnable() {
@Override public void run()
{
System.out.println("New thread created");
}
}).start();
}
}
Output
New thread created
If subclass (child class) has the same method as declared in the parent class, it is
known as method overriding in Java.
In java a child class can define methods with same signature as in parent class, if
we do so, we call this as method overriding. Method overriding is a technique in
java which allows java programmers to write methods in child class with same
signature as in parent class.
Programme:-
class Person {
void teach() {
System.out.println("I can teach");
}
}
16. 17. Write short notes on super keyword and abstract classes
Super Keyword in Java:-
The super keyword in Java is used in subclasses to access super class members
(attributes, constructors and methods).
The super keyword in Java is a reference variable which is used to refer immediate
parent class object.
Whenever you create the instance of subclass, an instance of parent class is created
implicitly which is referred by super reference variable.
void display()
{
// print maxSpeed of base class (vehicle)
System.out.println("Maximum Speed: "
+ super.maxSpeed);
}
}
// Driver Program
class Test {
public static void main(String[] args)
{
Car small = new Car();
small.display();
}
}
Abstract Class:-
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.
In this article, we will learn the use of abstract class in java.
What is Abstract class in Java?
Java abstract class is a class that can not be initiated by itself, it needs to be sub
classed by another class to use its properties. An abstract class is declared using
the “abstract” keyword in its class definition.
Illustration of 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.
// Abstract class
abstract class Sunstar {
abstract void printInfo();
}
System.out.println(name);
System.out.println(age);
System.out.println(salary);
// Base class
class Base {
public static void main(String args[]) {
Sunstar s = new Employee();
s.printInfo();
}
}
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");
}
}
In the above example, you can see that even though b is a type of Animal it runs
the move method 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.