Title: Part II: Strings
1Part II Strings
- String Literals
- Creating Strings
- String Length
- Concatenating Strings
- String Conversion
- Escape Sequences
2Strings
- Strings, which are widely used in Java
programming, are a sequence of characters. In the
Java programming language, strings are objects.
3String Literals
- The following are examples of string literals
- "" // the empty string
- "\"" // a string containing "
alone - "This is a string" // a string containing
16 characters - "This is a " // actually a constant
expression, - "two-line string // formed from two
string literals
4Creating Strings
- The most direct way to create a string is to
write - String greeting "Hello world!"
- In this case, "Hello world!" is a string
literala series of characters in your code that
is enclosed in double quotes. - Whenever it encounters a string literal in your
code, the compiler creates a String object with
its value.
5Creating Strings
- As with any other object, you can create String
objects by using the new keyword and a
constructor. The String class has 11 constructors
that allow you to provide the initial value of
the string using different sources, such as an
array of characters - char helloArray 'h', 'e', 'l', 'l',
'o', '.' - String helloString new String(helloArray)
- System.out.println(helloString)
6Creating Strings
- Note The String class is immutable, so that once
it is created a String object cannot be changed. - The String class has a number of methods, that
appear to modify strings. Since strings are
immutable, what these methods really do is create
and return a new string that contains the result
of the operation.
7String Length
- Methods used to obtain information about an
object are known as accessor methods. - length is an accessor method, returns the number
of characters in string. - String str "Hello world!"
- int str str.length()
8Concatenating Strings
// using concat method of an // instantiated
string string1.concat(string2) // using
concat method of an implicitly // created string
"Something is here ".concat("and here.") //
using operator "Hello," " world" "!"
9Concatenating Strings
- Note The Java programming language does not
permit literal strings to span lines in source
files, so you must use the concatenation
operator at the end of each line in a multi-line
string. - For example
- String quote "Now is the time for all good
" - "men to come to the aid of their country."
10String Conversion
- If only one operand expression is of type String,
then string conversion is performed on the other
operand to produce a string at run time. - The result is a reference to a String object
(newly created, unless the expression is a
compile-time constant expression) that is the
concatenation of the two operand strings. The
characters of the left-hand operand precede the
characters of the right-hand operand in the newly
created string. - Any type may be converted to type String by
string conversion.
11String Conversion
- A value x of primitive type T is first converted
to a reference value as if by giving it as an
argument to an appropriate class instance
creation expression - If T is boolean, then use new Boolean(x).
- If T is char, then use new Character(x).
- If T is byte, short, or int, then use new
Integer(x). - etc
- This reference value is then converted to type
String by string conversion.
12String Conversion
- The example expression
- "The square root of 2 is " Math.sqrt(2)
- produces the result
- "The square root of 2 is 1.4142135623730952"
- The operator is syntactically left-associative,
no matter whether it is later determined by type
analysis to represent string concatenation or
addition. In some cases care is required to get
the desired result.
13String Conversion
- For example, the expression
- a b c
- is always regarded as meaning
- (a b) c
- Therefore the result of the expression
- 1 2 " fiddlers"
- is
- "3 fiddlers
- but the result of
- "fiddlers " 1 2
- is
- "fiddlers 12"
14Escape Sequences
\b / \u0008 backspace BS / \t /
\u0009 horizontal tab HT / \n / \u000a
linefeed LF / \f / \u000c form feed FF
/ \r / \u000d carriage return CR / \ /
\u0022 double quote / \ / \u0027
single quote / \\ / \u005c backslash
\ /
15PartIIIMore OOP
1.Inheritance 2.Applications of
inheritance 3.Subclassing 4.Abstract
classes 5.Interface
16Inheritance
- In the Java language, classes can be derived from
other classes, thereby inheriting fields and
methods from those classes. - Moreover, inheritance is also called
generalization, because the is-a relationships
capture a hierarchical relationship between
classes of objects. - For instance a "fruit" is a generalization of
"apple", "orange", "mango" and many others. We
say that fruit is an abstraction of apple,
orange, etc. Conversely, we can say that since
apples are fruit (i.e. an apple is-a fruit), that
they inherit all the properties common to all
fruit, such as being a fleshy container for the
seed of a plant.
17Applications of inheritance
- Specialization
- A common reason to use inheritance is to create
specializations of existing classes or objects.
This is often called subtyping when applied to
classes. - Overriding
- Many object-oriented programming languages permit
a class or object to replace the implementation
of an aspecttypically a behaviorthat it has
inherited. This process is usually called
overriding.
18Applications of inheritance
- Extension
- Another reason to use inheritance is to provide
additional data or behavior features. This
practice is sometimes called extension or
subclassing. - Code re-use
- One of the earliest motivations for using
inheritance was to allow a new class to re-use
code which already existed in another class. This
practice is usually called implementation
inheritance.
19Subclasses and superclasses
- Classes are often related in some way. The most
popular of these relations is inheritance, which
involves subclasses and superclasses, also known
respectively as child classes (or derived
classes) and parent classes (or base classes). - Example If Car was a class, then Jaguar and
Porsche might be two sub-classes. - If Button is a subclass of Control, then all
buttons are controls. - Subclasses usually consists of several kinds of
modifications (customizations) to their
respective superclasses addition of new instance
variables, addition of new methods and overriding
of existing methods to support the new instance
variables.
20Subclasses and superclasses
- Excepting Object, which has no superclass, every
class has one and only one direct superclass
(single inheritance). In the absence of any other
explicit superclass, every class is implicitly a
subclass of Object.
21Subclasses and superclasses
- Conceptually, a superclass should be considered
as a common part of its subclasses. This
factoring of commonality is one mechanism for
providing reuse. Thus, extending a superclass by
modifying the existing class is also likely to
narrow its applicability in various situations.
22Subclassing
- A subclass inherits all of the public and
protected members of its parent, no matter what
package the subclass is in. - Subclassing fields
- The inherited fields can be used directly, just
like any other fields. - You can declare a field in the subclass with the
same name as the one in the superclass, thus
hiding it (not recommended). - You can declare new fields in the subclass that
are not in the superclass.
23Subclassing
- Subclassing methods
- The inherited methods can be used directly as
they are. - You can write a new instance method in the
subclass that has the same signature as the one
in the superclass, thus overriding it. - You can write a new static method in the subclass
that has the same signature as the one in the
superclass, thus hiding it. - You can declare new methods in the subclass that
are not in the superclass. - You can write a subclass constructor that invokes
the constructor of the superclass, either
implicitly or by using the keyword super.
24Private Members in a Superclass
- A subclass does not inherit the private members
of its parent class. However, if the superclass
has public or protected methods for accessing its
private fields, these can also be used by the
subclass. - A nested class has access to all the private
members of its enclosing classboth fields and
methods. Therefore, a public or protected nested
class inherited by a subclass has indirect access
to all of the private members of the superclass.
25Casting Objects
- public class Animal ...
- public class Dog extends Animal ...
- ...
- Dog puppy new Dog()
- Animal animal1 (Animal)puppy
- Note If you need to cast-back an object, you can
make a logical test as to the type of a
particular object using the instanceof operator.
This can save you from a runtime error owing to
an improper cast - if (animal1 instanceof Dog)
- Dog dog1 (Dog)animal1
-
26Abstract and concrete classes
- An abstract class, or abstract base class, is one
that is designed only as a parent class and from
which child classes may be derived, and which is
not itself suitable for instantiation. - Abstract classes are often used to represent
abstract concepts or entities. The incomplete
features of the abstract class are then shared by
a group of sibling sub-classes which add
different variations of the missing pieces.
27Interface
- An interface in the Java programming language is
an abstract type which is used to specify an
interface (in the generic sense) that classes
must implement. Interfaces are introduced with
the interface keyword, and may only contain
function signatures and constant declarations. - As interfaces are abstract, they cannot be
instantiated. Object references in Java may be
specified to be of interface type in which case
they must be bound to null, or an object which
implements the interface.
28Interface
- The primary capability which interfaces have, and
classes lack, is multiple inheritance. All
classes in Java must have exactly one base class
multiple inheritance of classes is not allowed. - However, Java classes may implement as many
interfaces as the programmer desires (with the
implements clause). - A Java class which implements an interface, but
which fails to implement all the methods
specified in the interface, becomes an abstract
base class, and must be declared abstract in the
class definition.
29Interface
visibility interface InterfaceName extends
other interfaces constant
declarations abstract method
declarations ... implements interface name,
another interface, another, ... ...
30Interface
- Casting objects that are implement an interface
(interface as a data type) - When you define a new interface, you are defining
a new reference data type. If you define a
reference variable whose type is an interface,
any object you assign to it must be an instance
of a class that implements the interface.
31Interface
Interface definition public interface Shape
extends Interface1,
Interface2, Interface3 //
method signatures public void Draw()
public void SetSize(String s)
32Interface
public class Box implements Shape ... public
class Circle implements Shape ... public class
Triangle implements Shape ... ... Shape a1
new Box() Shape a2 new Triangle() Shape a3
new Circle() ... a1.Draw() a2.Draw() a3.Draw()
33Interface
- Rewriting interfaces may cause serious problems
in the architecture of an application. - Consider an interface that you have developed
called DoIt - public interface DoIt
- void doSomething(int i, double x)
- int doSomethingElse(String s)
-
- Suppose that, at a later time, you want to add a
third method to DoIt, so that the interface now
becomes - public interface DoIt
- void doSomething(int i, double x)
- int doSomethingElse(String s)
- boolean didItWork(int i, double x, String
s) -
34Interface
- If you make this change, all classes that
implement the old DoIt interface will break
because they don't implement the interface
anymore. Programmers relying on this interface
will protest loudly. - Try to anticipate all uses for your interface and
to specify it completely from the beginning.
Given that this is often impossible, you may need
to create more interfaces later. For example, you
could create a DoItPlus interface that extends
DoIt - public interface DoItPlus extends DoIt
- boolean didItWork(int i, double x, String s)