0% found this document useful (0 votes)
10 views26 pages

Unit 2

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views26 pages

Unit 2

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 26

Hindusthan College of Engineering and Technology

Hindusthan College of Engineering and Technology


An Autonomous InstitutionInstitution,
(An Autonomous Affiliated toAffiliated
Anna University | ApprovedChennai)
to Anna University, by AICTE, New Delhi
Valley
Accredited with Campus,
‘A’ Grade by NAAC | Accredited
Pollachi Highway, Coimbatore – 641032
by NBA (ECE, MECH, EEE, IT & CSE)
Valley Campus, Pollachi Highway, Coimbatore 641 032.| www.hicet.ac.in
22CS3251 / OBJECT ORIENTED PROGRAMMING
USING JAVA

UNIT 2 - ARRAYS, CLASS AND INHERITANCE


Introduction to Arrays in java-Arrays class-declaration and initialization of an array-2D array declaration
and initialization -multi-dimensional array-Classes and objects-naming convention in java-methods-
access modifiers-constructors- copy constructors -singleton class- object class-inner class-abstract class-
Throwable class- types of inner class- static and non-static nested class-Inheritance-Types of inheritance
Difference between inheritance in C++ and Java.

1.1 Introduction to Arrays


An array is a collection of similar datatypes. All arrays are dynamically allocated. Arrays are
stored in contiguous memory. The variables in the array are ordered, and each has an index beginning
with 0. The size of an array must be specified by int or short value and not long. The size of the array
cannot be altered once initialized.
Types of Array
 One-dimensional Array. Also known as a linear array, the elements are stored in a single row.
 Two-dimensional Array. Two-dimensional arrays store the data in rows and columns.
 Multi-dimensional Array. This is a combination of two or more arrays or nested arrays.

1.2 One-dimensional Array


An array with one dimension is called one-dimensional array or single dimensional array in java. It is a
list of variables containing values that all have the same type. One dimensional array represents one row
or one column of array elements that share a common name and is distinguishable by index values. For
example, marks obtained by a student in five subjects can be represented by single-dimensional array
because these marks can be written as one row or one column.
Syntax to declare an 1D array:
dataType[] arr = new dataType[size]; (OR)
dataType []arr = new dataType[size]; (OR)
dataType arr[] = new dataType[size];
Example
int a = new int[10];
Static Initialization
int number[] = {11, 22, 33, 44, 55, 66, 77, 88, 99, 100};

Memory Representation after Initialization


Example
import java.util.*;
public class Main
{
public static void main(String[] args)
{
int [] a = new int [10];
int temp = 0, n;
Scanner in = new Scanner(System.in);
System.out.println("Enter n: ");
n = in.nextInt();
System.out.println("Enter the elements: ");
for (int i = 0; i <n; i++)
{
a[i] = in.nextInt();
}
for (int i = 0; i <n; i++)
{
for (int j = i+1; j <n; j++)
{
if(a[i] >a[j]) {
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
System.out.println("\nArray sorted in ascending order: ");
for (int i = 0; i <n; i++)
{
System.out.print(a[i] + " ");
}
}
}
Output
Enter n:
5
Enter the elements:
10
26
8
36
48

Array sorted in ascending order:


8 10 26 36 48

For-each Loop for Java Array


Syntax
for(data_type variable:array)
{
//body of the loop
}
Example
import java.util.*;
public class Main
{
public static void main(String[] args)
{
char c[] = new char[10];
int n;
Scanner in = new Scanner(System.in);
System.out.println("Enter n: ");
n = in.nextInt();
System.out.println("Enter the characters: ");
for (int i = 0; i <n; i++)
{
c[i] = in.next().charAt(0);
}
System.out.println("Entered characters are: ");
for (char i : c)
{
System.out.println(i);
}
}
}

Passing Array to a Method in Java


import java.util.*;
public class Main
{
public static void main(String[] args)
{
double c[] = new double[5];
Scanner in = new Scanner(System.in);
System.out.println("Enter the numbers: ");
for (int i = 0; i <5; i++)
{
c[i] = in.nextDouble();
}
System.out.println("Entered numbers are: ");
for (double i : c)
{
System.out.print(i+" ");
}
min(c);
}
static void min(double arr[])
{
double min=arr[0];
for(int i=1;i<arr.length;i++)
if(min>arr[i])
min=arr[i];
System.out.print("\nMinimum value is "+min);
}
}

Anonymous Array in Java


public class Main
{
static void printArray(int arr[])
{
for(int i=0;i<arr.length;i++)
System.out.println(arr[i]);
}
public static void main(String args[])
{
printArray(new int[]{10,22,44,66});
}
}

1.3 Two-dimensional Array


In Java, this tabular representation of data is implemented using a two-dimensional array. A two-
dimensional array is used to store data in tabular format. Since a 2D array in Java consists of rows and
columns, we need two indices, one to refer to rows and the other to a particular column in that row.
Hence, the syntax of declaring a two-dimensional array is similar to that of a one-dimensional array with
the exception of having two square brackets instead of one:
DataType[][] ArrayName = new DataType[size][size];
Example
int a[][] = new int[3][3];
Static Initialization
int a[][] = {{1, 2, 3}, {1, 2, 3}, {1, 2, 3}};

Example
import java.util.*;
class Main
{
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
int a[][] = new int[3][3];
int b[][] = new int[3][3];
int sum[][] = new int[3][3];
int r,c,i,j;
System.out.println("Enter r & c: ");
r = in.nextInt();
c = in.nextInt();
System.out.println("Enter the elements for A matrix: ");
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
a[i][j] = in.nextInt();
}
}
System.out.println("Enter the elements for B matrix: ");
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
b[i][j] = in.nextInt();
}
}
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
sum[i][j] = a[i][j] + b[i][j];
}
}
System.out.println("Sum of A & B matrix: ");
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
System.out.print(sum[i][j]+"\t");
}
System.out.println();
}
}
}
Output
Enter r & c:
2
2
Enter the elements for A matrix:
1
2
3
4
Enter the elements for B matrix:
5
6
7
8
Sum of A & B matrix:
6 8
10 12

1.4 Multi-dimensional Array


A multidimensional array is an array of arrays. Each element of a multidimensional array is an
array itself. Data in multi-dimensional arrays are stored in row-major format, i.e., tabular form. To
access array elements in multidimensional arrays, more than one index is used.

1.5 Arrays Class


The Arrays class in java.util package is a part of the Java Collection Framework. This class provides
static methods to dynamically create and access Java arrays. It consists of only static methods and the
methods of Object class.
Methods in Java Array Class

Methods Action Performed

compare(array 1, array 2) Compares two arrays passed as parameters lexicographically.

Searches for the specified element in the array with the help of the
binarySearch()
Binary Search Algorithm

equals(array1, array2) Checks if both the arrays are equal or not.

fill(originalArray,
Assigns this fill value to each index of this arrays.
fillValue)

hashCode(originalArray) Returns an integer hashCode of this array instance.

sort(originalArray) Sorts the complete array in ascending order.


Methods Action Performed

spliterator(originalArray) Returns a Spliterator covering all of the specified Arrays.

Finds and returns the index of the first unmatched element between
mismatch(array1, array2)
the two specified arrays.

It returns a string representation of the contents of this array. The


string representation consists of a list of the array’s elements,
toString(originalArray) enclosed in square brackets (“[]”). Adjacent elements are separated
by the characters a comma followed by a space. Elements are
converted to strings as by String.valueOf() function.

Example
import java.util.*;
class Main
{
public static void main(String args[])
{
int a[] = {5, 78, 45, 92, 10};
int b[] = {89, 8, 65, 44, 17};
int n;
Scanner in = new Scanner(System.in);
System.out.println("Array-A before sorting: ");
for(int i : a)
{
System.out.print(i+" ");
}
Arrays.sort(a);
System.out.println("\nArray-A after sorting: ");
for(int i : a)
{
System.out.print(i+" ");
}
System.out.println("\nEnter the element to search: ");
n = in.nextInt();
System.out.println(n + " found at index = "+ Arrays.binarySearch(a, n));
System.out.println("Array-B: ");
for(int i : b)
{
System.out.print(i+" ");
}
System.out.println("\nComparing A & B: "+ Arrays.compare(a, b));
}
}
1.6 Class & Object
Class is a user-defined datatype that contains data members and Methods. It is a blueprint or prototype
from which objects are created. Class does not occupy memory. A Class in Java can contain:
 Data member
 Method
 Constructor
 Nested Class
Syntax
access_modifier class <class_name>
{
data member;
method;
constructor;
nested class;
}

Object
Object is a real time entity. It is an instance of a class. Objects are created dynamically using the new
keyword. Every object is associated with data and functions which define meaningful operations on
that object.
Syntax
Classname objectname = new Classname();
Example
import java.util.*;
class Student
{
String name;
int marks[] = new int[6];
int total;
double avg;
char grade;
Student()
{
Scanner in = new Scanner(System.in);
System.out.print("Enter name & 6 marks: ");
name = in.nextLine();
for(int i=0;i<6;i++)
{
marks[i] = in.nextInt();
}
}
public void calculate()
{
total = 0;
for(int i=0;i<6;i++)
{
total += marks[i];
}
avg = total / 6;
if(avg >= 80 )
grade = 'A';
else if(avg >=60 )
grade = 'B';
else if(avg >=40 )
grade = 'C';
else
grade = 'D';
}
public void display()
{
System.out.println("Name: "+name);
System.out.println("Total: "+total);
System.out.println("Average :"+avg);
System.out.println("Grade: "+grade);
}
}
class Main
{
public static void main(String[] args)
{
Student obj = new Student();
obj.calculate();;
obj.display();
}
}

1.7 Access Modifiers


Access modifiers help to restrict the scope of a class, constructor, variable, method, or data member. It
provides security, accessibility, etc. to the user depending upon the access modifier used with the
element.
Types of Access Modifiers in Java
There are four types of access modifiers available in Java:
1. Private: The access level of a private modifier is only within the class. It cannot be accessed
from outside the class.
2. Default: The access level of a default modifier is only within the package. It cannot be accessed
from outside the package. If no access level is specified, it will be the default.
3. Protected: The access level of a protected modifier is within the package and outside the
package through child class.
4. Public: The access level of a public modifier is everywhere. It can be accessed from within the
class, outside the class, within the package and outside the package.

1.8 Constructors
A constructor is a special method having name same as class name. The constructor is
automatically called immediately after the object is created, before the new operator completes. They
have no return type, not even void. Its purpose is to initialize the object of a class. It is of three types:
• Default Constructor: Constructor which takes no argument(s) is called Default Constructor.
• Parameterized constructor: Constructor which takes argument(s) is called
parameterized Constructor.
• Copy Constructor: Constructor which takes object as its argument is called copy constructor.
When a single program contains more than one constructor, then the constructor is said to be overloaded.
Example
class Box
{
double width; double height; double depth;
Box(double w, double h, double d) // Parameterized Constructor
{
width = w; height = h; depth = d;
}
Box() // Default Constructor
{
width = -1;
height = -1;
depth = -1;
}
Box(double len) // Parameterized Constructor
{
width = height = depth = len;
}
double volume()
{
return width * height * depth;
}
}
class Main
{
public static void main(String args[])
{
Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box();
Box mycube = new Box(7);
double vol;
vol = mybox1.volume();
System.out.println("Volume of mybox1 is " + vol); vol = mybox2.volume();
System.out.println("Volume of mybox2 is " + vol); vol = mycube.volume();
System.out.println("Volume of mycube is " + vol);
}
}
Output
Volume of mybox1 is 3000.0 Volume of mybox2 is -1.0 Volume of mycube is 343.0

Java this Keyword


The this keyword refers to the current object in a method or constructor. The most common use
of the this keyword is to eliminate the confusion between data members and parameters with the same
name. this can also be used to:
 Refer current class instance variable.
 Invoke current class method (implicitly)
 Invoke current class constructor.
 this can be passed as an argument in the method call.
 this can be passed as argument in the constructor call.
 this can be used to return the current class instance from the method.
Example
class Box
{
double width, height, depth;
Box(double width, double height, double depth)
{
this.width = width; //refers the instance variable
this.height = height;
this.depth = depth;
this.volume(); //invokes the method
}
public void volume()
{
double vol = width * height * depth;
System.out.println("Volume of box = " + vol);
}
}
class Main
{
public static void main(String args[])
{
Box mybox1 = new Box(10, 20, 15);
}
}

The final Keyword


In Java, the final keyword is used to indicate that a variable, method, or class cannot be modified or
extended. Here are some of its characteristics:
 Final variables: When a variable is declared as final, its value cannot be changed once it has
been initialized. This is useful for declaring constants.
 Final methods: When a method is declared as final, it cannot be overridden by a subclass.
 Final classes: When a class is declared as final, it cannot be extended by a subclass.
Example
import java.util.*;
class Circle
{
final double pai = 3.14;
double r, area;
Circle()
{
Scanner in = new Scanner(System.in);
System.out.print("Enter r: ");
r = in.nextDouble();
}
public void calculate()
{
area = pai * r * r;
System.out.println("Area of Circle = "+area);
}
}
class Main
{
public static void main(String args[])
{
Circle obj = new Circle();
obj.calculate();
}
}

Garbage Collection
In Java destruction of object from memory is done automatically by the JVM. When there is no reference
to an object, then that object is assumed to be no longer needed and the memory occupied by the object
are released. This technique is called Garbage Collection. This is accomplished by the JVM.
Advantages of Garbage Collection
 Programmer does not need to worry about dereferencing an object.
 It is done automatically by JVM.
 Increases memory efficiency and decreases the chances for memory leak.
gc() Method
gc() method is used to call garbage collector explicitly. However gc() method does not guarantee that
JVM will perform the garbage collection. It only request the JVM for garbage collection. This method
is present in System and Runtime class.

The finalize () method


Sometime an object will need to perform some specific tasks before it is destroyed such as closing an
open connection or releasing any resources held. To handle such situation finalize() method is used.
finalize() method is called by garbage collection thread before collecting object. It’s the last chance for
any object to perform cleanup utility. The finalize ( ) method has this general form:
protected void finalize( )
{
// finalization code here
}
Example
class Main
{
public static void main(String[] args)
{
Main obj = new Main();
obj = null;
System.gc();
}
public void finalize()
{
System.out.println("Garbage Collected");
}
}
Output
Garbage Collected

1.9 Copy Constructor


Copy constructor in Java allows creating an exact copy on an existing object of the same class
such that changes made on the existing object do not affect the new copy. To create a copy constructor,
take the existing object as an argument and initialize the values of instance variables with the values
obtained in the object.
Example
import java.util.*;
class Circle
{
private double r, area;
final double pai = 3.14;
public Circle() { r = 10; }
public Circle(int r) { this.r = r; }
public Circle(Circle obj) { r = obj.r; }
public void calc()
{
area = pai * r * r;
System.out.println("Area of Circle = "+area);
}
}
public class Main
{
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
Circle obj1 = new Circle();
System.out.println("Enter r: ");
int r = in.nextInt();
Circle obj2 = new Circle(r);
Circle obj3 = new Circle(obj2);
obj1.calc();
obj2.calc();
obj3.calc();
}
}

1.10 Private Constructor


A private constructor in Java is used in restricting object creation. If a constructor is declared private,
we are not able to create an object of the class. If a constructor is declared as private, then its objects are
only accessible from within the declared class. You cannot access its objects from outside the constructor
class.
Rules for Private Constructor
 It does not allow a class to be sub-classed.
 It does not allow to create an object outside the class.
 If a class has a private constructor and when we try to extend the class, a compile-time error
occurs.
 We cannot access a private constructor from any other class.
 If all the constant methods are there in our class, we can use a private constructor.
 If all the methods are static then we can use a private constructor.
 We can use a public function to call the private constructor if an object is not initialized.
 We can return only the instance of that object if an object is already initialized.
Example
import java.util.*;
class A
{
int a;
private static A obj;
private A()
{
Scanner in = new Scanner(System.in);
System.out.println("Enter a: ");
a = in.nextInt();
}
public static A getInstance()
{
if(obj == null)
{
obj = new A();
}
return obj;
}
public void display()
{
System.out.println("a = "+a);
}
}
public class Main
{
public static void main(String args[])
{
A obj1 = A.getInstance();
A obj2 = A.getInstance();
obj1.display();
obj2.display();
}
}

1.11 Singleton Class


A java singleton class is a class that can have only one object (an instance of the class) at a time.
After the first time, if we try to instantiate the Java Singleton classes, the new variable also points to the
first instance created. There are two forms of singleton design pattern
 Early Instantiation: object creation takes place at the load time.
 Lazy Instantiation: object creation is done according to the requirement.
Rules for creating Singleton class
1. Ensure that only one instance of the class exists.
2. Provide global access to that instance by
 Declaring all constructors of the class to be private.
 Providing a static method that returns a reference to the instance. The lazy initialization
concept is used to write the static methods.
 The instance is stored as a private static variable.
Example
import java.util.*;
class Singleton
{
String s;
private static Singleton obj;
private Singleton()
{
Scanner in = new Scanner(System.in);
System.out.println("Enter a string: ");
s = in.nextLine();
}
public static Singleton getInstance()
{
if(obj == null)
{
obj = new Singleton();
}
return obj;
}
public void display()
{
System.out.println(s);
}
}
public class Main
{
public static void main(String args[])
{
Singleton obj = Singleton.getInstance();
obj.display();
}
}

1.12 Object Class


Object class is present in java.lang package. Every class in Java is directly or indirectly derived
from the Object class. If a class does not extend any other class, then it is a direct child class of Object
and if extends another class then it is indirectly derived. Therefore, the Object class methods are
available to all Java classes.
Methods supported by Object class

Program
class Student
{
static int last_roll = 100;
int roll_no;
Student()
{
roll_no = last_roll;
last_roll++;
}
public int hashCode() { return roll_no; }
}
public class Main
{
public static void main(String args[])
{
Student s = new Student();
Object obj = new String("Object class");
Class c = obj.getClass();
System.out.println("Class of Object obj is : "+ c.getName());
System.out.println(s);
System.out.println(s.toString());
}
public void finalize()
{
System.out.println("finalize() method will be executed finally");
}
}

1.13 Inner Class


Inner class refers to the class that is declared inside class or interface. There are basically four types of
inner classes in java:
i. Nested Inner Class
ii. Method Local Inner Classes
iii. Static Nested Classes
iv. Anonymous Inner Classes
i) Nested Inner class
class Outer
{
class Inner
{
public void show()
{
System.out.println("In a nested class method");
}
}
}
class Main
{
public static void main(String[] args)
{
Outer.Inner in = new Outer().new Inner();
in.show();
}
}
ii) Method local inner class
class Outer
{
void outerMethod()
{
System.out.println("inside outerMethod");
class Inner
{
void innerMethod()
{
System.out.println("inside innerMethod");
}
}
Inner y = new Inner();
y.innerMethod();
}
}
class Main
{
public static void main(String[] args)
{
Outer x = new Outer();
x.outerMethod();
}
}
iii) Static nested classes
class Outer {
private static void outerMethod()
{
System.out.println("inside outerMethod");
}
static class Inner {
public static void display()
{
System.out.println("inside inner class Method");
outerMethod();
}
}
}
class Main {
public static void main(String args[])
{
Outer.Inner.display();
}
}
iv) Anonymous Inner class
abstract class Example
{
abstract void display();
}

class Main
{
public static void main(String args[])
{
Example obj=new Example()
{
void display(){System.out.println("Java anonymous inner class");
}
};
obj.display();
}
}

1.14 Abstract Class


A class which is declared with the abstract keyword is known as an abstract class in Java. It can have
abstract and non-abstract methods (method with the body). Java abstract class is a class that can not be
initiated by itself, it needs to be subclassed by another class to use its properties. There are two ways to
achieve abstraction in java:
 Abstract class (0 to 100%)
 Interface (100%)
Syntax
abstract class Classname
{
data members;
non-abstract methods() {}
abstract methods();
}
Example
import java.util.*;
abstract class Shape
{
double area;
abstract public void calc_area();
}
class Square extends Shape
{ int a;
public Square()
{
Scanner in = new Scanner(System.in);
System.out.println("Enter a: ");
a = in.nextInt();
}
public void calc_area()
{
area = a * a;
System.out.println("Area of Square = "+area);
}
}
class Circle extends Shape
{ int r;
final double pai = 3.14;
public Circle()
{
Scanner in = new Scanner(System.in);
System.out.println("Enter r: ");
r = in.nextInt();
}
public void calc_area()
{ area = r * pai * pai;
System.out.println("Area of Circle = "+area);
}
}
class Main
{ public static void main(String args[])
{
Square sobj = new Square();
Circle cobj = new Circle();
sobj.calc_area();
cobj.calc_area();
}
}
1.15 Throwable Class
The java.lang.Throwable class is the superclass of all errors and exceptions in the Java language. Only
objects that are instances of this class (or one of its subclasses) are thrown by the Java Virtual Machine
or can be thrown by the Java throw statement. Java Throwable class provides several methods like
addSuppressed(), fillInStackTrace(), getMessage(), getStackTrace(), getSuppressed(), toString(),
printStackTrace() etc.
Example
public class Main
{
public static void main(String[] args)throws Throwable
{
try
{
int i=10/0;
}
catch(Throwable t)
{
System.out.println(t.getMessage());
}
}
}

1.16 Inheritance
Inheritance is the mechanism by which one class is allowed to inherit the features (data members and
methods) of another class. A class that inherits from another class can reuse the methods and fields
of that class. The extends keyword is used for inheritance in Java.
Syntax
class derived-class extends base-class
{
data members;
methods;
}
There are five types of inheritance:

i) Single Inheritance
import java.util.*;
class Student{
String name;
int regno;
String branch;
public Student()
{
Scanner in = new Scanner(System.in);
System.out.println("Enter name, branch & regno: ");
name = in.nextLine();
branch = in.nextLine();
regno = in.nextInt();
}
public void display()
{
System.out.println("Name : "+name);
System.out.println("Reg. No : "+regno);
System.out.println("Branch : "+branch);
}
}
class Exam extends Student
{ int m1, m2, m3, m4, total;
double avg;
public Exam()
{ super();
Scanner in = new Scanner(System.in);
System.out.println("Enter four marks: ");
m1 = in.nextInt();
m2 = in.nextInt();
m3 = in.nextInt();
m4 = in.nextInt();
}
public void showMarks()
{ total = m1 + m2 + m3 + m4;
avg = total / 4;
System.out.println("Marks: "+m1+" "+m2+" "+m3+" "+m4);
System.out.println("Total: "+total);
System.out.println("Average: "+avg);
}
}
class Main
{
public static void main(String args[])
{
Exam s1 = new Exam();
s1.display();
s1.showMarks();
}
}
ii) Multilevel
import java.util.*;
class GrandFather
{
String gf_name;
public GrandFather()
{
Scanner in = new Scanner(System.in);
System.out.println("Enter grand father name: ");
gf_name = in.nextLine();
}
}
class Father extends GrandFather
{
String f_name;
public Father()
{
super();
Scanner in = new Scanner(System.in);
System.out.println("Enter father name: ");
f_name = in.nextLine();
}
}
class Son extends Father
{ String s_name;
public Son()
{ super();
Scanner in = new Scanner(System.in);
System.out.println("Enter son name: ");
s_name = in.nextLine();
}
public void display()
{
System.out.println("GrandFather's Name : "+gf_name);
System.out.println("Father's Name : "+f_name);
System.out.println("Son's Name : "+s_name);
}
}
class Main
{
public static void main(String args[])
{ Son obj = new Son();
obj.display();
}
}

iii)Hierarchical
import java.util.*;
class Shape
{ double area;
public void calc_area() {}
}
class Square extends Shape
{ int a;
public Square()
{
Scanner in = new Scanner(System.in);
System.out.println("Enter a: ");
a = in.nextInt();
}
public void calc_area()
{
area = a * a;
System.out.println("Area of Square = "+area);
}
}
class Circle extends Shape
{ int r;
final double pai = 3.14;
public Circle()
{
Scanner in = new Scanner(System.in);
System.out.println("Enter r: ");
r = in.nextInt();
}
public void calc_area()
{ area = r * pai * pai;
System.out.println("Area of Circle = "+area);
}
}
class Main
{ public static void main(String args[])
{ Square sobj = new Square();
Circle cobj = new Circle();
sobj.calc_area();
cobj.calc_area();
}
}

1.17 Difference between inheritance in C++ and Java

C++ Java

C++ supports multiple inheritance. Java does not support multiple inheritance through
class. It can be achieved by using interfaces in java.

C++ supports virtual keyword to override Java has no virtual keyword. It is possible to override
a function. all non-static methods by default.

C++ always creates a new inheritance Java always uses a single inheritance tree because all
tree. classes are the child of the Object class in Java. The
Object class is the root of the inheritance tree in java.

You might also like