OOP CH-3
OOP CH-3
When you think in an object-oriented manner, everything is an object, and every object is a member of a class.
A circle is a member of the class that called geometry. An object-oriented programmer would say that circle is
an instance of the geometry class.
These statements represent is-a relationships, that is, relationships in which the object “is a” concrete example
of the class.
An object represents an entity in the real world that can be distinctly identified.
A class is a template, blueprint, or contract that defines what an object’s data fields and methods will be.
An object is an instance of a class. You can create many instances of a class. Creating an instance is referred
to as instantiation.
A Java class uses variables to define data fields and methods to define actions.
Additionally, a class provides methods of a special type, known as constructors, which are invoked to create a
new object.
A constructor can perform any action, but constructors are designed to perform initializing actions, such as
initializing the data fields of objects.
When you create a class, you must assign a name to the class, and you must determine what data and methods
will be part of the class.
c) Any legal identifier you choose for the name of your class - starting with an uppercase letter is
conventional.
Syntax:
Example:
After writing the class header public class Circle, you write the body of the Circle class between a set of curly
braces. The body contains the data and methods for the class. The data components of a class are often
referred to as data fields to help distinguish them from other variables you might use.
Data fields are variables you declare within a class but outside of any method. A class’s data fields are most
often private and not static. The exception occurs when you want to use a non-changing value without being
required to create an object – in that case you make the field both static and final.
Example:
1. Write a type and an identifier - just as when you declare any variable - and then you allocate computer
memory for that object.
ClassName objectRefVar;
Example:
When you declare the circle1 instance of the Circle class, you are notifying the compiler that you will use the
identifier circle1.
However, you are not yet setting aside computer memory in which the Circle named circle1 might be stored -
that is done automatically only for primitive type variables.
2. Allocating memory for object name. To allocate the needed memory for an object, you must use the new
operator (used to create an object from the constructor).
Example:
In this statement, Circle is the object’s type (its class), and circle1 is the name of the object. Also, circle1
becomes a reference to the object - the name for a memory address where the object is held.
Every object name is also a reference - that is, a computer memory location. The new operator is allocating a
new, unused portion of computer memory for circle1.
The value that the statement is assigning to circle1 is a memory address at which circle1 is to be located.
You do not need to be concerned with what the actual memory address is - when you refer to circle1, the
compiler locates it at the appropriate address for you.
The statement after the new operator, Circle(), with its parentheses, looks suspiciously like a method name
that constructs a Circle object.
The Circle() method is a constructor, a special type of method that creates and initializes objects.
Example:
circle1.radius;
B. Accessing a Methods
Example:
circle1.getArea();
Methods are invoked as operations on objects.
Example:
Write a java program using class of circle with radius data field and getArea method.
F The data field radius is referred to as an instance variable, because it is dependent on a specific instance.
F For the same reason, the method getArea is referred to as an instance method, because you can invoke it only
on a specific instance.
F The object on which an instance method is invoked is called a calling object.
• ð Constructors are invoked using the new operator when an object is created. Constructors play the
role of initializing objects.
• A constructor can be overloaded (i.e., multiple constructors can have the same name but different
signatures), making it easy to construct objects with different initial data values. Constructors are used
to construct objects. To construct an object from a class, invoke a constructor of the class using the
new operator, as follows:
A class normally provides a constructor without arguments (e.g., Circle()). Such a constructor is referred
to as a no-arg or no-argument constructor.
A class may be defined without constructors. In this case, a no-arg constructor with an empty body is
implicitly defined in the class. This constructor, called a default constructor, is provided automatically
only if no constructors are explicitly defined in the class.
The automatically supplied default constructor provides the following specific initial values to an
object’s data fields:
• The data field of a class is an instance variable. An instance variable is tied to a specific instance of the
class; it is not shared among objects of the same class.
Example:
• The radius in circle1 is independent of the radius in circle2 and is stored in a different memory location.
Changes made to circle1’s radius do not affect circle2’s radius, and vice versa.
• If you want all the instances of a class to share data, use static variables, also known as class variables.
Static variables store values for the variables in a common memory location.
• Because of this common location, if one object changes the value of a static variable, all objects of the
same class are affected. Java supports static methods as well as static variables.
• Static methods can be called without creating an instance of the class.
• Object-oriented programming allows you to derive new classes from existing classes. This is called
inheritance.
• Polymorphism enables you to “program in the general” rather than “program in the specific.”
• Abstract classes cannot be used to instantiate objects, because they are incomplete. Subclasses must declare
the “missing pieces” to become “concrete” classes, from which you can instantiate objects.
• In the Java programming language, an interface is a reference type that can contain only constants, method
signatures, and nested types. There are no method bodies. The Java API provides several predefined data
structures, called collections, used to store groups of related objects.
Example:
A capsule which is mixed of several medicines.
Advantages of Encapsulation:
By providing only a setter or getter method, you can make the class read-only or write- only.
It provides you the control over the data. Suppose you want to set the value of ID which should be
greater than 100 only, you can write the logic inside the setter method.
It is a way to achieve data hiding in Java because other class will not be able to access the data through
the private data members.
Note: F setter is used only for write-only and getter is used only for read-only!
Inheritance
You use a class to model objects of the same type.
Different classes may have some common properties and behaviors, which can be generalized in a class that can
be shared by other classes.
Inheritance enables you to define a general class and later extend it to more specialized classes.
The specialized classes inherit the properties and methods from the general class.
Consider Geometric Objects. Suppose you want to design the classes to model Geometric Objects such as circles and
rectangles.
Geometric Objects have many common properties and behaviors. Assume that this class also contains the dateCreated
property, getDateCreated() method and displayDate() methods.
The Circle and Rectangle class inherits all accessible data fields and methods from the GeometricObject
class.
In addition, it has a new data field, radius and also contains the getArea().
Likewise, rectangle has the data fields, height and width and method getArea().
Syntax of inheritance:
public class Subclass extends Superclass
• Note:
• F The keyword extend tells the compiler that the subclass extends the common features from the superclass, thus
inheriting the data fields and methods.
• Example:
Features of inheritance:
A 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 accessor/mutator if defined in the
superclass.
Inheritance is used to model the is-a relationship. A subclass and its superclass must have the is-a relationship.
Some programming languages allow you to derive a subclass from several classes. This capability is known as
multiple inheritance. Java, however, does not allow multiple inheritance.
Features of inheritance:
A Java class may inherit directly from only one superclass. This restriction is known as single inheritance. If
you use the extends keyword to define a subclass, it allows only one parent class. Nevertheless, multiple
inheritance can be achieved through interfaces.
The inheritance relationship enables a subclass to inherit features from its superclass with additional new
features. A subclass is a specialization of its superclass; every instance of a subclass is also an instance of its
superclass, but not vice versa.
Example: Write a java program with two subclasses, Circle and Rectangle that inherit the date created from
the Geometry with their any respective coordinates.
A subclass inherits accessible data fields and methods from its superclass.
It refers to the superclass of the class in which super appears. It can be used:
To access the data members of parent class when both parent and child class have member with same
name.
To explicitly call the no-arg and parameterized constructor of parent class
To access the method of parent class when child class has overridden that method.
• The syntax to call a superclass constructor and super-class methods are, respectively:
The statement super() or super(arguments) must appear in the first line of the subclass constructor; this is the only
way to explicitly invoke a superclass constructor.
If neither is invoked explicitly, the compiler automatically puts super() as the first statement in the constructor.
In any case, constructing an instance of a class invokes the constructors of all the superclasses 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 constructor
chaining.
• It is a method that define multiple methods with the same name but different signatures with parameter
list within one class.
• The Java compiler determines which method is used based on the method signature.
• Overriding means to provide a new implementation for a method in the subclass. The method is already
defined in the superclass.
• To override a method, the method must be defined in the subclass using the same signature and the same
return type.
• 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.
• An instance method can be overridden only if it is accessible. Thus, a private method cannot be
overridden, because it is not accessible outside its own class.
• If a method defined in a subclass is private as in its superclass, the two methods are completely unrelated.
• A static method can be inherited. However, a static method cannot be overridden.
• If a static method defined in the superclass is redefined in a subclass, the method defined in the superclass is hidden.
The hidden static methods can be invoked using the
syntax SuperClassName.staticMethodName.
Output:
Note:
Every class in Java is descended from the java.lang.Object class. If no inheritance is specified when
a class is defined, the superclass of the class is Object by default.
The word "poly" means many and "morphs" means forms. So, polymorphism means many forms.
It allows us to perform a single action in different ways or it is the capability of a method to do different things
based on the object that it is acting upon.
In other words, polymorphism allows you define one interface and have multiple implementations.
A class defines a type. A type defined by a subclass is called a subtype and a type defined by its superclass is
called a supertype
Suppose we have a class Geometry that has a method area(). The action for the different geometry like
circle, rectangle, square, etc., are different.
Now consider two subclasses of Geometry as Circle and Rectangle that extends from Geometry.
All the Geometry have an area, but there were different ways to do the same action. This feature allows
us to perform a single action in different ways.
It would not make any sense to just call the generic area() method as each Geometry has a different area.
Thus, we can say that the action this method performs is based on the type of object.
So, the method area() have multiple implementations in the different-2 subclasses. Which area() method
will be called is determined at runtime. Therefore, it is a runtime polymorphism.
Example:-
Write a java program that computes the area of Circle and Rectangle using polymorphism. Superclass
(PolyGeometry):
Output:
Note:
F Method Overloading in Java – compile time (or static polymorphism)
F Method Overriding in Java – runtime time (or dynamic polymorphism)
It is a process of hiding the implementation details from the user. Only the functionality will be provided to
the user. In Java, abstraction is achieved using abstract classes and interfaces.
In the inheritance hierarchy, classes become more specific and concrete with each new
subclass.
If you move from a subclass back up to a superclass, the classes become more general
Class design should ensure that a superclass contains common features of its subclasses.
Abstract Methods – it is a method that is not implemented (i.e. defined without implementation) in the
superclass, its implementation is provided by the subclasses and are denoted using the abstract modifier in the
method header.
Abstract classes are like regular classes, but you cannot create instances of abstract classes using the new
operator.
The constructor in the abstract class is defined protected, because it is used only by subclasses.
When you create an instance of a concrete subclass, its superclass’s constructor is invoked to initialize data
superclass doesn’t implement all the abstract methods, the subclass must be defined abstract.
In other words, in a non-abstract subclass extended from an abstract class, all the abstract
methods must be implemented. Also note that abstract methods are non-static.
An abstract class cannot be instantiated using the new operator, but you can still define its
A subclass can be abstract even if its superclass is concrete. Example: The Object class is
A subclass can override a method from its superclass to define it abstract. This is very
unusual but is useful when the implementation of the method in the superclass becomes
invalid in the subclass. In this case, the subclass must be defined abstract.
You cannot create an instance from an abstract class using the new operator, but an
abstract class can be used as a data type. Therefore, the following statement, which
You can then create an instance of GeometricObject and assign its reference to the array like this:
• Output
It is a reference type, similar to a class, that can contain only constants, method signatures, and
nested types.
There are no method bodies, i.e. the method signatures have no braces and are terminated with
a semicolon.
Interfaces cannot be instantiated they can only be implemented by classes or extended by other
interfaces.
Declaring Interface:
Example:
It a special class in Java. Each interface is compiled into a separate bytecode file, just like a regular
class.
The class for the object implements this interface using the implements keyword. When a class
implements an interface, it implements all the methods defined in the interface with the exact
The relationship between the class and the interface is known as interface inheritance.
An interface with an empty body is referred to as a marker interface. A marker interface does not contain
constants or methods. It is used to denote that a class possesses certain desirable properties.
Extending Interface
An interface can inherit other interfaces using the extends keyword. Such an interface is called
a
subinterface.
Syntax:
Modifiers interface subInterfaceName
extends superInterfaceName{
Multiple Interface-inheritance:
Implementing an Interface
To use an interface, you write a class that implements the interface. When an instantiable class implements
an interface, it provides a method body for each of the methods declared in the interface. To declare a class
that implements an interface, you include an implements clause in the class declaration.
Syntax:
Modifiers class ClassName implements InterfaceName {
Generally, in Java, a class can inherit from only one class but it can implement more than one
interface. Java allows only single inheritance for class extension but allows multiple extensions
for interfaces. An interface can extend other interfaces but not classes. A class can extend its
Output
All classes share a single root, the Object class, but there is no single root for interfaces. Like a
A variable of an interface type can reference any instance of the class that implements the interface.
If a class implements an interface, the interface is like a superclass for the class. You can use an
interface as a data type and cast a variable of an interface type to its subclass, and vice versa.
It is a grouping of related types providing access protection and name space management. The
types refer to classes, interfaces, enumerations, and annotation types. Enumerations and
annotation types are special kinds of classes and interfaces, respectively.
The types that are part of the Java platform are members of various packages that bundle
classes by function:
Fundamental classes are in java.lang, classes for reading and writing (input and output) are in
java.io, and so on. You can put your types in packages too.
To create a package, you choose a name for the package and put a package statement with that name at the
top of every source file that contains the types (classes, interfaces, enumerations, and annotation types) that
you want to include in the package.
The package statement must be the first line in the source file. There can be only one package statement in
each source file, and it applies to all types in the file.
Package names are written in all lowercase to avoid conflict with the names of classes or interfaces.
For convenience, the Java compiler automatically imports three entire packages for each source file:
It specifies whether data fields and methods can be accessed from the outside of the class or specify how
class and class members are accessed.
There is no restriction on accessing data fields and methods from inside the class.
The visibility of these modifiers increases in this order:
1. Public
It enables the members of the class to be accessed by any class.
Public members can be accessed from any other classes.
It is used for classes, methods, and data fields.
2. Protected
It enables the members of the class to be accessed by the subclasses in any package or classes in the same
package.
A protected data field or method in a superclass can be accessed in its subclasses.
It is used for members of the class (methods, and data fields).
3. Default
The default or no modifiers in order to allow the members of the class to be accessed directly from any
class within the same package but not from other packages.
This is known as package-private or package-access. It is used for classes, methods, and data fields.
4. Private
• It hides the members of the class completely so that they cannot be accessed directly from outside the
class.
• Private members can be accessed only from the inside of the class.
4. Private