Experiment No1,2,3
Experiment No1,2,3
1
Aim: Design a class ‘Complex ‘with data members for real and imaginary part. Provide default
and Parameterized constructors. Write a program to perform arithmetic operations of two
complex numbers.
Theory:
Fields
Methods
Constructors
Blocks
Nested class and interface
A variable which is created inside the class but outside the method is known as an
instance variable. Instance variable doesn't get memory at compile time. It gets
memory at runtime when an object or instance is created. That is why it is known as an
instance variable.
Method in Java
In Java, a method is like a function which is used to expose the behaviour of an object.
new keyword in Java
The new keyword is used to allocate memory at runtime. All objects get memory in Heap
memory area.
classname object =new classname();
3. What is an object in Java ?
An entity that has state and behavior is known as an object e.g., chair, bike, marker, pen, table,
car, etc. It can be physical or logical (tangible and intangible).
An object has three characteristics:
State: represents the data (value) of an object.
Behavior: represents the behaviour (functionality) of an object such as deposit, withdraw, etc.
Identity: An object identity is typically implemented via a unique ID. The value of the ID is not
visible to the external user. However, it is used internally by the JVM to identify each object
uniquely.
For Example, Pen is an object. Its name is Reynolds; color is white, known as its state. It is used
to write, so writing is its behaviour.
An object is an instance of a class. A class is a template or blueprint from which objects are
created.
Object Definitions:
An object is a real-world entity.
An object is a runtime entity.
The object is an entity which has state and behavior.
The object is an instance of a class.
File: Student.java
4. Constructors in Java
In Java, a constructor is a block of codes similar to the method. It is called when an instance of
the class is created. At the time of calling constructor, memory for the object is allocated in the
memory. It is a special type of method which is used to initialize the object. Every time an
object is created using the new() keyword, at least one constructor is called. It calls a default
constructor if there is no constructor available in the class. In such case, Java compiler provides
a default constructor by default.
There are two types of constructors in Java: no-arg constructor, and parameterized constructor.
It is not necessary to write a constructor for a class. It is because java compiler creates a default
constructor if your class doesn't have any.
Example:
Algorithm:
1. Begin
2. Define a class operation with instance variables real and imag
3. Input the two complex numbers c1=(a+ib) and c2=(c+id)
4. Define the method add (c1, c2) as (a+ib) + (c+id) and stores result in c3
5. Define the method sub (c1, c2) as (a+ib) - (c+id) and stores result in c3
6. Define the method mul (c1, c2) as (a+ib) * (c+id) and store the result in c3
as (ac-bd) + i(bc+ad)
7. Define the method div (c1, c2) as (a+ib)/(c+id) and stores the quotient c3 as
{(ac+bd)/(c2+d2)} +i{(bc-ad)/(c2+d2)}
8. Define the method display () which outputs each result
9. End
Input and Output Requirements:
Program reads real and imaginary parts of two complex numbers through keyboard and displays
their sum, difference, product and quotient as result.
Conclusion:
Theory:
This section explains the Object Oriented Concept, Polymorphism. Polymorphism is the ability
of an entity to behave in different forms. Take a real-world example; the Army Ants. There are
different size of ants in the same ant colony with different responsibilities; workers are in
different sizes and the queen is the largest one. This is a polymorphic behavior where the
entities have a unique feature while they share all other common attributes and behaviors.
Polymorphism is considered as one of the important features of Object Oriented Programming.
Polymorphism allows us to perform a single action in different ways. In other words,
polymorphism allows you to define one interface and have multiple implementations. The word
“poly” means many and “morphs” means forms, So it means many forms.
There are two types of polymorphism in java:
Method Overloading: This allows us to have more than one method having the same name, if the
parameters of methods are different in number, sequence and data types of parameters.
Example :Method overloading is one of the way java supports static polymorphism. Here we
have two definitions of the same method add() which add method would be called is determined
by the parameter list at the compile time. That is the reason this is also known as compile time
polymorphism.
classSimpleCalculator
{
int add(int a,int b)
{
returna+b;
}
int add(int a,int b,int c)
{
returna+b+c;
}
}
publicclassDemo
{
publicstaticvoid main(Stringargs[])
{
SimpleCalculatorobj=newSimpleCalculator();
System.out.println(obj.add(10,20));
System.out.println(obj.add(10,20,30));
}
}
Method Overriding: 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.
Method Overriding Example: We have two classes: A child class Boy and a parent class Human.
The Boy class extends Human class. Both the classes have a common method void eat (). Boy
class is giving its own implementation to the eat () method or in other words it is overriding the
eat () method.
The purpose of Method Overriding is clear here. Child class wants to give its own
implementation so that when it calls this method, it prints Boy is eating instead of Human is
eating.
classHuman{
//Overridden method
publicvoid eat()
{
System.out.println("Human is eating");
}
}
classBoyextendsHuman{
//Overriding method
publicvoid eat(){
System.out.println("Boy is eating");
}
publicstaticvoid main(Stringargs[]){
Boyobj=newBoy();
//This will call the child class version of eat()
obj.eat();
}
}
Output:
Boy is eating
Advantage of method overriding: The main advantage of method overriding is that the class can
give its own specific implementation to a inherited method without even modifying the parent
class code. This is helpful when a class has several child classes, so if a child class needs to use
the parent class method, it can use it and the other classes that want to have different
implementation can use overriding feature to make changes without touching the parent class
code.
Method Overriding is an example of runtime polymorphism. When a parent class reference
points to the child class object then the call to the overridden method is determined at runtime,
because during method call which method (parent class or child class) is to be executed is
determined by the type of object. This process in which call to the overridden method is
class ABC{
//Overridden method
publicvoiddisp()
{
System.out.println("disp() method of parent class");
}
}
classDemoextends ABC{
//Overriding method
publicvoiddisp(){
System.out.println("disp() method of Child class");
}
publicvoidnewMethod(){
System.out.println("new method of child class");
}
publicstaticvoid main(Stringargs[]){
/* When Parent class reference refers to the parent class object
* then in this case overridden method (the method of parent class)
* is called.
*/
ABC obj=newABC();
obj.disp();
Output
:
In the above example the call to the disp() method using second object (obj2) is runtime polymorphism In
dynamic method dispatch the object can call the overriding methods of child class and all the non-
overridden methods of base class but it cannot call the methods which are newly declared in the child
class. In the above example the object obj2 is calling the disp(). However if you try to
call the newMethod() method (which has been newly declared in Demo class) using obj2 then you
would give compilation error.
Rule #1:
Overriding method name and the overridden method name must be exactly same.
Rule #2:
Overriding method must have the same set of parameters as the overridden method.
Rule #3:
The return type of overriding method name must be same as the super class’s method.
Rule #4:
Access modifier of the overriding method must be same or less restrictive than the overridden method’s access
modifier.
Rule #5:
The overriding method can throw new unchecked exceptions but cannot throw new checked exceptions.
Sample Code:
Consider Book & Magazines both specific type of publication
Attribute title, author & price are obvious parameter. For Book, orderCopies() takes parameter specifying
how many copies are added to stock.For Magazine, orderQty is number of copies received of each new issue
and currIssue is date/period of current issue.We can separate out these common member of classes into
superclass called Publication.The differences will need to be specified as additional member for the
‘subclasses’ Book and Magazine.
Conclusion
Experiment No.3
Problem Statement: -
Design and develop inheritance for a given case study, identify objects and relationships and
implement inheritance wherever applicable. Employee class with Emp_name, Emp_id, Address,
Mail_id, and Mobile_no as members. Inherit the classes, Programmer, Team Lead, Assistant
Project Manager and Project Manager from employee class. Add Basic Pay (BP) as the member
of all the inherited classes with 97% of BP as DA, 10 % of BP as HRA, 12% of BP as PF, 0.1%
of BP for staff club fund. Generate pay slips for the employees with their gross and net salary.
Objectives:
1) To Study Inheritance and its types
2) To implement inheritance using OOP language
Theory:-
Inheritance:
Different kinds of objects often have a certain amount in common with each other. Mountain
bikes, road bikes, and tandem bikes, for example, all share the characteristics of bicycles
(current speed, current pedal cadence, current gear). Yet each also defines additional features
that make them different: tandem bicycles have two seats and two sets of handlebars; road bikes
have drop handlebars; some mountain bikes have an additional chain ring, giving them a lower
gear ratio. Object-oriented programming allows classes to inherit commonly used state and
behavior from other classes. In this example, Bicycle now becomes the superclass of
MountainBike, RoadBike, and TandemBike. In the Java programming language, each class is
allowed to have one direct superclass, and each superclass has the potential for an unlimited
number of subclasses:
The syntax for creating a subclass is simple. At the beginning of your class
declaration, use the extends keyword, followed by the name of the class to
inherit from:
This gives MountainBike all the same fields and methods as Bicycle, yet allows its code to focus
exclusively on the features that make it unique. This makes code for your subclasses easy to
read. However, you must take care to properly document the state and behavior that each
superclass defines, since that code will not appear in the source file of each subclass.
Single Inheritance: When a class extends another one class only then we call it a single
inheritance. The below flow diagram shows that class B extends only one class which is A.
Here A is a parent class of B and B would be a child class of A.
Multiple Inheritance: It refers to the concept of one class extending (Or inherits) more than
one base class. The inheritance we learnt earlier had the concept of one base class or parent.
The problem with “multiple inheritance” is that the derived class will have to manage the
dependency on two base classes.
Hybrid Inheritance :In simple terms you can say that Hybrid inheritance is a combination
of Single and Multiple inheritance. A typical flow diagram would look like below. A hybrid
inheritance can be achieved in the java in a same way as multiple inheritance can be!! Using
interfaces. yes you heard it right. By using interfaces you can have multiple as well as hybrid
inheritance in Java.
Steps :
1. Start
2. Create the class Employee with name, Empid, address, mailid, mobileno as data members.
3. Inherit the classes Programmer, Team Lead, Assistant Project Manager and Project Manager
from employee class.
4. Add Basic Pay (BP) as the member of all the inherited classes.
5. Calculate DA as 97% of BP, HRA as 10% of BP, PF as 12% of BP, Staff club fund as 0.1% of
BP.
6. Calculate gross salary and net salary.
7. Generate payslip for all categories of employees.
8. Create the objects for the inherited classes and invoke the necessary methods to display the
Payslip
9. Stop
Input:
Empid, address, mailid, mobileno, Basic Pay (BP)
Output:
gross and net salary slip
Implementation: -
clas
s
Em
plo
yee
{ in
t
em
pid;
long mobile;
String name,
address, mailid;
void getdata() {----}
void display() {-----}
}
class Programmer extends
Employee { double
salary,bp,da,hra,pf,club,net,
gross; void getasst() { }
void calculateasst() {- - -}
}
class TeamLead extends Employee {
---
}
class AssistantProjectManager extends Employee {
---
}
class Project Manager extends Employee {
---
}
class Salary {
public static void main(String args[]) {----}
}
Conclusion