COMP2111
:
Object Oriented
Programming
Fall 2018
1. Access Control
2. Nested Classes
3. String
Please turn OFF your Mobile Phones!
9/22/20
Ansif Arooj
19
/2
2/
2
•
By default the class, variable, or data can be accessible
by any class. you can control what parts of a program
can access the members of a class. By controlling
access, you can prevent misuse.
•
For example, allowing access to data only through a well
defined set of methods, you can prevent the misuse of
that data.
•
Thus, when correctly implemented, a class creates a
“black box”
which may be used, but the inner workings
of which are not open to tampering.
•
However, the classes that were presented earlier do not
completely meet this goal.
Visibility Modifiers and Accessor Methods
•
By default, the class, variable, or data can be accessed by
any class in the same package.
• public
•
The class, data, or method is visible to any class in any
package.
• private
•
The data or methods can be accessed only by the
declaring class.
•
The getter and setter accessor methods are used
Access Level
Access Levels
Modifier Class Package Subclass World
public Y Y Y Y
protected Y Y Y N
no modifier Y Y N N
private Y N N N
/* This program demonstrates the difference
between public and private.*/
class Test {
int a; // default access
public
int b; // public access
private
int c; // private access
// methods to access c
void setc(int i) { // set c's value
c = i; }
class AccessTest {
public static void main(String args[]) { Test ob = new Test();
// These are OK, a and b may be accessed directly ob.a = 10;
ob.b = 20;
// This is not OK and will cause an error
// ob.c = 100; // Error!
// You must access c through its methods ob.setc(100); // OK
System.out.println("a, b, and c: " + ob.a + " " + ob.b + " " + ob.getc()); } }
Using Static
•
There will be times when you will want to define a class
member that will be used
independently
of any object of
that class.
•
Normally, a class member must be accessed only in
combination with an object of its class. However, it is
possible to create a member that can be used by itself,
without reference to a specific instance.
•
To create such a member, 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.
• You can declare both methods and variables to be static. The
most common example of a static member is
main( ).
• main( ) is declared as static because it must be called before any
objects exist.
• Instance variables declared as static are, essentially, global variables. When objects of its class are declared, no copy of a
static variable is made.
• Instead, all instances of the class share the same static variable. • Methods declared as static have several restrictions:
• They can only call other static methods. • They must only access static data.
// Demonstrate static variables, methods, and blocks. class UseStatic {
static int a = 3; static int b;
static void meth(int x) {
System.out.println("x = " + x); System.out.println("a = " + a); System.out.println("b = " + b);} static {
System.out.println("Static block initialized."); b = a * 4; }
public static void main(String args[]) { meth(42);}}
• Here is the output of the program:
Static block initialized. x = 42
a = 3 b = 12
Introducing Nested and Inner Classes
•
It is possible to define a class within another
class; such classes are known as
nested classes
.
•
The scope of a nested class is bounded by the
scope of its enclosing class.
•
Thus, if class B is defined within class A, then B does
not exist independently of A.
•
A nested class has access to the members,
including
private members
, of the class in which
it is nested. However, the enclosing class does
not have access to the members of the nested
class.
•
There are two types of nested classes:
1)
Static
2)
N
on-static
•
A
static nested class
is one that has the
static
modifier
applied. Because it is static, it must access the members
of its enclosing class through an object. That is, it cannot
refer to members of its enclosing class directly. Because
of this restriction, static nested classes are seldom used.
•
The most important type of nested class is the
inner
class. An inner class is a
non-static nested class
. It has
access to all of the variables and methods of its outer
// Demonstrate an inner class. class Outer {
int outer_x = 100; void test() {
Inner inner = new Inner(); inner.display(); }
// this is an inner class class Inner {
void display() {
System.out.println("display: outer_x = " + outer_x);}}} class InnerClassDemo {
public static void main(String args[]) { Outer outer = new Outer();
outer.test();}
}Output from this application is shown here:
display: outer_x = 100
Intro to String
• What is a string in Java?
Strings in Java are represented as objects. • What is a string literal?
Java considers a series of characters surrounded by
quotation marks to be a string literal or string constant. In the following example ‘s’ is a string literal.
String s = "This is a string literal in Java “
• How to create String Objects?
String str1 = new String("String named str2"); String str2 = “Hello Pakistan";
9
/2
2/
2
0
Cont..
• String concatenation in Java
String cat = "cat";
System.out.println("con" + cat + "enation");
9
/2
2/
2
You Can't Modify a String Object, but
You Can Replace It
• Objects of type String are immutable;
• Once a String object is created, its contents cannot be altered. • If you need to change a string, you can always create a new
one that contains the modifications.
• Java defines a peer class of String, called StringBuffer,
which allows strings to be altered, so all of the normal string manipulations are still available in Java.
String myString = "this is a test";
• Once you have created a String object, you can use it anywhere that a string is allowed.
• For example, this statement displays myString:
// Demonstrating Strings.
class StringDemo {
public static void main(String args[]) { String strOb1 = "First String";
String strOb2 = "Second String";
String strOb3 = strOb1 + " and " + strOb2; System.out.println(strOb1);
System.out.println(strOb2); System.out.println(strOb3); }}
The output produced by this program is shown here: First String
Demonstration
9
/2
2/
2
0
String Methods
• The String class contains several methods that you can use. Here are a few. You can test two strings for equality by using
equals( ).
• You can obtain the length of a string by calling • the length( ) method.
• You can obtain the character at a specified index within a string by calling charAt( ).
• The general forms of these three methods are shown here:
•
boolean equals(String
object
)
•
int length( )
9
/2
2/
2
Comparing String
• Remember
– everything is a reference (except primitives)
• = =
– Compares references only! (shallow comparison)
– Does
not
compare what is pointed to by the pointers
• equals() method
– Default implementation same as ==
– String class overrides to do a deep comparison, i.e. comparison of characters.
9
/2
2/
2
0
// Demonstrating some String methods. class StringDemo2 {
public static void main(String args[]) { String strOb1 = "First String";
String strOb2 = "Second String"; String strOb3 = strOb1;
System.out.println("Length of strOb1: " + strOb1.length());
System.out.println("Char at index 3 in strOb1: " + strOb1.charAt(3)); if(strOb1.equals(strOb2))
System.out.println("strOb1 == strOb2"); else
System.out.println("strOb1 != strOb2");
if(strOb1.equals(strOb3))
Constructors and Methods of the
String Class
String Class // Constructors
public String();
// Methods
public char charAt(int index); public String concat(String str);
public boolean equals(Object anObject);
public boolean equalsIgnoreCase(String anotherString); public String substring(int beginIndex);
public String substring(int beginIndex, int endIndex); public String toLowerCase();
public String toUpperCase();
public String[] split(String regex)
The Sample Program
public class StringMethodsApp {
public static void main (String args[]) { String str1 = "Hello World";
String str2 = new String("Pakistan"); char c = str1.charAt(0);
System.out.println("char of str1 at 0 index: " + c); System.out.println();
String conByMethod = str1.concat(str2); String conByOperator = str1 + str2;
System.out.println("concatenate by method: " + conByMethod); System.out.println("concatenate by method: " + conByOperator); System.out.println();
System.out.println( "comapring strings"); if (str2 == "Paksitan") {
System.out.println("strings equal using =="); } if (str2.equals("Pakistan")) {
System.out.println("strings equal using equals method"); } System.out.println();
String sub = str1.substring(5);
Output
9
/2
2/
2
0
Converting Strings to Numeric Primitive
Data Types
• list of methods
9
/2
2/
2
class ConvertStringTest{
public static void main(String[] args){ String intString = "20";
String doubleString = "35.573";
//converting string into int using parseInt method
System.out.println(“converting string into int”); int num1 = Integer.parseInt (intString);
System.out.println(num1);
//converting string into int using intValue method
int num2 = new Integer(intString).intValue();
System.out.println(num2);
//converting string into double using parseDouble method
System.out.println(“converting string into double”); double double1 = Double.parseDouble (doubleString); System.out.println(double1);
//converting string into double using doubleValue method
double double2 = new Double(doubleString).doubleValue();
System.out.println(double2); } }
Output
9
/2
2/
2
String Arrays
• Declaring and instantiating a String array
String[] stringOfReferences = new String[3]; • Allocating memory to contain the String objects
stringOfReferences[0] = new String("This is the first string."); stringOfReferences[1] = new String("This is the second string."); stringOfReferences[2] = "This is the third string.";
9
/2
2/
2
0
String Arrays
// Demonstrate String arrays. class StringDemo3 {
public static void main(String args[]) { String str[] = { "one", "two", "three" }; for(int i=0; i<str.length; i++)
System.out.println("str[" + i + "]: " + str[i]); }
}
9
/2
2/
2
split method of the String
Class
public class TokensTest {
public static void main (String args[ ]) { String str1 = “this is test”;
Strign str2 = “web design, development”;
System.out.println(“tokenizing string using space”);
String tokens1[] = str1.split(“ ”);
System.out.println(“first token: ” + tokens[0]); System.out.println(“second token: ” + tokens[1]); System.out.println(“third token: ” + tokens[2]); System.out.println();
System.out.println(“tokenizing string using comma”); String tokens1[] = str1.split(“,”);
System.out.println(“first token: ” + tokens[0]);
System.out.println(“second token: ” + tokens[1]); } }
Output
9
/2
2/
2
Command Line Arguments
• A command-line argument is the information that directly follows the program’s name on the command line when it is executed.
• We can pass command-line arguments to main( ).
• To access the command-line arguments inside a Java program we have to stored as strings in a String array passed to the
args parameter of main( ).
• The first command-line argument is stored at args[0], the second at args[1], and so on.
9
/2
2/
2
0
// Display all command-line arguments. class CommandLine {
public static void main(String args[]) { for(int i=0; i<args.length; i++)
System.out.println("args[" + i + "]: " + args[i]); }
}
9
/2
2/
2
References
• “Object Oriented Programming in C++”, by “Robert Lafore”,
published by Sams Publishing (The Waite Group). 4th ed. available
in soft form.
• “Object Oriented Programming Using C++” by “Joyce Farrell” ,
published by Course Technology, Cengage Learning
.
4th ed. availablein soft form
• National University of Computer & Emerging Sciences [www.nu.edu.pk]
• Virtual University of Pakistan [ocw.vu.edu.pk] • Open Courseware Consortium
[http://www.ocwconsortium.org/en/courses]
37
9
/2
2/
2