Final - OOPJ Lab Manual
Final - OOPJ Lab Manual
Inheritance: Inheritance is the process by which objects of one class acquire the properties of
objects of another class.
Polymorphism: polymorphism means ability to take more than one form. An operation may
exhibit different behaviors in different instances. The behavior depends upon the types of data
used in the operation.
Structure of C++ program
/ my first program in C++
#include <iostream>
int main()
{
std::cout << "Hello World!";
}
Output: Hello World!
1
Line 1: // my first program in C++
Two slash signs indicate that the rest of the line is a comment inserted by the programmer but
which has no effect on the behavior of the program. Programmers use them to include short
explanations or observations concerning the code or program. In this case, it is a brief introductory
description of the program.
This statement has three parts: First, std::cout, which identifies the standard character output device
(usually, this is the computer screen). Second, the insertion operator (<<), which indicates that
what follows is inserted into std::cout. Finally, a sentence within quotes ("Hello world!"), is the
content inserted into the standard output.
2
Experiment_No:1
3
OUTPUT:
Conclusion: Thus we have studied addition of numbers using C++ Programming in DOS platform.
4
b) Program on factorial numbers using C++ and virtual lab. Go to Problem Solving Lab →List Of
Experiments on http://ps-iiith.vlabs.ac.in/
We shall try to calculate the factorial of a number and then find out the number of digits in it.
1! = 1
2! = 1*2 = 2
3! = 1*2*3 = 6
4! = 1*2*3*4 = 24.
10! = 3628800
So n! means multiplying all the numbers from 1 to n. For the sample input, 52, we can see from the
sample output that the factorial of 52 is 68 digits and this cannot fit in long long data type in C. You
may now attempt to store the answer in a string and do multiplication operation on strings(by
multiplying each digit of the string individually). Now, let us see how many operations do we need
for multiplying 2 strings. Consider 11!, 11! = 11*10!, assume we already have 10! stored in a string
and 11 stored in a string. Now, to calculate 11! from 10! we need to multiply each digit of 11 with
each digit of 10!, i.e it would take No_digits(11) * No_digits(3628800) = 2*7 = 14 operations. We
consider only multiplication operations(we also have to consider addition operations for each of the
biproducts and carries).
Similarly 53! would take 2*68=136 operations from 52!.
52! would take 2*67 = 134 operations from 51!
51! would take 2*65 = 130 operations from 50!.
We can see that there would be a operations required for calculating 53! (No_operations =
136+134+130+...+1). Also in 1000000! the number of digits is 5565709, so we would require large
amount of storage and both these difficulties make calculation of N! hard.
Let us observe the zeroes in the factorial of a few numbers.
4!=24 (0 zeroes)
5!=120 (1 zeroes)
6!=720 (1 zeroes)
7!=5040 (1 zeroes)
8!=40320 (1 zeroes)
9!=362880 (1 zeroes)
10!=3628800 (2 zeroes)
11!-14! (2 zeroes)
15! (3 zeroes)
We can observe that for every multiple of 5, we have a zero being added to the product. This is due
to the multiplication of 5 with an even number in the product. So, our problem simplifies to counting
the number of 5's in the factors of the number to be calculated. Let us formalize the proof.
Conclusion: Thus we have studied Factorials in virtual lab.
5
EXPERIMENT NO: 2
Simple: Java is very easy to learn, and its syntax is simple, clean and easy to understand.
According to Sun, Java language is a simple programming language because:
Robust: With automatic garbage collection and simple memory management model (no
pointers like C/C++), plus language features like generics, try-with-resources, Java guides
programmer toward reliable programming habits for creating highly reliable applications.
Secure: The Java platform is designed with security features built into the language and runtime
system such as static type-checking at compile time and runtime checking (security manager),
which let you creating applications that can’t be invaded from outside. You never hear about
viruses attacking Java applications.
High Performance: Java code is compiled into bytecode which is highly optimized by the Java
compiler, so that the Java virtual machine (JVM) can execute Java applications at full speed. In
addition, compute-intensive code can be re-written in native code and interfaced with Java
platform via Java Native Interface (JNI) thus improve the performance.
Multithreaded: The Java platform is designed with multithreading capabilities built into the
language. That means you can build applications with many concurrent threads of activity,
resulting in highly interactive and responsive applications.
Platform Independence: Java code is compiled into intermediate format (byte code), which
can be executed on any systems for which Java virtual machine is ported. That means you can
write a Java program once and run it on Windows, Mac, Linux or Solaris without re-compiling.
Thus the slogan “Write once, run anywhere” of Java.
6
Java Scanner Class
Java Scanner class comes under the java.util package. Java has various ways to read input from
the keyboard, the java.util.Scanner class is one of them.
1 String next() It is used to get the next complete token from the
scanner which is in use.
2 boolean nextBoolean() It scans the next token of the input into a boolean
value and returns that value.
3 byte nextByte() It scans the next token of the input as a byte.
4 double nextDouble() It scans the next token of the input as a double.
5 float nextFloat() It scans the next token of the input as a float.
6 int nextInt() It scans the next token of the input as an Int.
7 String nextLine() It is used to get the input string that was skipped
of the Scanner object.
8 long nextLong() It scans the next token of the input as a long.
9 short nextShort() It scans the next token of the input as a short.
Structure of a JAVA program
class Simple
{
public static void main(String args[]){
System.out.println("Hello Java");
}
}
class keyword is used to declare a class in java.
public keyword is an access modifier which represents visibility. It means it is visible to all.
static is a keyword. If we declare any method as static, it is known as the static method. The core
advantage of the static method is that there is no need to create an object to invoke the static
method. The main method is executed by the JVM, so it doesn't require to create an object to
invoke the main method. So it saves memory.
void is the return type of the method. It means it doesn't return any value.
main represents the starting point of the program.
String[] args is used for command line argument. We will learn it later.
System.out.println() is used to print statement. Here, System is a class, out is the object of
PrintStream class, println() is the method of PrintStream class. We will learn about the internal
working of System.out.println statement later.
7
Experiment_No:2
Program.Simple calculator using java.
import java.util.Scanner;
public class JavaExample
{
public static void main(String[] args)
{
double num1, num2;
Scanner scanner = new Scanner(System.in);
System.out.print("Enter first number:");
num1 = scanner.nextDouble();
System.out.print("Enter second number:");
num2 = scanner.nextDouble();
8
Conclusion:
Here we have studied object oriented features and implemented simple java program.
9
EXPERIMENT NO: 3
Aim: Implementation Java Program to define a class defines instance methods for setting and
getting values of instance variables and instantiate its object.
Theory:
Class: A class is a user defined blueprint or prototype from which objects are created.
Syntax of the class:
class <class_name>{
field;
method; }
Object: It is a basic unit of Object Oriented Programming and represents the real life entities.
Object is instance of the class.
1.Initialization through Reference: Initializing an object means storing data into the object.
class Student{
}
public static void main(String args[]){
Student s1=new Student(); }
2.Initialization through method: In this example, we are creating the objects of Student class
and initializing the value to these objects by invoking the insertRecord method.
class Student{
Types of variables:
1. Local Variables: A variable defined within a block or method or constructor is called local
variable. These variable are created when the block in entered or the function is called and
destroyed after exiting from the block or when the call returns from the function.
10
2. Instance Variables: Instance variables are non-static variables and are declared in a class
outside any method, constructor or block.
3. Static Variables: Static variables are also known as Class variables.
These variables are declared similarly as instance variables, the difference is that static variables
are declared using the static keyword within a class outside any method constructor or block.
Unlike instance variables, we can only have one copy of a static variable per class irrespective
of how many objects we create
class A
{
int data=50;//instance variable
static int m=100;//static variable
void method(){
int n=90;//local variable
}
GET AND SET METHODS IN JAVA:
get and set are technically called getters & setters. getters/setters provide public access to
private data.
why they are better?
setters prevents direct exposing your class variables to other objects. You can keep your class
variable private and provide a setter to assign its value.
Public void setName ( String n ) {
name = n;
}
getter have same advantage as setter it can format the class variable and return.
11
Experiment_No:3
//A Java class which is a fully encapsulated class.
//It has a private data member and getter and setter methods.
package com.javatpoint;
public class Student{
//private data member
private String name;
//getter method for name
public String getName(){
return name;
}
//setter method for name
public void setName(String name){
this.name=name
}
}
Conclusion: Here we have studied class, instantiating object, Get and Set methods.
12
EXPERIMENT NO: 04
a) Addition of numbers
Method Overloading is a feature that allows a class to have more than one method having the same
name, if their argument lists are different.
Three ways to overload a method
In order to overload a method, the argument lists of the methods must differ in either of these:
1. Number of parameters.
For example: This is a valid case of overloading
add(int, int)
add(int, int, int)
13
a) Addition of numbers
public class Sum {
// Overloaded sum(). This sum takes two int parameters
public int sum(int x, int y)
{
return (x + y);
}
// Overloaded sum(). This sum takes three int parameters
public int sum(int x, int y, int z)
{
return (x + y + z);
}
// Overloaded sum(). This sum takes two double parameters
public double sum(double x, double y)
{
return (x + y);
}
// Driver code
public static void main(String args[])
{
Sum s = new Sum();
System.out.println(s.sum(10, 20));
System.out.println(s.sum(10, 20, 30));
System.out.println(s.sum(10.5, 20.5));
}
}
OUTPUT:
30
60
31.0
14
b)Calculate monthly salary
class Savingaccount {
static double annualinterestrate;
private double savingbalance;
double monthlyinterest;
Savingaccount(double balance) {
savingbalance=balance;
} //Constructor close
void interest() {
System.out.println("Saving Balance ="+savingbalance);
monthlyinterest=((savingbalance*annualinterestrate)/12);
System.out.println("Monthly Interest ="+monthlyinterest);
savingbalance=savingbalance+monthlyinterest;
System.out.println("Saving Balance ="+savingbalance);
} //Method close
void interest(double newannualinterestrate){
annualinterestrate=newannualinterestrate;
System.out.println("Annual interest rate ="
+annualinterestrate);
} //overloaded method close
} //class close
public class Methodover {
public static void main(String[] args){
Savingaccount s=new Savingaccount(2000.0);
s.interest(0.05);
s.interest();
Savingaccount s1=new Savingaccount(3000.0);
s1.interest(0.05);
s1.interest();
} //main close
} //Main class close
OUTPUT:
Annual interest rate =0.05
Saving Balance =2000.0
Monthly Interest =8.333333333333334
Saving Balance =2008.3333333333333
Annual interest rate =0.05
Saving Balance =3000.0
Monthly Interest =12.5
Saving Balance =3012.5
Conclusion-
15
EXPERIMENT NO: 05
Aim : Implementation Constructor in java.
Theory:
A constructor initializes an object when it is created. It has the same name as its class and is
syntactically similar to a method. However, constructors have no explicit return type.
Rules for writing Constructor:
Constructor(s) of a class must has same name as the class name in which it resides.
A constructor in Java can not be abstract, final, static and Synchronized.
When you set a method as final it means: "You don't want any class override it." But the
constructor (according to the Java Language Specification) can't be overridden, so it is clean.
When you set a method as abstract it means: "The method doesn't have a body and it should be
implemented in a child class." But the constructor is called implicitly when the new keyword is
used so it can't lack a body. Constructor needs to have a body and implementation, so there is no
sense in making them abstract.
When you set a method as static it means: "The method belongs to the class, not a particular
object." But the constructor is implicitly called to initialize an object, so there is no purpose in
having a static constructor.
Access modifiers can be used in constructor declaration to control its access i.e which other class
can call the constructor.
17
Experiment_No:5
class ConsMain {
private int x;
// Default constructor
private ConsMain(){
System.out.println("Constructor is called!");
x = 139;
} //constructor close
public static void main(String[] args){
ConsMain obj = new ConsMain();
System.out.println("Value of x = " + obj.x);
} //main close
} //class close
OUTPUT:
Constructor is called!
Value of x = 139
Title2: Java Program for Parameterized Constructor.
class Vehicles {
int wheels;
private Vehicles(int wheel)
{
wheels = wheel;
System.out.println(wheels + " wheeler vehicle created.");
} //Parameterized constructor
public static void main(String[] args)
{
Vehicles v1 = new Vehicles(2);
Vehicles v2 = new Vehicles(3);
Vehicles v3 = new Vehicles(4);
}
}
OUTPUT:
2 wheeler vehicle created.
3 wheeler vehicle created.
4 wheeler vehicle created.
Conclusion: Here we have studied constructor concepts.
18
EXPERIMENT NO: 06
In the code, creating object p3, the III constructor is accessed. From III, with "this(100)" statement, the II
constructor is accessed. Again from II, the I is accessed without the statement "this()". As per the parameter
supplied to this(), the appropriate or corresponding constructor is accessed.
ules of using this()
A few restrictions exist for the usage of this().
If included, this() statement must be the first one in the constructor. You cannot write anything before this()
in the constructor.
With the above rule, there cannot be two this() statements in the same constructor (because both cannot be
the first).
this() must be used with constructors only, that too to call the same class constructor (but not super class
constructor).
19
Experiment_6: Java Program for Constructor Overloading.
class Company {
String domainName;
public Company(){
this.domainName = "DefaultConstuctor.com";
} //Default constructor close
public Company(String dName){
this.domainName = dName;
} //parameterized constructor close
public void getName(){
System.out.println(this.domainName);
}
public static void main(String[] args) {
Company defaultObj = new Company();
Company programizObj = new Company("ByateWorld.com");
defaultObj.getName();
programizObj.getName();
} //main close
} //class close
OUTPUT:
DefaultConstuctor.com
ByateWorld.com
20
EXPERIMENT_NO : 07
21
Experiment_No:7 Implementation of class grade book using two-dimensional array.
import java.util.Scanner;
OUTPUT:
23
EXPERIMENT NO: 08
24
2.Using packagename.classname
25
Experiment_No:08
package myPack;
public class car
{
String c_name;
engine e;
tyre t;
door d;
public car(String cn,engine e1,tyre t1,door d1 )
{
c_name=cn;
e=e1;
t=t1;
d=d1;
}
public void display()
{
System.out.println("Car name"+c_name);
System.out.println("Engine type:”+e.e_type);
System.out.println("Door color:"+d.color);}
package myPack;
public class tyre
{
int size;
public void set(int size)
{
this.size=size;
26
System.out.println("Tyre Size:"+size);
}
}
package myPack;
public class engine {
String e_type;
public engine(String e_type)
{
this.e_type=e_type;
}
}
package myPack;
public class door {
String color;
public door (String c)
{
color=c;
}
}
Calling Classes from Packages
import myPack.*;
public class CarInfo {
public static void main(String[] args) {
engine e=new engine("Petrol");
tyre t=new tyre();
door d=new door("Black");
car c=new car("Lamborghini",e,t,d);
t.set(30);
c.display();
}
}
27
OUTPUT:
Tyre Size:30
Car name: Lamborghini
Engine type: Petrol
Door color: Black
Conclusion-
Thus we have studied how to create our own package and import it.
28
EXPERIMENT NO.9
Aim: Implementing the concept of Inheritance.
Theory:
Inheritance Basics
Inheritance is a major component of object-oriented programming. Inheritance will allow
you to define a very general class, and then later define more specialized classes by simply
adding some new details to the older more general class definition. This saves work, because the
more specialized class inherits all the properties of the general class and you, the programmer,
need only program the new features. i.e Inheritance in java is a mechanism in which one object
acquires all the properties and behaviors of parent object. The idea behind inheritance in java is
that you can create new classes that are built upon existing classes. When you inherit from an
existing class, you can reuse methods and fields of parent class, and you can add new methods
and fields also.
The extends keyword indicates that you are making a new class that derives from an existing
class.In the terminology of Java, a class that is inherited is called a super class. The new class is
called a subclass.Understanding the simple example of inheritance
29
displayed in the above figure, Programmer is the subclass and Employee is the superclass.
Relationship between two classes is Programmer IS-A Employee.It means that Programmer is
a type of Employee.
On the basis of class, there can be three types of inheritance in java: single, multilevel and
hierarchical.
When you need to use and modify property and behavior of a class inside your class, its best to
use Inheritance.
30
Experiment_No:9 Implementing the concept of Inheritance.
package myPack;
class Employee{
protected int emp_no;
protected String name;
protected int salary;
//constructor
public Employee(int empno,String nam,int sal){
emp_no=empno;
name=nam;
salary=sal;
}
//constructor
public Manager(int empno,String nam,int sal,int p){
super(empno,nam,sal);
reward=p;
}
//constructor
public Scientist(int empno,String nam,int sal,int s){
super(empno,nam,sal);
perks=s;
}
//Main Class
class Inheritance{
public static void main(String args[])
{
Employee emp= new Employee(1,"Priyanka",45000);
emp.emplo_data();
OUTPUT:
Employee No: 1
Name: Priyanka
Salary: 45000
Employee No: 2
Name: Rohit
Salary: 50000
Reward: 3000
Employee no: 3
Name: Pratiksha
Salary: 48000
Perks: 5000
Conclusion: Thus we have studied the concept of inheritance and implemented it.
32
Experiment No.10
Polymorphism in Java is a concept by which we can perform a single action in different ways.
Polymorphism is derived from 2 Greek words: poly and morphs. The word "poly" means many
and "morphs" means forms. So polymorphism means many forms.
There are two types of polymorphism in Java: compile-time polymorphism and runtime
polymorphism. We can perform polymorphism in java by method overloading and method
overriding.
If you overload a static method in Java, it is the example of compile time polymorphism. Here,
Types of polymorphism:
1.Method Overloading in Java – This is an example of compile time (or static polymorphism)
Method Overloading is a feature that allows a class to have more than one method having the
same name, if their argument lists are different. It is similar to constructor overloading in Java,
that allows a class to have more than one constructor having different argument lists.
Declaring a method in sub class which is already present in parent class is known as method
overriding. Overriding is done so that a child class can give its own implementation to a method
which is already provided by the parent class. In this case the method in parent class is called
overridden method and the method in child class is called overriding method. In this guide, we
will see what is method overriding in Java and why we use it.
class Human{
//Overridden method
public void eat()
{
System.out.println("Human is eating");
}
}
class Boy extends Human{
//Overriding method
public void eat(){
System.out.println("Boy is eating");
}
public static void main( String args[]) {
Boy obj = new Boy();
//This will call the child class version of eat()
obj.eat();
}
33
Runtime polymorphism or Dynamic Method Dispatch is a process in which a call to an
overridden method is resolved at runtime rather than compile-time.
In this process, an overridden method is called through the reference variable of a superclass.
The determination of the method to be called is based on the object being referred to by the
reference variable.
class A{}
A a=new B();//upcasting
Consider a scenario where Bank is a class that provides a method to get the rate of interest.
However, the rate of interest may differ according to banks. For example, SBI, ICICI, and AXIS
banks are providing 8.4%, 7.3%, and 9.7% rate of interest.
34
Experiment_10
a)Bank details polymorphism
class Bank{
float getRateOfInterest(){return 0;}
}
class SBI extends Bank{
float getRateOfInterest(){return 8.4f;}
}
class ICICI extends Bank{
float getRateOfInterest(){return 7.3f;}
}
class AXIS extends Bank{
float getRateOfInterest(){return 9.7f;}
}
class TestPolymorphism{
public static void main(String args[]){
Bank b;
b=new SBI();
System.out.println("SBI Rate of Interest: "+b.getRateOfInterest());
b=new ICICI();
System.out.println("ICICI Rate of Interest: "+b.getRateOfInterest());
b=new AXIS();
System.out.println("AXIS Rate of Interest: "+b.getRateOfInterest());
}
}
OUTPUT:
SBI Rate of Interest: 8.4
ICICI Rate of Interest: 7.3
AXIS Rate of Interest: 9.7
OUTPUT:
eating bread...
eating rat...
eating meat...
Conclusion: Thus we have studied the concept of polymorphism and implemented it.
36