Uploaded by Maleeha Shah

Lab 03

advertisement
DHA SUFFA UNIVERSITY
Department of Computer Science
CS-1002L
Object Oriented Programming
Spring 2021
LAB 03
Introduction to OOP
Objectives
● To learn about classes, objects, constructors, static fields, static methods scanner class,
and this keyword.
Introduction to OOP:
Object-oriented programming System(OOPs) is a programming paradigm based on the concept
of “objects” that contain data and methods. The primary purpose of object-oriented
programming is to increase the flexibility and maintainability of programs. Object oriented
programming brings together data and its behaviour(methods) in a single location(object) and
makes it easier to understand how a program works. In object-oriented programming technique,
programs are designed using objects and classes. Java is an object-oriented programming
language. Everything in Java is associated with classes and objects, along with its attributes and
methods.
Class
A class is the building block of OOP. It is the prototype that defines methods and variables that
are common to all specified types of objects. It is the way to bind the data and its logically related
functions together. It's a non-primitive data type that can be treated like any other built-in data
type.
A class is a group of objects which have common properties. A Class is like an object constructor,
or a "blueprint" for creating objects. It is a template or blueprint from which objects are created.
It is a logical entity. It can't be physical.A class can be considered as a blueprint using which you
can create as many objects as you like. Data members are also known as fields, instance variables
and object states.
When you define a class, you declare its exact form and nature. You do this by specifying the
instance variables that it contains and the methods that operate on them. Although very simple
classes might contain only methods or only instance variables, most real-world classes contain
both. A class is created by using the keyword class. In general, class declarations can include these
components, in order:
● Modifiers: A class can be public or has default access. (Discuss in future Lab)
DHA SUFFA UNIVERSITY
Department of Computer Science
CS-1002L
Object Oriented Programming
Spring 2021
● class keyword: class keyword is used to create a class.
● Class name: The name should begin with an initial letter (capitalized by convention).
● Superclass(if any): The name of the class’s parent (superclass), if any, preceded by the
keyword extends. A class can only extend (subclass) one parent. (Discuss in future Lab)
● Interfaces(if any): A comma-separated list of interfaces implemented by the class, if
any, preceded by the keyword implements. A class can implement more than one
interface. (Discuss in future Lab)
● Body: The class body surrounded by braces, { }.
The general form of a class definition is shown below.
Syntax
//Syntax of a class
public class classname
{
// declare instance variables
type var1;
type var2;
//…
type varN;
// declare methods
type method1(parameters)
{ // body of method }
type method2(parameters)
{ // body of method }
//…
type methodN(parameters)
{ // body of method }
}
Example 3.1
//FileName:cellPhone.java
//Defining class
public class CellPhone
{
DHA SUFFA UNIVERSITY
Department of Computer Science
CS-1002L
Object Oriented Programming
Spring 2021
//Declaring instance variables
string name ;
string processor;
string memory;
string os ;
//Declaring and Defining member function
void display()
{
system.out.println("\====Displaying Phone Information====\n");
system.out.println("Device Name = " +name);
system.out.println("Processor = " +processor);
system.out.println("Memory = “ +memory);
system.out.println("OS = " +os);
}
}
Object:
A class provides the blueprints for objects. So basically, an object is created from a class. In Java,
the new keyword is used to create new objects. It is used to allocate memory at runtime. The
new operator also invokes the class constructor. All objects get memory in the Heap memory
area.
There are three steps when creating an object from a class −
● Declaration − A variable declaration with a variable name with an object type.
● Instantiation − The 'new' keyword is used to create the object.
● Initialization − The 'new' keyword is followed by a call to a constructor. This call initializes
the new object.
We have already created the class named CellPhone, so now we can use this to create objects.
To create an object of CellPhone, specify the class name, followed by the object name, and use
the keyword new:
Syntax
public static void main(String[] args) {
ClassName ObjectName = new Constructor();
}
DHA SUFFA UNIVERSITY
Department of Computer Science
CS-1002L
Object Oriented Programming
Spring 2021
Creating an object of CellPhone class
syntax
public static void main(String[] args) {
CellPhone myObj = new CellPhone();
}
Calling member function through an object
Syntax
//syntax of calling member function of a class through an object
objectName.member_function;
Calling display function of CellPhone class
Syntax
myObj.display();
Constructor:
When discussing classes, one of the most important sub topic would be constructors. Every class
has a constructor. If we do not explicitly write a constructor for a class, the Java compiler builds
a default constructor for that class.
A constructor in Java is a special method that is used to initialize objects. The constructor is
called when an object of a class is created. It can be used to set initial values for object attributes
Each time a new object is created, at least one constructor will be invoked. The main rule of
constructors is that they should have the same name as the class. A class can have more than
one constructor.
Types of Java constructors
There are two types of constructors in Java:
1. Default constructor
2. Non-Parameterized (no-arg constructor)
3. Parameterized constructor
DHA SUFFA UNIVERSITY
Department of Computer Science
CS-1002L
Object Oriented Programming
Spring 2021
Default constructor
If you do not implement any constructor in your class, Java compiler inserts a default
constructor into your code on your behalf. This constructor is known as default constructor.
You would not find it in your source code (the java file) as it would be inserted into the code
during compilation and exists in .class file.
Example 3.2
Lets see the example of the default constructor that displays the default values.
Here, we are creating a main() method inside the class.
Output:
DHA SUFFA UNIVERSITY
Department of Computer Science
CS-1002L
Object Oriented Programming
Spring 2021
In the above class, you are not creating any constructor so the compiler provides you a default
constructor. Here 0 and null values are provided by default constructor.
Non-Parameterized constructor
Constructor that do not take any arguments are non-Parameterized constructors.
Syntax
public class ClassName
{
//Syntax of creating a non-parameterized constructor
className()
{
}
};
In this example, we are creating the no-arg constructor in the CellPhone class. It will be invoked
at the time of object creation.
Example 3.3
DHA SUFFA UNIVERSITY
Department of Computer Science
CS-1002L
Object Oriented Programming
Spring 2021
Output:
Parameterized constructor
Constructor that take arguments are Parameterized constructors.
Syntax
class className
{
//Syntax of creating a parameterized constructor
className( datatype )
{
}
};
Example 3. 4
DHA SUFFA UNIVERSITY
Department of Computer Science
CS-1002L
Object Oriented Programming
Spring 2021
Output:
Static Keyword:
The static keyword in Java is used for memory management mainly. Static is a non-access
modifier in Java which is applicable for the following:
1. blocks
2. variables
3. methods
4. nested classes
To create a static member(block,variable,method,nested class), precede its declaration with the
keyword static. When a member is declared static, it can be accessed before any objects of its
class are created, and without reference to any object. Static members belong to the class instead
of a specific instance, this means if you make a member static, you can access it without object.
DHA SUFFA UNIVERSITY
Department of Computer Science
CS-1002L
Object Oriented Programming
Spring 2021
Static members are common for all the instances(objects) of the class but non-static members
are separate for each instance of class.
Restrictions for the static method
There are two main restrictions for the static method. They are:
1. The static method can not use non-static data members or call non-static methods
directly.
2. this and super cannot be used in static context.
Static Variable:
A static variable is common to all the instances (or objects) of the class because it is a class level
variable. In other words you can say that only a single copy of a static variable is created and
shared among all the instances of the class. Memory allocation for such variables only happens
once when the class is loaded in the memory. Static block and static variables are executed in
order they are present in a program.
● Static variables are also known as Class Variables.
● Unlike non-static variables, such variables can be accessed directly in static and non-static
methods.
● The static variable can be used to refer to the common property of all objects (which is
not unique for each object), for example, the company name of employees, college name
of students, etc.
Example 3.5
DHA SUFFA UNIVERSITY
Department of Computer Science
CS-1002L
Object Oriented Programming
Spring 2021
Output:
Static Methods:
Static Methods can access class variables(static variables) without using object(instance) of the
class, however non-static methods and non-static variables can only be accessed using objects.
Static methods can be accessed directly in static and non-static methods.If you apply static
keyword with any method, it is known as static method. A static method can access a static data
member and can change the value of it.
Example 3.6
DHA SUFFA UNIVERSITY
Department of Computer Science
CS-1002L
Object Oriented Programming
Spring 2021
Output:
Static Block:
Static block is used for initializing the static variables.This block gets executed when the class is
loaded in the memory. It means that it is executed before the main method at the time of
classloading. A class can have multiple Static blocks, which will execute in the same sequence in
which they have been written into the program.
Example 3.7
Output:
DHA SUFFA UNIVERSITY
Department of Computer Science
CS-1002L
Object Oriented Programming
Spring 2021
Static Class
A class can be made static only if it is a nested class. Nested static class doesn’t need reference
of Outer class A static class cannot access non-static members of the Outer class.
We will see examples of static class when we study the concept of nested class.
Lets see example of Static Members( static variables, methods and blocks)
Example 3.8
DHA SUFFA UNIVERSITY
Department of Computer Science
CS-1002L
Object Oriented Programming
Spring 2021
Output:
Java Scanner Class
Java Scanner class allows the user to take input from the console. It belongs to the java.util
package. It is used to read the input of primitive types like int, double, long, short, float, and
byte. It is the easiest way to read input in a Java program.
Syntax
Scanner sc=new Scanner(System.in);
The above statement creates a constructor of the Scanner class having System.in as an
argument. It means it is going to read from the standard input stream of the program. The
java.util package should be imported while using Scanner class.
It also converts the Bytes (from the input stream) into characters using the platform's default
charset.
Methods of Java Scanner Class
Java Scanner class provides the following methods to read different primitives types:
Method
Description
int nextInt()
It is used to scan the next token of the input as an integer.
float nextFloat()
It is used to scan the next token of the input as a float.
DHA SUFFA UNIVERSITY
Department of Computer Science
CS-1002L
Object Oriented Programming
Spring 2021
double nextDouble()
It is used to scan the next token of the input as a double.
byte nextByte()
It is used to scan the next token of the input as a byte.
String nextLine()
Advances this scanner past the current line.
boolean nextBoolean()
It is used to scan the next token of the input into a boolean value.
long nextLong()
It is used to scan the next token of the input as a long.
short nextShort()
It is used to scan the next token of the input as a Short.
BigInteger nextBigInteger()
It is used to scan the next token of the input as a BigInteger.
BigDecimal nextBigDecimal()
It is used to scan the next token of the input as a BigDecimal.
Example of integer input from user
The following example allows the user to read an integer form the System.in.
Example 3.9
DHA SUFFA UNIVERSITY
Department of Computer Science
CS-1002L
Object Oriented Programming
Spring 2021
Output:
The nextLine() method of java.util.Scanner class advances this scanner past the current line and
returns the input that was skipped. This function prints the rest of the current line, leaving out
the line separator at the end. The next is set to after the line separator. Since this method
continues to search through the input looking for a line separator, it may search all of the input
searching for the line to skip if no line separators are present.
Below example shows how to solve this issue with nextLine() method:
Example 3.10
DHA SUFFA UNIVERSITY
Department of Computer Science
CS-1002L
Object Oriented Programming
Spring 2021
DHA SUFFA UNIVERSITY
Department of Computer Science
CS-1002L
Object Oriented Programming
Spring 2021
Output:
this keyword:
this is a keyword in Java. It can be used inside the method or constructor of a class. It(this)
works as a reference to the current object, whose method or constructor is being invoked. This
keyword can refer to any member of the current object from within an instance method or a
constructor.
Following are the ways to use ‘this’ keyword in java:
1. Using ‘this’ keyword to refer current class instance variables
Example 3.11
DHA SUFFA UNIVERSITY
Department of Computer Science
CS-1002L
Object Oriented Programming
Spring 2021
Output:
2. Using this() to invoke current class constructor
This example will be discussed in next Lab after studying the concept of constructor
overloading.
3. Using ‘this’ keyword to return the current class instance
Example 3.12
DHA SUFFA UNIVERSITY
Department of Computer Science
CS-1002L
Object Oriented Programming
Spring 2021
Output:
DHA SUFFA UNIVERSITY
Department of Computer Science
CS-1002L
Object Oriented Programming
Spring 2021
4. Using ‘this’ keyword as method parameter
Example 3.13
Output:
DHA SUFFA UNIVERSITY
Department of Computer Science
CS-1002L
Object Oriented Programming
Spring 2021
5. Using ‘this’ keyword to invoke current class method
Example 3.14
Output:
DHA SUFFA UNIVERSITY
Department of Computer Science
CS-1002L
Object Oriented Programming
Spring 2021
6. Using ‘this’ keyword as an argument in the constructor call
Example 3.15
DHA SUFFA UNIVERSITY
Department of Computer Science
CS-1002L
Object Oriented Programming
Spring 2021
Output:
Lab Tasks:
Create a calculator class that will calculate sum, subtraction, product and division of two numbers taken
from the user.
Assignment 03
Problem 01:
Create a class BankAccount whose attributes are: account number, account holder’s name and
balance. BankAccount constructor initializes the values of account number, account holder’s
name and balance. Make one credit function which credits the amount either passed by
arguments or the value entered by the user. Create three accounts for three persons and display
the same on your screen.
Problem 02:
Create a class Author whose attributes are: name, email, gender and books. Author constructor
initializes the values of name, email, gender and books. Define a static variable, method and
block, and use this keyword in your code.
Submission Instructions
●
●
●
●
●
●
Name your Files as P1,P2, etc. ( example : P1.cs)
Name your home assignment as Lab_0X .cs (X is the lab number)
Create a new folder named cs201abc where abc is your 3 digit roll #. e.g. cs201125.
Copy all the task and assignment files into this folder.
Now make a zip file of above made folder named cs201abc.zip is created e.g. cs201125.zip
Upload this zipped folder on LMS under the assignment named Lab 0X_Assignment.
Download