Download as pdf or txt
Download as pdf or txt
You are on page 1of 13

LECTURE NOTES AND LAB HANDOUTS

OBJECT OREINTED PROGRAMMING (ITEC / SENG – 321 ) WEEK. 7

PASSING ARRAY TO METHOD


You can pass arrays to a method just like normal variables. When we pass an array to a method as an argument,
actually the address of the array in the memory is passed (reference). Therefore, any changes to this array in the
method will affect the array.

PROGRAM 1: Demonstrate passing of array to method

class Test
{
public static void sum(int[] arr) // getting sum of array values
{
int sum = 0;
for (int i = 0; i < arr.length; i++)
sum+=arr[i];
System.out.println("sum of array values : " + sum);
}

public static void main(String args[])


{
int arr[] = {3, 1, 2, 5, 4};
sum(arr); // passing array to method m1
}
}

VARIABLE ARGUMENTS (VARARGS) IN JAVA


In JDK 5, Java has included a feature that simplifies the creation of methods that need to take a variable number of
arguments. This feature is called varargs and it is short-form for variable-length arguments. A method that takes a
variable number of arguments is a varargs method.
Prior to JDK 5, variable-length arguments could be handled two ways. One using overloaded method(one for each)
and another put the arguments into an array, and then pass this array to the method. Both of them are potentially
error-prone and require more code. The varargs feature offers a simpler, better option.
A variable-length argument is specified by three periods(…). For Example,
public static void fun(int ... a)
{
// method body
}
This syntax tells the compiler that fun( ) can be called with zero or more arguments. As a result, here a is implicitly
declared as an array of type int[].

A method can have variable length parameters with other parameters too, but one should ensure that there exists
only one varargs parameter that should be written last in the parameter list of the method declaration.
int nums(int a, float b, double … c)
In this case, the first two arguments are matched with the first two parameters and the remaining arguments
belong to c.

 Vararg Methods can also be overloaded but overloading may lead to ambiguity.
 Prior to JDK 5, variable length arguments could be handled into two ways : One was using overloading,
other was using array argument.
 There can be only one variable argument in a method.
 Variable argument (varargs) must be the last argument.

Course Instructor: Nazish Basir Page: 1/13


Institute of Information and Communication Technology, University of Sindh.
LECTURE NOTES AND LAB HANDOUTS
OBJECT OREINTED PROGRAMMING (ITEC / SENG – 321 ) WEEK. 7

PROGRAM 2: Demonstrate Variable Arguments

class Test1 {
// A method that takes variable number of integer arguments.
static void fun(int ...a) {
System.out.println("Number of arguments: " + a.length);
// using for each loop to display contents of a
for (int i: a)
System.out.print(i + " ");
System.out.println();
}

public static void main(String args[]) {


// Calling the varargs method with different number of parameters
fun(100); // one parameter
fun(1, 2, 3, 4); // four parameters
fun(); // no parameter
}
}

PROGRAM 3: Overloading Vararg Methods

class VarArgs3 {
static void vaTest(int ... v) {
System.out.print("vaTest(int ...): " + "Number of args: " + v.length +
" Contents: ");
for(int x : v)
System.out.print(x + " ");
System.out.println();
}
static void vaTest(boolean ... v) {
System.out.print("vaTest(boolean ...) " + "Number of args: " +
v.length + " Contents: ");
for(boolean x : v)
System.out.print(x + " ");
System.out.println();
}
static void vaTest(String msg, int ... v) {
System.out.print("vaTest(String, int ...): " + msg + v.length +
" Contents: ");
for(int x : v)
System.out.print(x + " ");
System.out.println();
} public static void main(String args[])
{
vaTest(1, 2, 3);
vaTest("Testing: ", 10, 20);
vaTest(true, false, false);
}
}

Course Instructor: Nazish Basir Page: 2/13


Institute of Information and Communication Technology, University of Sindh.
LECTURE NOTES AND LAB HANDOUTS
OBJECT OREINTED PROGRAMMING (ITEC / SENG – 321 ) WEEK. 7

INPUT AND OUTPUT USING JOPTIONPANE DIALOG BOXES

Java provides the JOptionPane class for creating dialog boxes—those familiar pop-up windows that prompt the
user to enter a value or notify the user of an error. The JOptionPane class is in the javax.swing package.

THE INTEGER, DOUBLE, AND OTHER WRAPPER CLASSES

A wrapper class “wraps” the value of a primitive type, such as double or int, into an object. These wrapper classes
define an instance variable of that primitive data type, and also provide useful constants and methods for
converting between the objects and the primitive data types.

PROGRAM 4: Using the JOptionPane class for creating dialog boxes

import javax.swing.JOptionPane;
class Test {
public static void main(String a[]){
JOptionPane.showMessageDialog(null, "Hello");
String name;
name = JOptionPane.showInputDialog("What is your name?");
JOptionPane.showMessageDialog(null, "Hello "+ name);
System.out.println();
}
}

Course Instructor: Nazish Basir Page: 3/13


Institute of Information and Communication Technology, University of Sindh.
LECTURE NOTES AND LAB HANDOUTS
OBJECT OREINTED PROGRAMMING (ITEC / SENG – 321 ) WEEK. 7

PROGRAM 5: Using parseInt() and the JOptionPane class for creating dialog boxes

import javax.swing.JOptionPane;
class Test {
public static void main(String arg[]){
int a,b;
a = Integer.parseInt(JOptionPane.showInputDialog("Enter 1st Value:"));
b = Integer.parseInt(JOptionPane.showInputDialog("Enter 2nd Value:"));
JOptionPane.showMessageDialog(null, a+" + " +b+ " = "+ (a+b));
System.out.println();
}
}

PROGRAM 6:
import javax.swing.JOptionPane;
class MainMenu {
int option;
public void mainMenu() {
do {
option = Integer.parseInt(JOptionPane.showInputDialog("SELECT FROM
THIS MENU" + "\n1.Calculator\n2.Convertor\n3.Marksheet\n4.Exit"
+ "\nEnter Your Choice "));

switch(option) {
case 1:
Calculator cl = new Calculator();
cl.menu();
break;

case 2:
JOptionPane.showMessageDialog(null,"Convertor");
break;

case 3:
JOptionPane.showMessageDialog(null,"Marks Sheet");
break;

case 4:
JOptionPane.showMessageDialog(null,"Thank You for Using");
break;

default:
JOptionPane.showMessageDialog(null,"Invalid Option");
}
}
while(option !=4);
}
}

Course Instructor: Nazish Basir Page: 4/13


Institute of Information and Communication Technology, University of Sindh.
LECTURE NOTES AND LAB HANDOUTS
OBJECT OREINTED PROGRAMMING (ITEC / SENG – 321 ) WEEK. 7

class Calculator {
int n1,n2, option;
char ch;

public void menu() {

do {
option=Integer.parseInt(JOptionPane.showInputDialog("Calculator\n"
+ "\n1Add\n2.Sub\n3.Multi\n4.Division\n5.Back"));

if(option == 1) {
add();
}
else if(option == 2) {
sub();
}
else if(option == 3) {
mul();
}
else if(option == 4) {
div();
}
else if (option == 5) {
JOptionPane.showMessageDialog(null, "Thank you for using Calculator");
}
}while(option != 5);
}

public void init() {


n1=Integer.parseInt(JOptionPane.showInputDialog("Enter 1st Value "));
n2=Integer.parseInt(JOptionPane.showInputDialog("Enter 2nd Value "));
}

public void add() {


do {
init();
JOptionPane.showMessageDialog(null, n1+" + " + n2 + " = "+(n1+n2));
ch = JOptionPane.showInputDialog("Calculate Again [Y/N]").charAt(0);
}while(ch=='y' || ch == 'Y');
}

public void sub() {


do {
init();
JOptionPane.showMessageDialog(null, n1+" - " + n2 + " = "+(n1-n2));
ch = JOptionPane.showInputDialog("Calculate Again [Y/N]").charAt(0);
}while(ch=='y' || ch == 'Y');
}

Course Instructor: Nazish Basir Page: 5/13


Institute of Information and Communication Technology, University of Sindh.
LECTURE NOTES AND LAB HANDOUTS
OBJECT OREINTED PROGRAMMING (ITEC / SENG – 321 ) WEEK. 7

public void mul() {


do {
init();
JOptionPane.showMessageDialog(null, n1+" x " + n2 + " = "+(n1*n2));
ch = JOptionPane.showInputDialog("Calculate Again [Y/N]").charAt(0);
}while(ch=='y' || ch == 'Y');
}

public void div() {


do {
init();
JOptionPane.showMessageDialog(null, n1+" / " + n2 + " = "+(n1/n2));
ch = JOptionPane.showInputDialog("Calculate Again [Y/N]").charAt(0);
}while(ch=='y' || ch == 'Y');
}

class MultiProgramClient {
public static void main(String[] args) {
MainMenu ob = new MainMenu();
ob.mainMenu();
}
}

EXERCISE:

Run program number 3 and see the results. Now create two more classes Converter and MarkSheet. (See
Calculator class for the design of both classes)
In Converter, use any 4 options for conversion of your choice. For Example Kilogram to Pounds, Hours to
Minuets or Degree Celsius to Degree Fahrenheit, etc. The program should show a menu for choice. When
user selects the choice the input box should take value of unit from user and convert it accordingly. The
program should ask if you want to convert another value.
In MarkSheet, take five subject of your choice and show in menu then when a user select a choice the
program should take input of marks from user for each subject. Finally shows the total, percentage and
grade of that student.

Course Instructor: Nazish Basir Page: 6/13


Institute of Information and Communication Technology, University of Sindh.
LECTURE NOTES AND LAB HANDOUTS
OBJECT OREINTED PROGRAMMING (ITEC / SENG – 321 ) WEEK. 7

INHERITANCE IN JAVA
 Inheritance allows us to define a class in terms of another class, which makes it easier to create and maintain
an application.
 This also provides an opportunity to reuse the code functionality and fast implementation time. When creating
a class, instead of writing completely new data members and member methods, the programmer can designate
that the new class should inherit the members of an existing class.
 The idea of inheritance implements the “is a” relationship. For example, mammal IS-A animal, dog IS-A
mammal hence dog IS-A animal as well and so on.
 Inheritance lets us organize related classes into ordered levels of functionality, called hierarchies. The
advantage is that we write the common code only once and reuse it in multiple classes.
 A subclass inherits methods and fields of its superclass. A subclass can have only one direct superclass, but
many subclasses can inherit from a common superclass.
 Inheritance implements the “is a” relationship between classes. Any object of a subclass is also an object of the
superclass.
 All classes inherit from the Object class.
 To specify that a subclass inherits from a superclass, the subclass uses the extends keyword in the class
definition, as in the following syntax:
AccessModifier class CassName extends SuperClassName
 A subclass does not inherit constructors or private members of the superclass. However, the superclass
constructors are still available to be called from the subclass, and the private fields of the superclass are
implemented as fields of the subclass.
 To access private fields of the superclass, the subclass needs to use the methods provided by the superclass.
 To call the constructor of the superclass, the subclass constructor uses the following syntax:
super ( argument list );
 If used, this statement must be the first statement in the subclass constructor.
 A subclass can override an inherited method by providing a new version of the method. The new method’s API
must be identical to the inherited method. To call the inherited version of the method, the subclass uses the
super object reference using the following syntax:
super.methodName ( argument list );
 Any field declared using the protected access modifier is inherited by the subclass. As such, the subclass can
directly access the field without calling its method.
 In Multilevel Inheritance, a subclass will be inheriting a superclass and as well as the subclass also act as the
superclass to other class. In below image, the class A serves as a superclass for the subclass B, which in turn
serves as a superclass for the subclass C. In Java, a class cannot directly access the grandparent’s members.

Course Instructor: Nazish Basir Page: 7/13


Institute of Information and Communication Technology, University of Sindh.
LECTURE NOTES AND LAB HANDOUTS
OBJECT OREINTED PROGRAMMING (ITEC / SENG – 321 ) WEEK. 7

PROGRAM 8: A simple example of inheritance.

// Create a superclass.
class A {
int i, j;
void showij() {
System.out.println("i and j: " + i + " " + j);
}
}

// Create a subclass by extending class A.


class B extends A {
int k;
void showk() {
System.out.println("k: " + k);
}
void sum() {
System.out.println("i+j+k: " + (i+j+k));
}
}

PROGRAM 8: This program uses inheritance to extend Box


class Box {
double width;
double height;
double depth;

// construct clone of an object


Box(Box ob) { // pass object to constructor
width = ob.width;
height = ob.height;
depth = ob.depth;
}

// constructor used when all dimensions specified


Box(double width, double height, double depth) {
this.width = width;
this.height = height;
this.depth = depth;
}

// constructor used when no dimensions specified


Box() {
width = -1; // use -1 to indicate
height = -1; // an uninitialized
depth = -1; // box
}

Course Instructor: Nazish Basir Page: 8/13


Institute of Information and Communication Technology, University of Sindh.
LECTURE NOTES AND LAB HANDOUTS
OBJECT OREINTED PROGRAMMING (ITEC / SENG – 321 ) WEEK. 7

// constructor used when cube is created


Box(double len) {
width = height = depth = len;
}

// compute and return volume


double volume() {
return width * height * depth;
}
}

// Here, Box is extended to include weight.


class BoxWeight extends Box {
double weight; // weight of box

// constructor for BoxWeight


BoxWeight(double w, double h, double d, double m) {
width = w;
height = h;
depth = d;
weight = m;
}
}

class DemoBoxWeight {
public static void main(String args[]) {

BoxWeight mybox1 = new BoxWeight(10, 20, 15, 34.3);


BoxWeight mybox2 = new BoxWeight(2, 3, 4, 0.076);

double vol;

vol = mybox1.volume();

System.out.println("Volume of mybox1 is " + vol);


System.out.println("Weight of mybox1 is " + mybox1.weight);
System.out.println();

vol = mybox2.volume();

System.out.println("Volume of mybox2 is " + vol);


System.out.println("Weight of mybox2 is " + mybox2.weight);
}
}

Course Instructor: Nazish Basir Page: 9/13


Institute of Information and Communication Technology, University of Sindh.
LECTURE NOTES AND LAB HANDOUTS
OBJECT OREINTED PROGRAMMING (ITEC / SENG – 321 ) WEEK. 7

PROGRAM 9: Demonstrate super

class A {
int i;
}
class B extends A {
int i;

B(int a, int b) {
super.i = a;
i = b;
}
void show() {
System.out.println("i in superclass: " + super.i);
System.out.println("i in subclass: " + i);
}
}

class UseSuper {
public static void main(String args[]) {
B subOb = new B(1, 2);
subOb.show();
}
}

PROGRAM 10: Using super to overcome name hiding.

class A {
int i;
}

// Create a subclass by extending class A.


class B extends A {
int i; // this i hides the i in A
B(int a, int b) {
super.i = a; // i in A
i = b; // i in B
}
void show() {
System.out.println("i in superclass: " + super.i);
System.out.println("i in subclass: " + i);
}
}

class UseSuper {
public static void main(String args[]) {
B subOb = new B(1, 2);
subOb.show();
}
}

Course Instructor: Nazish Basir Page: 10/13


Institute of Information and Communication Technology, University of Sindh.
LECTURE NOTES AND LAB HANDOUTS
OBJECT OREINTED PROGRAMMING (ITEC / SENG – 321 ) WEEK. 7

PROGRAM 12: Demonstrate Multi-level inheritance

// Start with Box.


class Box {
private double width;
private double height;
private double depth;

// construct clone of an object


Box(Box ob) { // pass object to constructor
width = ob.width;
height = ob.height;
depth = ob.depth;
}

// constructor used when all dimensions specified


Box(double w, double h, double d) {
width = w;
height = h;
depth = d;
}

// constructor used when no dimensions specified


Box() {
width = -1; // use -1 to indicate
height = -1; // an uninitialized
depth = -1; // box
}

// constructor used when cube is created


Box(double len) {
width = height = depth = len;
}

// compute and return volume


double volume() {
return width * height * depth;
}
}

// Add weight.
class BoxWeight extends Box {
double weight; // weight of box

// construct clone of an object


BoxWeight(BoxWeight ob) { // pass object to constructor
super(ob);
weight = ob.weight;
}

Course Instructor: Nazish Basir Page: 11/13


Institute of Information and Communication Technology, University of Sindh.
LECTURE NOTES AND LAB HANDOUTS
OBJECT OREINTED PROGRAMMING (ITEC / SENG – 321 ) WEEK. 7

// constructor when all parameters are specified


BoxWeight(double w, double h, double d, double m) {
super(w, h, d); // call superclass constructor
weight = m;
}

// default constructor
BoxWeight() {
super();
weight = -1;
}

// constructor used when cube is created


BoxWeight(double len, double m) {
super(len);
weight = m;
}
}

// Add shipping costs.


class Shipment extends BoxWeight {
double cost;

// construct clone of an object


Shipment(Shipment ob) { // pass object to constructor
super(ob);
cost = ob.cost;
}

// constructor when all parameters are specified


Shipment(double w, double h, double d,
double m, double c) {
super(w, h, d, m); // call superclass constructor
cost = c;
}

// default constructor
Shipment() {
super();
cost = -1;
}

// constructor used when cube is created


Shipment(double len, double m, double c) {
super(len, m);
cost = c;
}
}

Course Instructor: Nazish Basir Page: 12/13


Institute of Information and Communication Technology, University of Sindh.
LECTURE NOTES AND LAB HANDOUTS
OBJECT OREINTED PROGRAMMING (ITEC / SENG – 321 ) WEEK. 7

class DemoShipment {
public static void main(String args[]) {
Shipment shipment1 =
new Shipment(10, 20, 15, 10, 3.41);
Shipment shipment2 =
new Shipment(2, 3, 4, 0.76, 1.28);
double vol;
vol = shipment1.volume();
System.out.println("Volume of shipment1 is " + vol);
System.out.println("Weight of shipment1 is "
+ shipment1.weight);
System.out.println("Shipping cost: $" + shipment1.cost);
System.out.println();
vol = shipment2.volume();
System.out.println("Volume of shipment2 is " + vol);
System.out.println("Weight of shipment2 is "
+ shipment2.weight);
System.out.println("Shipping cost: $" + shipment2.cost);
}
}

PROGRAM 13: Demonstrate order of constructor call

class A {
A() {
System.out.println("Inside A's constructor.");
}
}

class B extends A {
B() {
System.out.println("Inside B's constructor.");
}
}

class C extends B {
C() {
System.out.println("Inside C's constructor.");
}
}

class CallingCons {
public static void main(String args[]) {
C c = new C();
}
}

Course Instructor: Nazish Basir Page: 13/13


Institute of Information and Communication Technology, University of Sindh.

You might also like