Object Oriented Programming Concepts - II
Object Oriented Programming Concepts - II
(PART II)
The String class
• A String object is immutable: Its content cannot be changed once
the string is created.
• The String class has 13 constructors and more than 40 methods
for manipulating strings.
Constructing a string
• To create a string from a string literal, use the syntax:
String newString = new String(stringLiteral);
• The argument stringLiteral is a sequence of characters enclosed inside double
quotes.
• The following statement creates a String object message for the string literal
"Welcome to Java":
String message = new String("Welcome to Java");
• Java treats a string literal as a String object. Thus, the following statement is
valid:
String message = "Welcome to Java";
• We can also create a string from an array of characters. For example, the
following statements create the string "Good Day":
char[] charArray = {'G', 'o', 'o', 'd', ' ', 'D', 'a', 'y’};
String message = new String(charArray);
Immutable Strings and Interned
Strings
• A String object is immutable; its contents cannot be changed. Consider below
example:
String s = "Java";
s = "HTML";
• The answer is no. The first statement creates a String object with the content
"Java" and assigns its reference to s.
• The second statement creates a new String object with the content "HTML"
and assigns its reference to s.
• The first String object still exists after the assignment, but it can no longer be
accessed, because variable s now points to the new object.
Cont’d
• Because strings are immutable and are ubiquitous in programming, the JVM
uses a unique instance for string literals with the same character sequence in
order to improve efficiency and save memory. Such an instance is called an
interned string. For example,
String s1 = "Welcome to Java";
String s2 = new String("Welcome to Java");
String s3 = "Welcome to Java";
System.out.println("s1 == s2 is " + (s1 == s2));
System.out.println("s1 == s3 is " + (s1 == s3));
• display
s1 == s2 is false
s1 == s3 is true
• s1 and s3 refer to the same interned string—"Welcome to Java"—so s1 == s3
is true. However, s1 == s2 is false, because s1 and s2 are two different string
objects, even though they have the same contents.
Replacing and Splitting Strings
• We can add, insert, or append new contents into StringBuilder and StringBuffer
objects, whereas the value of a String object is fixed once the string is created.
• The StringBuilder class is similar to StringBuffer except that the methods for
modifying the buffer in StringBuffer are synchronized, which means that only
one task is allowed to execute the methods.
Modifying Strings in the StringBuilder
Inheritance
• Object-oriented programming allows us to define new classes
from existing classes. This is called inheritance. It represents the
IS-A relationship which is also known as a parent-child
relationship.
• Inheritance enables us to define a general class (i.e., a
superclass) and later extend it to more specialized classes (i.e.,
subclasses).
• In Java terminology, a class C1 extended from another class C2 is
called a subclass, and C2 is called a superclass.
• A superclass is also referred to as a parent class or a base class,
and a subclass as a child class, an extended class, or a derived
class.
• A subclass inherits accessible data fields and methods from its
superclass and may also add new data fields and methods.
Cont’d
• The syntax is as follows:
class Subclass-name extends Superclass-name
{ //methods and fields
}
• For example:
class Employee{
float salary=40000;
}
class Programmer extends Employee{
int bonus=10000;
public static void main(String args[]){
Programmer p=new Programmer();
System.out.println("Programmer salary is:"+p.salary);
System.out.println("Bonus of Programmer is:"+p.bonus);
}
}
Types of Inheritance
Cont’d
Important Notes to Inheritance
• Subclass is not a subset of its superclass. In fact, a subclass usually contains
more information and methods than its superclass.
• Private data fields in a superclass are not accessible outside the class.
Therefore, they cannot be used directly in a subclass. They can, however, be
accessed/mutated through public accessors/mutators if defined in the
superclass.
• Not all is-a relationships should be modeled using inheritance. For example, a
square is a rectangle, but you should not extend a Square class from a
Rectangle class, because the width and height properties are not appropriate
for a square.
• Inheritance is used to model the is-a relationship. Do not blindly extend a class
just for the sake of reusing methods. For example, it makes no sense for a Tree
class to extend a Person class, even though they share common properties
such as height and weight. A subclass and its superclass must have the is-a
relationship.
• Multiple inheritance is not possible in java with classes, but it is possible with
interfaces.
Super Keyword
• The keyword super refers to the superclass and can be used to
invoke the superclass’s methods and constructors.
• A subclass inherits accessible data fields and methods from its
superclass.
• The keyword super refers to the superclass of the class in which
super appears. It can be used in two ways:
– To call a superclass constructor.
– To call a superclass method.
Calling Superclass Constructors
• A constructor is used to construct an instance of a class. Unlike
properties and methods, the constructors of a superclass are not
inherited by a subclass.
• They can only be invoked from the constructors of the subclasses
using the keyword super.
• The syntax to call a superclass’s constructor is:
– super(), or super(parameters);
• The statement super() invokes the no-arg constructor of its
superclass, and the statement super(arguments) invokes the
superclass constructor that matches the arguments.
• The statement super() or super(arguments) must be the first
statement of the subclass’s constructor; this is the only way to
explicitly invoke a superclass constructor.
Example
class Animal{
Animal(){System.out.println("animal is created");}
}
class Dog extends Animal{
Dog(){
super();
System.out.println("dog is created");
}
}
class TestSuper3{
public static void main(String args[]){
Dog d=new Dog();
}}
Output is:
Animal is created
Dog is created
Calling Superclass Methods
• The keyword super can also be used to reference a
method other than the constructor in the superclass.
The syntax is:
– super.method(parameters);
Example
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void eat(){System.out.println("eating bread...");}
void bark(){System.out.println("barking...");}
void work(){
super.eat();
bark(); }
}
class TestSuper2{
public static void main(String args[]){
Dog d=new Dog(); Output:
d.work(); eating…
}} Barking…
Constructor Chaining
• A constructor may invoke an overloaded constructor or
its superclass constructor. If neither is invoked explicitly,
the compiler automatically puts super() as the first
statement in the constructor. For example:
• In any case, constructing an instance of a class invokes
the constructors of all the super-classes along the
inheritance chain.
• When constructing an object of a subclass, the subclass
constructor first invokes its superclass constructor
before performing its own tasks.
• If the superclass is derived from another class, the
superclass constructor invokes its parent-class
constructor before performing its own tasks.
• This process continues until the last constructor along
the inheritance hierarchy is called. This is called
constructor chaining.
Example
public class Faculty extends Employee {
public static void main(String[] args) {
new Faculty(); }
public Faculty() {
System.out.println("(4) Performs Faculty's tasks");
}}
class Employee extends Person {
public Employee() {
this("(2) Invoke Employee's overloaded constructor");
System.out.println("(3) Performs Employee's tasks "); }
public Employee(String s) {
System.out.println(s);
}}
class Person {
public Person() {
System.out.println("(1) Performs Person's tasks");} }
Important
• If a class is designed to be extended, it is better to
provide a no-arg constructor to avoid programming
errors. Consider the following code:
public class Apple extends Fruit {
}
class Fruit {
public Fruit(String name) {
System.out.println("Fruit's constructor is invoked");
}}
• Since no constructor is explicitly defined in Apple,
Apple’s default no-arg constructor is defined
implicitly. Since Apple is a subclass of Fruit, Apple’s
default constructor automatically invokes Fruit’s
no-arg constructor.
• However, Fruit does not have a no-arg constructor,
because Fruit has an explicit constructor defined.
Therefore, the program cannot be compiled.
Overriding Methods
• A subclass inherits methods from a superclass.
• Sometimes it is necessary for the subclass to modify the
implementation of a method defined in the superclass.
• This is referred to as method overriding.
• To override a method, the method must be defined in
the subclass using the same signature and the same
return type as in its superclass.
class Vehicle{
//defining a method
void run(){
System.out.println("Vehicle is running");}
}
• For instance,
class A{}
class B extends A{}
A a= new B(); //upcasting
class Bike{
void run(){System.out.println("running");}
}
class Splendor extends Bike{
void run(){System.out.println("running safely with 60km");}
public static void main(String args[]){
Bike b = new Splendor(); //upcasting
b.run();
}
}
• We are calling the run method by the reference variable of
Parent class. Since it refers to the subclass object and subclass
method overrides the Parent class method, the subclass method
is invoked at runtime. Since method invocation is determined by
the JVM not compiler, it is known as runtime polymorphism.
Static binding and dynamic binding
class Dog{
static void eat(){System.out.println("dog is eating...");}