object oriented concepts through java
TRANSCRIPT
-
8/7/2019 Object Oriented Concepts through Java
1/39
Object Oriented ConceptsObject Oriented Concepts
and Programming throughand Programming through
JAVAJAVA
-
8/7/2019 Object Oriented Concepts through Java
2/39
Access SpecifiersAccess Specifiers Javas access specifiers are
public,
private,
Protected and
a default access level.
When a member of a class is specified as public, then that
member can be accessed by any other code.
When a member of a class is specified as private, then that
member can only be accessed by other members of its class.
Thats why main( ) has always been preceded by the public
specifier.
It is called by code that is outside the programthat is, by
the Java run-time system.
-
8/7/2019 Object Oriented Concepts through Java
3/39
Access SpecifiersAccess Specifiers
When no access specifier is used, then by default the
member of a class is public within its own package,
but cannot be accessed outside of its package.
Protected used when inheritance is there. Example
-
8/7/2019 Object Oriented Concepts through Java
4/39
-
8/7/2019 Object Oriented Concepts through Java
5/39
ContCont
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 otherstatic methods.
They must only access static data.
They cannot refer to this or super in any way.
-
8/7/2019 Object Oriented Concepts through Java
6/39
InheritanceInheritance
It allows the creation of hierarchical classifications.
you can create a general class that defines traits or
properties common to a set of related items.
This class can then be inherited by other, more specificclasses, each adding those things that are unique to it.
In the terminology of Java, a class that is inherited is
called a superclass.
The class thatdoes the inheriting is called a subclass. A subclass is a specialized version of a superclass.
It inherits all of the instance variables and methods
defined by the superclass and adds its own, unique
elements.
-
8/7/2019 Object Oriented Concepts through Java
7/39
ContCont
To inherit a class, we incorporate the definition of one class
into another by using the extends keyword.
class A{}
class B extends A{}
Example
Superclass can be used as a complete independent,
stand-alone class.
A subclass can be a superclass for another subclass.
The general form
class subclass-name extends superclass-name {
// body of class
}
-
8/7/2019 Object Oriented Concepts through Java
8/39
Member Access and InheritanceMember Access and Inheritance
A subclass includes all of the members of its
superclass, it cannot access those members
of the superclass that have been declared as
private.
-
8/7/2019 Object Oriented Concepts through Java
9/39
Using super()Using super()
There will be times when you will want to create a
superclass that keeps the details of its implementation
to itself.
That is, that keeps its data members private. Whenever a subclass needs to refer to its immediate
superclass, it can do so by use of the keyword super.
super has two general forms.
The first calls the superclass constructor. The second is used to access a member of the
superclass that has been hidden by a member of a
subclass.
-
8/7/2019 Object Oriented Concepts through Java
10/39
ContCont Using super to Call Superclass Constructors:
super(parameter-list);
super( ) must always be the first statement executed
inside a subclass constructor.
When a subclass calls super( ), it is calling the constructorof its immediate superclass.
Thus, super( ) always refers to the superclass immediately
above the calling class.
A Second Use for super : super.member
This second form ofsuper is most applicable to
situations in which member names of a subclass hide
members by the same name in the superclass.
-
8/7/2019 Object Oriented Concepts through Java
11/39
Constructor calling sequenceConstructor calling sequence
In a class hierarchy, constructors are called in order of
derivation, from superclass to subclass.
Since super( ) must be the first statement executed
in a subclass constructor, this order is the samewhether or not super( ) is used.
If super( ) is not used, then the default or
parameterless constructor of each superclass will be
executed.
-
8/7/2019 Object Oriented Concepts through Java
12/39
Method OverridingMethod Overriding
When a method in a subclass has the same name and type
signature as a method in its superclass, then the method in the
subclass is said to override the method in the superclass.
When an overridden method is called from within a subclass, it
will always refer to the version of that method defined by thesubclass.
If you wish to access the superclass version of an overridden
function, you can do so by using super.
Method overriding occurs only when the names and the type
signatures of the two methods are identical. If they are not, thenthe two methods are simply overloaded.
Overridden methods allow Java to support run-time
polymorphism.
-
8/7/2019 Object Oriented Concepts through Java
13/39
ContCont
Polymorphism is essential to object-orientedprogramming for one reason: it allows a general classto specify methods that will be common to all of itsderivatives, while allowing subclasses to define the
specific implementation of some or all of thosemethods.
Overridden methods are another way that Javaimplements the one interface, multiple methodsaspect of polymorphism.
-
8/7/2019 Object Oriented Concepts through Java
14/39
Using Abstract ClassesUsing Abstract Classes
Sometime you want to define a superclass that declares the
structure of a given abstraction without providing a complete
implementation of every method.
Sometimes you will want to create a superclass that only definesa generalized form that will be shared by all of its subclasses,
leaving it to each subclass to fill in the details.
Such a class determines the nature of the methods that the
subclasses must implement.
One way this situation can occur is when a superclass is unableto create a meaningful implementation for a method.
Figure class area() method
You may have methods which must be overridden by the
subclass in order for the subclass to have any meaning.
-
8/7/2019 Object Oriented Concepts through Java
15/39
Cont
Sometime you want some way to ensure that a subclass
does, indeed, override all necessary methods. Javas
solution to this problem is the abstract method.
You can require that certain methods be overridden bysubclasses by specifying the abstract type modifier.
These methods are sometimes referred to as subclasser
responsibilitybecause they have no implementation
specified in the superclass.
Thus, a subclass must override themit cannot simply use
the version defined in the superclass.
To declare an abstract method, use this general form:
abstract type name(parameter-list);
-
8/7/2019 Object Oriented Concepts through Java
16/39
Cont Any class that contains one or more abstract methods must also
be declared abstract.
To declare a class abstract, you simply use the abstract keywordin front of the class keyword at the beginning of the classdeclaration.
There can be no objects of an abstract class.
That is, an abstract class cannot be directly instantiated with thenew operator.
Such objects would be useless, because an abstract class is notfully defined.
Also, you cannot declare abstract constructors, or abstract staticmethods.
Any subclass of an abstract class must either implement all of theabstract methods in the superclass, or be itself declaredabstract.
-
8/7/2019 Object Oriented Concepts through Java
17/39
Using final with Inheritance Using final to Prevent Overriding
There will be times when you will want to prevent it from
occurring.
To disallow a method from being overridden, specify final as a
modifier at the start of its declaration. Methods declared as final cannot be overridden.
Early and late binding
Using final to Prevent Inheritance
Sometimes you will want to prevent a class from beinginherited.
To do this, precede the class declaration with final. Declaring
a class as final implicitly declares all of its methods as final,
too.
It is illegal to declare a class as both abstract and final
-
8/7/2019 Object Oriented Concepts through Java
18/39
Packages
Packages are containers for classes that are used to
keep the class name space compartmentalized.
For example, a package allows you to create a class
named List, which you can store in your own packagewithout concern that it will collide with some other class
named List stored elsewhere.
Packages are stored in a hierarchical manner and are
explicitly imported into new class definitions. Name collision without packages.
Java provides a mechanism for partitioning the class
name space into more manageable chunks.
-
8/7/2019 Object Oriented Concepts through Java
19/39
Cont
This mechanism is the package. The package is both a
naming and a visibility control mechanism.
You can define classes inside a package that are not
accessible by code outside that package. You can also define class members that are only
exposed to other members of the same package.
This allows your classes to have intimate knowledge of
each other, but not expose that knowledge to the restof the world.
-
8/7/2019 Object Oriented Concepts through Java
20/39
String Class
Every string you create is actually an object of type String.
Objects of type String are immutable; once a String object is
created, its contents cannot be altered.
This may seem like a serious restriction, it is not, for two reasons:
If you need to change a string, you can always create a new
one that contains the modifications.
Java defines a peer class ofString, 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";
System.out.println(myString);
-
8/7/2019 Object Oriented Concepts through Java
21/39
Cont
Operator forString objects: +. It is used to
concatenate two strings.
String myString = "I" + " like " + "Java.";
The String Constructors
String s = new String();
String(charchars[ ])
String(charchars[ ], int startIndex, int numChars)
String(String strObj)
String(byte asciiChars[ ])
String(byte asciiChars[ ], int startIndex, int
numChars)
-
8/7/2019 Object Oriented Concepts through Java
22/39
Cont The length of a string is the number of characters that it contains. int length( ); is used to get length.
char chars[] = { 'a', 'b', 'c' };
String s = new String(chars);
System.out.println(s.length()); String concatenation is done with various data types.
String age = 9;
String s = "He is " + age + " years old.";
System.out.println(s);
What will be the output of following code?
String s = "four: " + 2 + 2;
System.out.println(s);
-
8/7/2019 Object Oriented Concepts through Java
23/39
Cont
String Conversion and toString( )
Java converts data into its string representation during
concatenationby using overloaded versions of the string
conversion method valueOf( ) defined by String.
valueOf( ) is overloaded for all the simple types and for
type Object.
For objects, valueOf( ) calls the toString( ) method on the
object.
Every class implements toString( ) because it is defined byObject.
General form is String toString( );
Example of Box Class
-
8/7/2019 Object Oriented Concepts through Java
24/39
Cont
Character Extraction charAt()
Extract a single character from a string
char charAt(int where)
ch = "abc".charAt(1);
getChars()
To extract more than one character at a time
void getChars(int sourceStart, int sourceEnd, char target[
], int targetStart)
getBytes()
To stores the characters in an array of bytes.
byte[ ] getBytes( )
-
8/7/2019 Object Oriented Concepts through Java
25/39
Cont
toCharArray()
To convert all the characters in a String object into a
character array
char[ ] toCharArray( )
-
8/7/2019 Object Oriented Concepts through Java
26/39
Cont
String Comparison
equals() and equalsIgnoreCase()
To compare two strings for equality, use equals( ).
boolean equals(Object str)
It returns true if the strings contain the same
characters in the same order, and false otherwise.
The comparison is case-sensitive.
To perform a comparison that ignores case
differences, call equalsIgnoreCase( ).
boolean equalsIgnoreCase(String str)
-
8/7/2019 Object Oriented Concepts through Java
27/39
Cont
String s1 = "Hello";
String s2 = "Hello";
String s3 = "Good-bye";
String s4 = "HELLO";
s1.equals(s2);
s1.equals(s3);
s1.equals(s4);
s1.equalsIgnoreCase(s4);
-
8/7/2019 Object Oriented Concepts through Java
28/39
Cont regionMatches()
Compares a specific region inside a string with another
specific region in another string.
boolean regionMatches(int startIndex, String str2, int
str2StartIndex, int numChars)boolean regionMatches(boolean ignoreCase, int
startIndex, String str2, int str2StartIndex, int numChars)
startsWith() and endsWith()
The startsWith( ) method determines whether a givenString begins with a specified string.
The endsWith( ) determines whether the String in
question ends with a specified string.
Second form of startsWith() is boolean startsWith(String str,
int startIndex)
-
8/7/2019 Object Oriented Concepts through Java
29/39
Cont
equals() Versus ==
the equals( ) method compares the characters
inside a String object.
The == operator compares two object referencesto see whether they refer to the same instance.
String s1 = "Hello";
String s2 = new String(s1);
System.out.println(s1 + " equals " + s2 + " -> " +
s1.equals(s2));
System.out.println(s1 + " == " + s2 + " -> " + (s1 ==
s2));
-
8/7/2019 Object Oriented Concepts through Java
30/39
-
8/7/2019 Object Oriented Concepts through Java
31/39
Cont
Searching Strings
indexOf( ) Searches for the first occurrence of a
character or substring.
lastIndexOf( ) Searches for the last occurrence of acharacter or substring.
int indexOf(int ch)
int indexOf(String str)
int indexOf(int ch, int startIndex)
int indexOf(String str, int startIndex)
-
8/7/2019 Object Oriented Concepts through Java
32/39
Cont
Modifying a String
substring( )
You can extract a substring using substring( ).
String substring(int startIndex) String substring(int startIndex, int endIndex)
result = org.substring(0, 7);
concat( )
You can concatenate two strings using concat( ) String concat(String str)
replace( )
The replace( ) method replaces all occurrences of one
character in the invoking string with another character.
-
8/7/2019 Object Oriented Concepts through Java
33/39
Cont
String replace(charoriginal, charreplacement)
String s = "Hello".replace('l', 'w');
trim( )
The trim( ) method returns a copy of the invoking stringfrom which any leading and trailing whitespace has been
removed.
String s = " Hello World ".trim();
The trim( ) method is quite useful when you process usercommands.
-
8/7/2019 Object Oriented Concepts through Java
34/39
Cont
Data Conversion Using valueOf() The valueOf( ) method converts data from its internal
format into a human-readable form.
static String valueOf(double num)
static String valueOf(long num)
static String valueOf(Object ob)
static String valueOf(charchars[ ])
Changing the Case of Characters String toLowerCase( )
String toUpperCase( )
-
8/7/2019 Object Oriented Concepts through Java
35/39
Cont
StringBuffer
String represents fixed-length, immutable character
sequences. In contrast,
StringBufferrepresents growable and writeable character
sequences.
StringBuffermay have characters and substrings inserted in
the middle or appended to the end.
StringBufferwill automatically grow to make room for such
additions and often has more characters preallocated than areactually needed, to allow room for growth.
StringBuffer( )
StringBuffer(int size)
StringBuffer(String str)
-
8/7/2019 Object Oriented Concepts through Java
36/39
Cont
int length( )
int capacity( )
void setLength(int len)
len value must be nonnegative. If you call setLength( ) with a value less than the current
value returned by length( ), then the characters stored
beyond the new length will be lost.
char charAt(int where) void setCharAt(int where, charch)
getChars( )
void getChars(int sourceStart, int sourceEnd, chartarget[
],int targetStart)
-
8/7/2019 Object Oriented Concepts through Java
37/39
Cont
append()
The append( ) method concatenates the string representation
of any other type of data to the end of the invoking
StringBufferobject.
StringBuffer append(String str)
StringBuffer append(int num) StringBuffer append(Object obj)
insert()
The insert( ) method inserts one string into another.
StringBuffer insert(int index, String str) StringBuffer insert(int index, charch)
StringBuffer insert(int index, Object obj)
StringBuffer sb = new StringBuffer("I Java!");
sb.insert(2, "like ");
-
8/7/2019 Object Oriented Concepts through Java
38/39
Cont
reverse( )
StringBuffer reverse( )
This method returns the reversed object on which it was
called. delete() and deleteCharAt( )
StringBuffer delete(int startIndex, int endIndex)
StringBuffer deleteCharAt(int loc)
replace() It replaces one set of characters with another set inside a
StringBufferobject.
StringBuffer replace(int startIndex, int endIndex, String
str)
-
8/7/2019 Object Oriented Concepts through Java
39/39
Cont
substring()
Returns a portion of a StringBuffer.
String substring(int startIndex)
String substring(int startIndex, int endIndex)