A package combines related classes into subsystems
All the classes in a particular directory
Classes in different packages can have the same name
Although not recommended
Importing a package is done as follows:
import finance.banking.accounts.*;
CE204 Object-Oriented Programming
Access control
Applies to methods and variables
public
Any class can access
protected
Only code in the package, or subclasses can access
(blank)
Only code in the package can access
private
Only code written in the class can access
Inheritance still occurs!
CE204 Object-Oriented Programming
Threads and concurrency
Thread:
Sequence of executing statements that can be running concurrently with other threads
To create a thread in Java:
Create a class implementing Runnable or extending Thread
Implement the run method as a loop that does something for a period of time
Create an instance of this class
Invoke the start operation, which calls run
CE204 Object-Oriented Programming
Programming Style Guidelines
Remember that programs are for people to read
Always choose the simpler alternative
Reject clever code that is hard to understand
Shorter code is not necessarily better
Choose good names
Make them highly descriptive
Do not worry about using long names
CE204 Object-Oriented Programming
Programming style
Comment extensively
Comment whatever is non-obvious
Do not comment the obvious
Comments should be 25-50% of the code
Organize class elements consistently
Variables, constructors, public methods then private methods
Be consistent regarding layout of code
CE204 Object-Oriented Programming
Programming style
Avoid duplication of code
Do not "clone" if possible
Create a new method and call it
Cloning results in two copies that may both have bugs
When one copy of the bug is fixed, the other may be forgotten
CE204 Object-Oriented Programming
Programming style
Adhere to good object oriented principles
E.g. the ‘isa rule’
Prefer private as opposed to public
Do not mix user interface code with non-user interface code
Interact with the user in separate classes
This makes non-UI classes more reusable
CE204 Object-Oriented Programming
Difficulties and Risks in Programming
Language evolution and deprecated features:
Java is evolving, so some features are ‘deprecated’ at every release
Efficiency can be a concern in some object oriented systems
Java can be less efficient than other languages
VM-based
Dynamic binding
CE204 Object-Oriented Programming
C++ vs Java
Comparison Index
C++
Java
Platform-independent
C++ is platform-dependent.
Java is platform-independent.
Mainly used for
C++ is mainly used for system programming.
Java is mainly used for application programming. It is widely used in Windows-based, web-based, enterprise, and mobile applications.
CE204 Object-Oriented Programming
C++ vs Java
Comparison Index
C++
Java
Multiple inheritance
C++ supports multiple inheritance.
Java doesn't support multiple inheritance through class. It can be achieved by using interfaces in java.
Operator Overloading
C++ supports operator overloading.
Java doesn't support operator overloading.
CE204 Object-Oriented Programming
C++ vs Java
Comparison Index
C++
Java
Goto
C++ supports the goto statement.
Java doesn't support the goto statement.
Compiler and Interpreter
C++ uses compiler only. C++ is compiled and run using the compiler which converts source code into machine code so, C++ is platform dependent.
Java uses both compiler and interpreter. Java source code is converted into bytecode at compilation time. The interpreter executes this bytecode at runtime and produces output. Java is interpreted that is why it is platform-independent.
CE204 Object-Oriented Programming
C++ vs Java
Comparison Index
C++
Java
Pointers
C++ supports pointers. You can write a pointer program in C++.
Java supports pointer internally. However, you can't write the pointer program in java. It means java has restricted pointer support in java.
Design Goal
C++ was designed for systems and applications programming. It was an extension of the C programming language.
Java was designed and created as an interpreter for printing systems but later extended as a support network computing. It was designed to be easy to use and accessible to a broader audience.
CE204 Object-Oriented Programming
C++ vs Java
Comparison Index
C++
Java
Structure and Union
C++ supports structures and unions.
Java doesn't support structures and unions.
Thread Support
C++ doesn't have built-in support for threads. It relies on third-party libraries for thread support.
Java has built-in thread support.
CE204 Object-Oriented Programming
C++ vs Java
Comparison Index
C++
Java
Documentation comment
C++ doesn't support documentation comments.
Java supports documentation comment (/** ... */) to create documentation for java source code.
Virtual Keyword
C++ supports virtual keyword so that we can decide whether or not to override a function.
Java has no virtual keyword. We can override all non-static methods by default. In other words, non-static methods are virtual by default.
CE204 Object-Oriented Programming
C++ vs Java
Comparison Index
C++
Java
unsigned right shift >>>
C++ doesn't support >>> operator.
Java supports unsigned right shift >>> operator that fills zero at the top for the negative numbers. For positive numbers, it works same like >> operator.
Inheritance Tree
C++ always creates a new inheritance tree.
Java always uses a single inheritance tree because all classes are the child of the Object class in Java. The Object class is the root of the inheritance tree in java.
CE204 Object-Oriented Programming
C++ vs Java
Comparison Index
C++
Java
Hardware
C++ is nearer to hardware.
Java is not so interactive with hardware.
Object-oriented
C++ is an object-oriented language. However, in the C language, a single root hierarchy is not possible.
Java is also an object-oriented language. However, everything (except fundamental types) is an object in Java. It is a single root hierarchy as everything gets derived from java.lang.Object.
CE204 Object-Oriented Programming
Object Orientation Part-2
CE204 Object-Oriented Programming
Procedural Programming
Pascal, C, Basic, Fortran and similar traditional languages are procedural
Each statement tells the computer to do something
The emphasis is on doing things
Functions
A program is divided into functions
Each function has a clearly defined purpose and interface
CE204 Object-Oriented Programming
Procedural Programming
CE204 Object-Oriented Programming
Problems with Procedural Programming
Data Is undervalued
Data is, after all, the reason for a program’s existence. The important parts of a program are not functions that display the data or functions that checks for correct input; they are data
Procedural programs don’t model the real world very well. The real world does not consist of functions
Global data can be corrupted by functions that have no business changing it
To add new data items, all the functions that access data must be modified so that they can also access these new items
Creating new data types is difficult
CE204 Object-Oriented Programming
Besides
It is also possible to write good programs by using procedural programming (C programs).
But object-oriented programming offers programmers many advantages, enables them to write high-quality programs
CE204 Object-Oriented Programming
Object-Oriented Programming
The fundamental idea behind object-oriented programming:
The real world consists of objects. Computer programs may contain computer world representations of the things (objects) that constitute the solutions of real world problems.
Real world objects have two parts:
Properties (or state: characteristics that can change),
Behavior (or abilities: things they can do).
To solve a programming problem in an object-oriented language,the programmer no longer asks how the problem will be divided into functions, but how it will be divided into objects.
The emphasis is on data
CE204 Object-Oriented Programming
Object-Oriented Programming
What kinds of things become objects in object-oriented programs?
Human entities: Employees, customers, salespeople,worker, manager
Graphics program: Point, line, square, circle, ...
Mathematics: Complex numbers, matrix
Computer user environment: Windows, menus, buttons
Thinking in terms of objects rather than functions
Close match between objects in the programming sense and objects in the real world
Both data and the functions that operate on that data are combined into a single program entity
Data represent the properties (state), and functions represent the behavior of an object. Data and its functions are said to be encapsulated into a single entity
An object’s functions, called member functions in Java typically provide the only way to access its data. The data is hidden, so it is safe from accidental alteration.
CE204 Object-Oriented Programming
OOP: Encapsulation and Data Hiding
Encapsulation and data hiding are key terms in the
description of object-oriented languages.
If you want to modify the data in an object, you know exactly what functions to interact with it
The member functions in the object.
No other functions can access the data: This simplifies writing, debugging, and maintaining the program.
CE204 Object-Oriented Programming
Example: A Point on the plane
A Point on a plane has two properties; x-y coordinates.
Abilities (behavior) of a Point are, moving on the plane, appearing on the screen and disappearing.
A model for 2 dimensional points with the following parts:
Two integer variables (x,y) to represent x and y coordinates
A function to move the point: move
A function to print the point on the screen: print
A function to hide the point: hide
CE204 Object-Oriented Programming
Example: A Point on the plane
Once the model has been built and tested, it is possible to create many objects of this model, in the main program.
Point pointOne = new Point(67, 89);
Point pointTwo = new Point(12, 34);
publicclassPoint{
publicint x = 0;
publicint y = 0;
publicPoint(int a, int b){
x = a;
y = b;
}
}
CE204 Object-Oriented Programming
Object Model
A Java program typically consists of a number of objects that communicate with each other by calling one another’s member functions.
CE204 Object-Oriented Programming
OOP vs. Procedural Programming
Procedural languages still require you to think in terms of the structure of the computer rather than the structure of the problem you are trying to solve.
The programmer must establish the association between the machine model and the model of the problem that is actually being solved.
The effort required to perform this mapping produces programs that are difficult to write and expensive to maintain. Because the real world thing and their models on the computer are quite different
CE204 Object-Oriented Programming
Example: Procedural Programming
Real world thing: student
Computer model: char *, int, float
It is said that the C language is closer to the computer than the problem.
CE204 Object-Oriented Programming
OOP vs. Procedural Programming
The OO approach provides tools for the programmer to represent elements in the problem space
Objects are both in the problem space and the solution
The OO programs are easy to update by adding new types of objects
OOP allows you to describe the problem in terms of the problem, rather than in terms of the computer where the solution will run.
CE204 Object-Oriented Programming
OOP vs. Procedural Programming
Benefits of the object-oriented programming:
Readability
Understandability
Low probability of errors
Maintenance
Reusability
Teamwork
CE204 Object-Oriented Programming
OOP vs. Procedural Programming
Procedural paradigm:
Software is organized around the notion of procedures
Procedural abstraction
Works as long as the data is simple
Adding data abstractions groups together the pieces of data that describe some entity
Helps reduce the system’s complexity.
Such as Records and structures
Object oriented paradigm:
Organizing procedural abstractions in the context of data abstractions
CE204 Object-Oriented Programming
Object Oriented paradigm
All computations are performed in the context of objects.
The objects are instances of classes, which:
are data abstractions
contain procedural abstractions that operate on the objects
A running program can be seen as a collection of objects collaborating to perform a given task
CE204 Object-Oriented Programming
A View of the Two paradigms
CE204 Object-Oriented Programming
Classes and Objects
Object
A chunk of structured data in a running software system
Has properties
Represent its state
Has behaviour
How it acts and reacts
May simulate the behaviour of an object in the real world
CE204 Object-Oriented Programming
Objects: Shown as a UML instance diagram
CE204 Object-Oriented Programming
Classes
A class:
A unit of abstraction in an object oriented (OO) program
Represents similar objects
Its instances
A kind of software module
Describes its instances’ structure (properties)
Contains methods to implement their behaviour
CE204 Object-Oriented Programming
Is Something a Class or an Instance?
Something should be a class if it could have instances
Something should be an instance if it is clearly a single member of the set defined by a class
Film
Class; instances are individual films.
Reel of Film:
Class; instances are physical reels
Film reel with serial number SW19876
Instance of ReelOfFilm
CE204 Object-Oriented Programming
Is Something a Class or an Instance?
Science Fiction
Instance of the class Genre.
Science Fiction Film
Class; instances include ‘Star Wars’
Showing of ‘Star Wars’ in the Phoenix Cinema at 7 p.m.:
Instance of ShowingOfFilm
CE204 Object-Oriented Programming
Naming classes
Use capital letters
E.g. BankAccount not bankAccount
Use singular nouns
Use the right level of generality
E.g. Municipality, not City
Make sure the name has only one meaning
E.g. "bus" has several meanings
CE204 Object-Oriented Programming
Instance Variables
Variables defined inside a class corresponding to data present in each instance
Also called fields or member variables
Attributes
Simple data
E.g. name, dateOfBirth
Associations
Relationships to other important classes
E.g. supervisor, coursesTaken
CE204 Object-Oriented Programming
Variables vs. Objects
A variable
Refers to an object
May refer to different objects at different points in time
An object can be referred to by several different variables at the same time
Type of a variable
Determines what classes of objects it may contain
CE204 Object-Oriented Programming
Class variables
A class variable’s value is shared by all instances of a class.
Also called a static variable
If one instance sets the value of a class variable, then all the other instances see the same changed value.
Class variables are useful for:
Default or ‘constant’ values (e.g. PI)
Lookup tables and similar structures
Caution: do not over-use class variables
CE204 Object-Oriented Programming
Methods, Operations and Polymorphism
Operation
A higher-level procedural abstraction that specifies a type of behaviour
Independent of any code which implements that behaviour
E.g. calculating area (in general)
CE204 Object-Oriented Programming
Methods, Operations and Polymorphism
Method
A procedural abstraction used to implement the behaviour of a class
Several different classes can have methods with the same name
They implement the same abstract operation in ways suitable to each class
E.g. calculating area in a rectangle is done differently from in a circle
CE204 Object-Oriented Programming
Polymorphism
A property of object oriented software by which an abstract operation may be performed in different ways in different classes.
Requires that there be multiple methods of the same name
The choice of which one to execute depends on the object that is in a variable
Reduces the need for programmers to code many if-else or switch statements
CE204 Object-Oriented Programming
Organizing Classes into Inheritance Hierarchies
Superclasses
Contain features common to a set of subclasses
Inheritance hierarchies
Show the relationships among superclasses and subclasses
A triangle shows a generalization
Inheritance
The implicit possession by all subclasses of features defined in its superclasses
CE204 Object-Oriented Programming
An Example Inheritance Hierarchy
Inheritance
The implicit possession by all subclasses of features defined in its superclasses
CE204 Object-Oriented Programming
The Is-a Rule
Always check generalizations to ensure they obey the isa rule
"A checking account is an account"
"A village is a municipality"
Should 'Province' be a subclass of 'Country'?
No, it violates the is-a rule
"A province is a country" is invalid!
CE204 Object-Oriented Programming
A possible inheritance hierarchy of mathematical objects
CE204 Object-Oriented Programming
Make Sure all Inherited Features Make Sense in Subclasses
CE204 Object-Oriented Programming
Inheritance, Polymorphism and Variables
CE204 Object-Oriented Programming
Some Operations in the Shape Example
CE204 Object-Oriented Programming
Abstract Classes and Methods
An operation should be declared to exist at the highest class in the hierarchy where it makes sense
The operation may be abstract (lacking implementation) at that level
If so, the class also must be abstract
No instances can be created
The opposite of an abstract class is a concrete class
If a superclass has an abstract operation then its subclasses at some level must have a concrete method for the operation
Leaf classes must have or inherit concrete methods for all operations
Leaf classes must be concrete
CE204 Object-Oriented Programming
Overriding
A method would be inherited, but a subclass contains a new version instead
For extension
E.g. SavingsAccount might charge an extra fee following every debit
For optimization
E.g. The getPerimeterLength method in Circle is much simpler than the one in Ellipse
For restriction (best to avoid)
E.g. scale(x,y) would not work in Circle
CE204 Object-Oriented Programming
How a decision is made about which method to run
If there is a concrete method for the operation in the current class, run that method.
Otherwise, check in the immediate superclass to see if there is a method there; if so, run it.
Repeat step 2, looking in successively higher superclasses until a concrete method is found and run.
If no method is found, then there is an error
In Java and C++ the program would not have compiled
In Java and C++ the program would not have compiled
CE204 Object-Oriented Programming
Dynamic binding
Occurs when decision about which method to run can only be made at run time
Needed when:
A variable is declared to have a superclass as its type, and
There is more than one possible polymorphic method that could be run among the type of the variable and its subclasses
CE204 Object-Oriented Programming
Key Terminology
Abstraction
Object ⟹ something in the world
Class ⟹ objects
Superclass ⟹ subclasses
Operation ⟹ methods
Attributes and associations ⟹ instance variables
Modularity
Code is divided into classes, and classes into methods
Encapsulation
Details can be hidden in classes
This gives rise to information hiding:
Programmers do not need to know all the details of a class
CE204 Object-Oriented Programming
Basing Software Development on Reusable Technology
CE204 Object-Oriented Programming
Building on the Experience of Others
Software engineers should avoid re-developing software already developed
Types of reuse:
Reuse of expertise
Reuse of standard designs and algorithms
Reuse of libraries of classes or procedures
Reuse of powerful commands built into languages and operating systems
Reuse of frameworks
Reuse of complete applications
CE204 Object-Oriented Programming
Frameworks: Reusable Subsystems
A framework is reusable software that implements a generic solution to a generalized problem.
It provides common facilities applicable to different application programs. - Principle: Applications that do different, but related, things tend to have similar designs
CE204 Object-Oriented Programming
Frameworks to promote reuse
A framework is intrinsically incomplete
Certain classes or methods are used by the framework, but are missing (slots)
Some functionality is optional
Allowance is made for developer to provide it (hooks or extension points)
Developers use the services that the framework provides
Taken together the services are called the Application Program Interface (API)
CE204 Object-Oriented Programming
Object-oriented frameworks
In the object oriented paradigm, a framework is composed of a library of classes.
The API is defined by the set of all public methods of these classes.
Some of the classes will normally be abstract and there are often many Interfaces
Example:
A framework for payroll management
A framework for frequent buyer clubs
A framework for university registration
A framework for e-commerce web sites
CE204 Object-Oriented Programming
Frameworks and product lines
A product line (or product family) is a set of products built on a common base of technology.
The various products in the product line have different features to satisfy different markets
The software common to all products in included in a framework
Each product is produced by filling the available hooks and slots
E.g. software products offering "demo", "lite" or "pro" versions
CE204 Object-Oriented Programming
Types of frameworks
A horizontal framework provides general application facilities that a large number of applications can use
A vertical framework (application framework) is more ‘complete’ but still needs some slots to be filled to adapt it to specific application needs
CE204 Object-Oriented Programming
The Client-Server Architecture
A distributed system is a system in which:
computations are performed by separate programs
… normally running on separate pieces of hardware
… that co-operate to perform the task of the system.
Server:
A program that provides a service for other programs that connect to it using a communication channel
Client
A program that accesses a server (or several servers) to obtain services
A server may be accessed by many clients simultaneously
CE204 Object-Oriented Programming
Example of client-server systems
CE204 Object-Oriented Programming
Activities of a server
Initializes itself
Starts listening for clients
Handles the following types of events originating from clients
accepts connections
responds to messages
handles client disconnection
May stop listening
Must cleanly terminate
CE204 Object-Oriented Programming
Activities of a client
Initializes itself
Initiates a connection
Sends messages
Handles the following types of events originating from the server
responds to messages
handles server disconnection
Must cleanly terminate
CE204 Object-Oriented Programming
Threads in a client-server system
CE204 Object-Oriented Programming
Thin- versus fat-client systems
Thin-client system (a)
Client is made as small as possible
Most of the work is done in the server.
Client easy to download over the network
Fat-client system (b)
As much work as possible is delegated to the clients.
Server can handle more clients
CE204 Object-Oriented Programming
Communications protocols
The messages the client sends to the server form a language.
The server has to be programmed to understand that language.
The messages the server sends to the client also form a language.
The client has to be programmed to understand that language.
When a client and server are communicating, they are in effect having a conversation using these two languages
The two languages and the rules of the conversation, taken together, are called the protocol
CE204 Object-Oriented Programming
Tasks to perform to develop client-server applications
Design the primary work to be performed by both client and server
Design how the work will be distributed
Design the details of the set of messages that will be sent
Design the mechanism for
Initializing
Handling connections
Sending and receiving messages
Terminating
CE204 Object-Oriented Programming
Advantages of client-server systems
The work can be distributed among different machines
The clients can access the server’s functionality from a distance
The client and server can be designed separately
They can both be simpler
There is a choice about where to keep data:
All the data can be kept centrally at the server
Data can be distributed among many different clients or servers
The server can be accessed simultaneously by many clients
Competing clients can be written to communicate with the same server, and vice-versa
CE204 Object-Oriented Programming
Technology Needed to Build Client-Server Systems
Internet Protocol (IP)
Route messages from one computer to another
Long messages are normally split up into small pieces
Transmission Control Protocol (TCP)
Handles connections between two computers
Computers can then exchange many IP messages over a connection
Assures that the messages have been satisfactorily received
A host has an IP address and a host name
Several servers can run on the same host.
Each server is identified by a port number (0 to 65535).
To initiate communication with a server, a client must know both the host name and the port number
CE204 Object-Oriented Programming
Establishing a connection in Java
The java.net package
Permits the creation of a TCP/IP connection between two applications
Before a connection can be established, the server must start listening to one of the ports:
ServerSocket serverSocket = new ServerSocket(port);
Socket clientSocket = serverSocket.accept();
For a client to connect to a server:
Socket clientSocket= new Socket(host, port);
CE204 Object-Oriented Programming
Exchanging information in Java
Each program uses an instance of
InputStream to receive messages from the other program
OutputStream to send messages to the other program
Ensure that the developers of the reusable technology:
follow good software engineering practices
are willing to provide active support
Compatibility not maintained
Avoid obscure features
Only re-use technology that others are also re-using
CE204 Object-Oriented Programming
Risks when developing reusable technology
Investment uncertainty
Plan the development of the reusable technology, just as if it was a product for a client
The "not invented here syndrome"
Build confidence in the reusable technology by:
Guaranteeing support
Ensuring it is of high quality
Responding to the needs of its users
CE204 Object-Oriented Programming
Risks when developing reusable technology
Competition
The reusable technology must be as useful and as high quality as possible
Divergence (tendency of various groups to change technology in different ways)
Design it to be general enough, test it and review it in advance
CE204 Object-Oriented Programming
Risks when adopting a client-server approach
Security
Security is a big problem with no perfect solutions: consider the use of encryption, firewalls, ...
Need for adaptive maintenance
Ensure that all software is forward and backward compatible with other versions of clients and servers
CE204 Object-Oriented Programming
Java Classes and Objects
CE204 Object-Oriented Programming
Java Classes
Java is an object-oriented programming language, so everything in java program must be based on the object concept. In a java programming language, the class concept defines the skeleton of an object.
CE204 Object-Oriented Programming
Java Classes
The java class is a template of an object. The class defines the blueprint of an object. Every class in java forms a new data type. Once a class got created, we can generate as many objects as we want. Every class defines the properties and behaviors of an object. All the objects of a class have the same properties and behaviors that were defined in the class.
CE204 Object-Oriented Programming
Java Classes
Every class of java programming language has the following characteristics.
Identity - It is the name given to the class.
State - Represents data values that are associated with an object.
Behavior - Represents actions can be performed by an object.
CE204 Object-Oriented Programming
Java Classes
CE204 Object-Oriented Programming
Creating a Class
In java, we use the keyword class to create a class. A class in java contains properties as variables and behaviors as methods. Following is the syntax of class in the java.
class <ClassName>{
data members declaration;
methods defination;
}
Here, fields (variables) and methods represent the state and behavior of the object respectively.
fields are used to store data
methods are used to perform some operations
CE204 Object-Oriented Programming
Creating a Class
A class is a blueprint for the object. Before we create an object, we first need to define the class.
We can think of the class as a sketch (prototype) of a house. It contains all the details about the floors, doors, windows, etc. Based on these descriptions we build the house. House is the object.
Since many houses can be made from the same description, we can create many objects from a class.
CE204 Object-Oriented Programming
Creating a Class
The ClassName must begin with an alphabet, and the Upper-case letter is preferred.
The ClassName must follow all naming rules.
CE204 Object-Oriented Programming
Creating a Class
classBicycle{
// state or fieldprivateint gear = 5;
// behavior or methodpublicvoidbraking(){
System.out.println("Working of Braking");
}
}
In the above example, we have created a class named Bicycle. It contains a field named gear and a method named braking().
CE204 Object-Oriented Programming
Creating a Class
Here, Bicycle is a prototype. Now, we can create any number of bicycles using the prototype. And, all the bicycles will share the fields and methods of the prototype.
CE204 Object-Oriented Programming
Creating an Object
In java, an object is an instance of a class. When an object of a class is created, the class is said to be instantiated. All the objects that are created using a single class have the same properties and methods. But the value of properties is different for every object. Following is the syntax of class in the java.
<ClassName> <objectName> = new <ClassName>( );
CE204 Object-Oriented Programming
Creating an Object
The objectName must begin with an alphabet, and a Lower-case letter is preferred.
The objectName must follow all naming rules.
CE204 Object-Oriented Programming
Creating an Object
An object is called an instance of a class. For example, suppose Bicycle is a class then MountainBicycle, SportsBicycle, TouringBicycle, etc can be considered as objects of the class.
className object = new className();
// for Bicycle class
Bicycle sportsBicycle = new Bicycle();
Bicycle touringBicycle = new Bicycle();
We have used the new keyword along with the constructor of the class to create an object. Constructors are similar to methods and have the same name as the class. For example, Bicycle() is the constructor of the Bicycle class.
CE204 Object-Oriented Programming
Creating an Object
Here, sportsBicycle and touringBicycle are the names of objects. We can use them to access fields and methods of the class.
CE204 Object-Oriented Programming
Access Members of a Class
sportsBicycle.gear - access the field gear
sportsBicycle.braking() - access the method braking()
classBicycle{
// field of classint gear = 5;
// method of classvoidbraking(){
...
}
}
// create object
Bicycle sportsBicycle = new Bicycle();
// access field and method
sportsBicycle.gear;
sportsBicycle.braking();
CE204 Object-Oriented Programming
Example: Java Class and Objects
classLamp{
// stores the value for light// true if light is on// false if light is offboolean isOn;
// method to turn on the lightvoidturnOn(){
isOn = true;
System.out.println("Light on? " + isOn);
}
// method to turnoff the lightvoidturnOff(){
isOn = false;
System.out.println("Light on? " + isOn);
}
}
CE204 Object-Oriented Programming
Example: Java Class and Objects
classMain{
publicstaticvoidmain(String[] args){
// create objects led and halogen
Lamp led = new Lamp();
Lamp halogen = new Lamp();
// turn on the light by// calling method turnOn()
led.turnOn();
// turn off the light by// calling method turnOff()
halogen.turnOff();
}
}
CE204 Object-Oriented Programming
Example: Create objects inside the same class
Note that in the previous example, we have created objects inside another class and accessed the members from that class.
However, we can also create objects inside the same class.
CE204 Object-Oriented Programming
Example: Create objects inside the same class
classLamp{
// stores the value for light// true if light is on// false if light is offboolean isOn;
// method to turn on the lightvoidturnOn(){
isOn = true;
System.out.println("Light on? " + isOn);
}
publicstaticvoidmain(String[] args){
// create an object of Lamp
Lamp led = new Lamp();
// access method using object
led.turnOn();
}
}
CE204 Object-Oriented Programming
Java Methods
CE204 Object-Oriented Programming
Java Methods
A method is a block of statements under a name that gets executes only when it is called. Every method is used to perform a specific task. The major advantage of methods is code re-usability (define the code once, and use it many times).
CE204 Object-Oriented Programming
Java Methods
In a java programming language, a method defined as a behavior of an object. That means, every method in java must belong to a class.
Every method in java must be declared inside a class.
CE204 Object-Oriented Programming
Java Methods
Every method declaration has the following characteristics.
returnType - Specifies the data type of a return value.
name - Specifies a unique name to identify it.
parameters - The data values it may accept or recieve.
{ } - Defienes the block belongs to the method.
CE204 Object-Oriented Programming
Creating a method
A method is created inside the class and it may be created with any access specifier. However, specifying access specifier is optional.
Following is the syntax for creating methods in java.
class <ClassName>{
<accessSpecifier> <returnType> <methodName>( parameters ){
...
block of statements;
...
}
}
CE204 Object-Oriented Programming
Creating a method
modifier static returnType nameOfMethod(parameter1, parameter2, ...){
// method body
}
modifier - It defines access types whether the method is public, private, and so on. static - If we use the static keyword, it can be accessed without creating objects.
CE204 Object-Oriented Programming
Creating a method
The methodName must begin with an alphabet, and the Lower-case letter is preferred.
The methodName must follow all naming rules.
If you don't want to pass parameters, we ignore it.
If a method defined with return type other than void, it must contain the return statement, otherwise, it may be ignored.
CE204 Object-Oriented Programming
Calling a method
In java, a method call precedes with the object name of the class to which it belongs and a dot operator. It may call directly if the method defined with the static modifier. Every method call must be made, as to the method name with parentheses (), and it must terminate with a semicolon.
<objectName>.<methodName>( actualArguments );
CE204 Object-Oriented Programming
Calling a method
The method call must pass the values to parameters if it has.
If the method has a return type, we must provide the receiver.
CE204 Object-Oriented Programming
Calling a Method : Example
import java.util.Scanner;
publicclassJavaMethodsExample{
int sNo;
String name;
Scanner read = new Scanner(System.in);
voidreadData(){
System.out.print("Enter Serial Number: ");
sNo = read.nextInt();
System.out.print("Enter the Name: ");
name = read.next();
}
staticvoidshowData(int sNo, String name){
System.out.println("Hello, " + name + "! your serial number is " + sNo);
}
...
CE204 Object-Oriented Programming
Calling a Method : Example
...
publicstaticvoidmain(String[] args){
JavaMethodsExample obj = new JavaMethodsExample();
obj.readData(); // method call using object
showData(obj.sNo, obj.name); // method call without using object
}
}
CE204 Object-Oriented Programming
Variable arguments of a method
In java, a method can be defined with a variable number of arguments. That means creating a method that receives any number of arguments of the same data type.
classMain{
// create a methodpublicintaddNumbers(int a, int b){
int sum = a + b;
// return valuereturn sum;
}
publicstaticvoidmain(String[] args){
int num1 = 25;
int num2 = 15;
// create an object of Main
Main obj = new Main();
// calling methodint result = obj.addNumbers(num1, num2);
System.out.println("Sum is: " + result);
}
}
CE204 Object-Oriented Programming
Java Static Method Example
classMain{
// create a methodpublicstaticintsquare(int num){
// return statementreturn num * num;
}
publicstaticvoidmain(String[] args){
int result;
// call the method// store returned value to result
result = square(10);
System.out.println("Squared value of 10 is: " + result);
}
}
CE204 Object-Oriented Programming
Java Method Parameters
classMain{
// method with no parameterpublicvoiddisplay1(){
System.out.println("Method without parameter");
}
// method with single parameterpublicvoiddisplay2(int a){
System.out.println("Method with a single parameter: " + a);
}
publicstaticvoidmain(String[] args){
// create an object of Main
Main obj = new Main();
// calling method with no parameter
obj.display1();
// calling method with the single parameter
obj.display2(24);
}
}
CE204 Object-Oriented Programming
Java Method Overloading
CE204 Object-Oriented Programming
Java Method Overloading
two or more methods may have the same name if they differ in parameters (different number of parameters, different types of parameters, or both). These methods are called overloaded methods and this feature is called method overloading.
Note: The return types of the above methods are not the same. It is because method overloading is not associated with return types. Overloaded methods may have the same or different return types, but they must differ in parameters.
CE204 Object-Oriented Programming
Why method overloading?
Suppose, you have to perform the addition of given numbers but there can be any number of arguments (let’s say either 2 or 3 arguments for simplicity).
In order to accomplish the task, you can create two methods sum2num(int, int) and sum3num(int, int, int) for two and three parameters respectively. However, other programmers, as well as you in the future may get confused as the behavior of both methods are the same but they differ by name.
The better way to accomplish this task is by overloading methods. And, depending upon the argument passed, one of the overloaded methods is called. This helps to increase the readability of the program.
CE204 Object-Oriented Programming
How to perform method overloading in Java?
Overloading by changing the number of parameters
classMethodOverloading{
privatestaticvoiddisplay(int a){
System.out.println("Arguments: " + a);
}
privatestaticvoiddisplay(int a, int b){
System.out.println("Arguments: " + a + " and " + b);
}
publicstaticvoidmain(String[] args){
display(1);
display(1, 4);
}
}
CE204 Object-Oriented Programming
How to perform method overloading in Java?
Method Overloading by changing the data type of parameters
A constructor is a special method of a class that has the same name as the class name. The constructor gets executes automatically on object creation. It does not require the explicit method call. A constructor may have parameters and access specifiers too. In java, if you do not provide any constructor the compiler automatically creates a default constructor.
CE204 Object-Oriented Programming
Java Constructor
A constructor can not have return value.
publicclassConstructorExample{
ConstructorExample() {
System.out.println("Object created!");
}
publicstaticvoidmain(String[] args){
ConstructorExample obj1 = new ConstructorExample();
ConstructorExample obj2 = new ConstructorExample();
}
}
CE204 Object-Oriented Programming
Types of Constructor
In Java, constructors can be divided into 3 types:
No-Arg Constructor
Parameterized Constructor
Default Constructor
CE204 Object-Oriented Programming
Java No-Arg Constructors
Java private no-arg constructor
classMain{
int i;
// constructor with no parameterprivateMain(){
i = 5;
System.out.println("Constructor is called");
}
publicstaticvoidmain(String[] args){
// calling the constructor without any parameter
Main obj = new Main();
System.out.println("Value of i: " + obj.i);
}
}
CE204 Object-Oriented Programming
Java No-Arg Constructors
Java public no-arg constructor
classCompany{
String name;
// public constructorpublicCompany(){
name = "My Company";
}
}
classMain{
publicstaticvoidmain(String[] args){
// object is created in another class
Company obj = new Company();
System.out.println("Company name = " + obj.name);
}
}
CE204 Object-Oriented Programming
Java Parameterized Constructor
classMain{
String languages;
// constructor accepting single value
Main(String lang) {
languages = lang;
System.out.println(languages + " Programming Language");
}
publicstaticvoidmain(String[] args){
// call constructor by passing a single value
Main obj1 = new Main("Java");
Main obj2 = new Main("Python");
Main obj3 = new Main("C");
}
}
CE204 Object-Oriented Programming
Java Default Constructor
classMain{
int a;
boolean b;
publicstaticvoidmain(String[] args){
// A default constructor is called
Main obj = new Main();
System.out.println("Default Value:");
System.out.println("a = " + obj.a);
System.out.println("b = " + obj.b);
}
}
CE204 Object-Oriented Programming
Java Default Values
The default constructor initializes any uninitialized instance variables with default values.
classMain{
int a;
boolean b;
// a private constructorprivateMain(){
a = 0;
b = false;
}
publicstaticvoidmain(String[] args){
// call the constructor
Main obj = new Main();
System.out.println("Default Value:");
System.out.println("a = " + obj.a);
System.out.println("b = " + obj.b);
}
}
CE204 Object-Oriented Programming
Constructors Overloading in Java
classMain{
String language;
// constructor with no parameter
Main() {
this.language = "Java";
}
// constructor with a single parameter
Main(String language) {
this.language = language;
}
publicvoidgetName(){
System.out.println("Programming Langauage: " + this.language);
}
...
CE204 Object-Oriented Programming
Constructors Overloading in Java
...
publicstaticvoidmain(String[] args){
// call constructor with no parameter
Main obj1 = new Main();
// call constructor with a single parameter
Main obj2 = new Main("Python");
obj1.getName();
obj2.getName();
}
}
CE204 Object-Oriented Programming
Java Inheritance
CE204 Object-Oriented Programming
Inheritance Concept
The inheritance is a very useful and powerful concept of object-oriented programming.
In java, using the inheritance concept, we can use the existing features of one class in another class. - The inheritance provides a greate advantage called code re-usability.
With the help of code re-usability, the commonly used code in an application need not be written again and again.
CE204 Object-Oriented Programming
Inheritance Concept
CE204 Object-Oriented Programming
Inheritance Concept
The inheritance is the process of acquiring the properties of one class to another class.
CE204 Object-Oriented Programming
Inheritance Basics
In inheritance, we use the terms like
parent class,
child class,
base class,
derived class,
superclass, and
subclass.
CE204 Object-Oriented Programming
Inheritance Basics
The Parent class is the class which provides features to another class.
The parent class is also known as Base class or Superclass.
The Child class is the class which receives features from another class.
The child class is also known as the Derived Class or Subclass.
CE204 Object-Oriented Programming
Inheritance Basics
In the inheritance,
the child class acquires the features from its parent class.
But the parent class never acquires the features from its child class.
CE204 Object-Oriented Programming
Inheritance Basics
There are five types of inheritances, and they are as follows.
Simple Inheritance (or) Single Inheritance
Multiple Inheritance
Multi-Level Inheritance
Hierarchical Inheritance
Hybrid Inheritance
CE204 Object-Oriented Programming
Inheritance Basics
Simple Inheritance (or) Single Inheritance
CE204 Object-Oriented Programming
Inheritance Basics
Multiple Inheritance
CE204 Object-Oriented Programming
Inheritance Basics
Multi-Level Inheritance
CE204 Object-Oriented Programming
Inheritance Basics
Hierarchical Inheritance
CE204 Object-Oriented Programming
Inheritance Basics
Hybrid Inheritance
CE204 Object-Oriented Programming
Inheritance Basics
The java programming language does not support multiple inheritance type.
However, it provides an alternate with the concept of interfaces.
CE204 Object-Oriented Programming
Creating Child Class in java
In java, we use the keyword extends to create a child class.
The following syntax used to create a child class in java.
class <ChildClassName> extends <ParentClassName>{
...
//Implementation of child class
...
}
In a java programming language, a class extends only one class.
Extending multiple classes is not allowed in java.
CE204 Object-Oriented Programming
Single Inheritance in Java Example-1
In this type of inheritance, one child class derives from one parent class.
classParentClass{
int a;
voidsetData(int a){
this.a = a;
}
}
classChildClassextendsParentClass{
voidshowData(){
System.out.println("Value of a is " + a);
}
}
classAnimal{
// field and method of the parent class
String name;
publicvoideat(){
System.out.println("I can eat");
}
}
// inherit from AnimalclassDogextendsAnimal{
// new method in subclasspublicvoiddisplay(){
System.out.println("My name is " + name);
}
}
CE204 Object-Oriented Programming
Single Inheritance in Java Example-2
classMain{
publicstaticvoidmain(String[] args){
// create an object of the subclass
Dog labrador = new Dog();
// access field of superclass
labrador.name = "Rohu";
labrador.display();
// call method of superclass// using object of subclass
labrador.eat();
}
}
CE204 Object-Oriented Programming
Single Inheritance in Java Example-2
CE204 Object-Oriented Programming
Single Inheritance / is-a relationship
In Java, inheritance is an is-a relationship. That is, we use inheritance only if there exists an is-a relationship between two classes. For example,
Car is a Vehicle
Orange is a Fruit
Surgeon is a Doctor
Dog is an Animal
Here, Car can inherit from Vehicle, Orange can inherit from Fruit, and so on.
CE204 Object-Oriented Programming
Multi-level Inheritance in java
In this type of inheritance, the child class derives from a class which already derived from another class
classParentClass{
int a;
voidsetData(int a){
this.a = a;
}
}
CE204 Object-Oriented Programming
Multi-level Inheritance in java
classChildClassextendsParentClass{
voidshowData(){
System.out.println("Value of a is " + a);
}
}
In this type of inheritance, two or more child classes derive from one parent class.
classParentClass{
int a;
voidsetData(int a){
this.a = a;
}
}
CE204 Object-Oriented Programming
Hierarchical Inheritance in java
classChildClassextendsParentClass{
voidshowData(){
System.out.println("Inside ChildClass!");
System.out.println("Value of a is " + a);
}
}
classChildClassTooextendsParentClass{
voiddisplay(){
System.out.println("Inside ChildClassToo!");
System.out.println("Value of a is " + a);
}
}
CE204 Object-Oriented Programming
Hierarchical Inheritance in java
publicclassHierarchicalInheritance{
publicstaticvoidmain(String[] args){
ChildClass child_obj = new ChildClass();
child_obj.setData(100);
child_obj.showData();
ChildClassToo childToo_obj = new ChildClassToo();
childToo_obj.setData(200);
childToo_obj.display();
}
}
CE204 Object-Oriented Programming
Hybrid Inheritance in java
The hybrid inheritance is the combination of more than one type of inheritance.
We may use any combination as a
single with multiple inheritances,
multi-level with multiple inheritances, etc.,
CE204 Object-Oriented Programming
Java Access Modifiers
CE204 Object-Oriented Programming
Java Access Modifiers
In Java, the access specifiers (also known as access modifiers) used to restrict
the scope or
accessibility of a
class,
constructor,
variable,
method or
data member of class and interface.
CE204 Object-Oriented Programming
Java Access Modifiers
There are four access specifiers, and their list is below.
default (or) no modifier
public
protected
private
CE204 Object-Oriented Programming
Java Access Modifiers
In java, we can not employ all access specifiers on everything. The following table describes where we can apply the access specifiers.
CE204 Object-Oriented Programming
Java Access Modifiers
Let's look at the following example java code,
which generates an error
because a class does not allow private access specifier
unless it is an inner class.
privateclassSample{
...
}
CE204 Object-Oriented Programming
Java Access Modifiers
In java, the accessibility of the members of a class or interface depends on its access specifiers. The following table provides information about the visibility of both data members and methods.
CE204 Object-Oriented Programming
Java Access Modifiers
The public members can be accessed everywhere.
The private members can be accessed only inside the same class.
The protected members are accessible to every child class (same package or other packages).
The default members are accessible within the same package but not outside the package.
CE204 Object-Oriented Programming
Java Access Modifiers
classParentClass{
int a = 10;
publicint b = 20;
protectedint c = 30;
privateint d = 40;
voidshowData(){
System.out.println("Inside ParentClass");
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
System.out.println("d = " + d);
}
}
publicclassMain{
publicstaticvoidmain(String[] main){
// create an object of Data
Data d = new Data();
// access private variable and field from another class
d.name = "My App";
}
}
CE204 Object-Oriented Programming
Java Access Modifiers
Private Access Modifier
When we run the program, we will get the following error
Main.java:18: error: name has private access in Data
d.name = "My App";
^
publicclassMain{
publicstaticvoidmain(String[] main){
Data d = new Data();
// access the private variable using the getter and setter
d.setName("My App");
System.out.println(d.getName());
}
}
CE204 Object-Oriented Programming
Java Access Modifiers
Private Access Modifier
We cannot declare classes and interfaces private in Java.
However, the nested classes can be declared private.
CE204 Object-Oriented Programming
Java Access Modifiers
Protected Access Modifier
When methods and data members are declared protected,
we can access them within the same package
as well as from subclasses.
CE204 Object-Oriented Programming
Java Access Modifiers
Protected Access Modifier
classAnimal{
// protected methodprotectedvoiddisplay(){
System.out.println("I am an animal");
}
}
classDogextendsAnimal{
publicstaticvoidmain(String[] args){
// create an object of Dog class
Dog dog = new Dog();
// access protected method
dog.display();
}
}
CE204 Object-Oriented Programming
Java Access Modifiers
Protected Access Modifier (Ex-2)
classAnimal{
protected String name;
protectedvoiddisplay(){
System.out.println("I am an animal.");
}
}
classDogextendsAnimal{
publicvoidgetInfo(){
System.out.println("My name is " + name);
}
}
CE204 Object-Oriented Programming
Java Access Modifiers
Protected Access Modifier (Ex-2)
classMain{
publicstaticvoidmain(String[] args){
// create an object of the subclass
Dog labrador = new Dog();
// access protected field and method// using the object of subclass
labrador.name = "Rocky";
labrador.display();
labrador.getInfo();
}
}
CE204 Object-Oriented Programming
Java Access Modifiers
Protected Access Modifier
We cannot declare classes or interfaces protected in Java.
CE204 Object-Oriented Programming
Java Access Modifiers
Public Access Modifier
When methods, variables, classes, and so on are declared public,
then we can access them from anywhere.
// Animal.java file// public classpublicclassAnimal{
// public variablepublicint legCount;
// public methodpublicvoiddisplay(){
System.out.println("I am an animal.");
System.out.println("I have " + legCount + " legs.");
}
}
CE204 Object-Oriented Programming
Java Access Modifiers
Public Access Modifier
// Main.javapublicclassMain{
publicstaticvoidmain( String[] args ){
// accessing the public class
Animal animal = new Animal();
// accessing the public variable
animal.legCount = 4;
// accessing the public method
animal.display();
}
}
CE204 Object-Oriented Programming
Java Constructors in Inheritance
CE204 Object-Oriented Programming
Java Constructors in Inheritance
It is very important to understand how the constructors get executed in the inheritance concept.
In the inheritance, the constructors never get inherited to any child class.
In java, the default constructor of a parent class called automatically by the constructor of its child class.
That means when we create an object of the child class,
the parent class constructor executed, followed by the child class constructor executed.
CE204 Object-Oriented Programming
Java Constructors in Inheritance - Example
classParentClass{
int a;
ParentClass(){
System.out.println("Inside ParentClass constructor!");
}
}
publicclassConstructorInInheritance{
publicstaticvoidmain(String[] args){
ChildClass obj = new ChildClass();
}
}
CE204 Object-Oriented Programming
Java Constructors in Inheritance
The parameterized constructor of parent class must be called explicitly using the super keyword.
CE204 Object-Oriented Programming
Method Overriding in Java Inheritance
classAnimal{
// method in the superclasspublicvoideat(){
System.out.println("I can eat");
}
}
CE204 Object-Oriented Programming
Method Overriding in Java Inheritance
// Dog inherits AnimalclassDogextendsAnimal{
// overriding the eat() method@Overridepublicvoideat(){
System.out.println("I eat dog food");
}
// new method in subclasspublicvoidbark(){
System.out.println("I can bark");
}
}
CE204 Object-Oriented Programming
Method Overriding in Java Inheritance
classMain{
publicstaticvoidmain(String[] args){
// create an object of the subclass
Dog labrador = new Dog();
// call the eat() method
labrador.eat();
labrador.bark();
}
}
CE204 Object-Oriented Programming
Method Overriding in Java Inheritance
In the above example, the eat() method is present in both the superclass Animal and the subclass Dog.
Here, we have created an object labrador of Dog.
Now when we call eat() using the object labrador, the method inside Dog is called. This is because the method inside the derived class overrides the method inside the base class.
CE204 Object-Oriented Programming
super Keyword in Java Inheritance
CE204 Object-Oriented Programming
super Keyword in Java Inheritance
the same method in the subclass overrides the method in superclass.
In such a situation, the super keyword is used to call the method of the parent class from the method of the child class.
CE204 Object-Oriented Programming
super Keyword in Java Inheritance
classAnimal{
// method in the superclasspublicvoideat(){
System.out.println("I can eat");
}
}
CE204 Object-Oriented Programming
super Keyword in Java Inheritance
// Dog inherits AnimalclassDogextendsAnimal{
// overriding the eat() method@Overridepublicvoideat(){
// call method of superclasssuper.eat();
System.out.println("I eat dog food");
}
// new method in subclasspublicvoidbark(){
System.out.println("I can bark");
}
}
CE204 Object-Oriented Programming
super Keyword in Java Inheritance
classMain{
publicstaticvoidmain(String[] args){
// create an object of the subclass
Dog labrador = new Dog();
// call the eat() method
labrador.eat();
labrador.bark();
}
}
CE204 Object-Oriented Programming
Java this Keyword
CE204 Object-Oriented Programming
Java this Keyword
In Java, this keyword is used to refer to
the current object
inside a
method or a
constructor
CE204 Object-Oriented Programming
Java this Keyword
classMain{
int instVar;
Main(int instVar){
this.instVar = instVar;
System.out.println("this reference = " + this);
}
publicstaticvoidmain(String[] args){
Main obj = new Main(8);
System.out.println("object reference = " + obj);
}
}
CE204 Object-Oriented Programming
Using this for Ambiguity Variable Names
In Java, it is not allowed to declare two or more variables having the same name inside a scope (class scope or method scope).
However, instance variables and parameters may have the same name.
CE204 Object-Oriented Programming
Using this for Ambiguity Variable Names
WRONG
classMain{
int age;
Main(int age){
age = age;
}
publicstaticvoidmain(String[] args){
Main obj = new Main(8);
System.out.println("obj.age = " + obj.age);
}
}
CE204 Object-Oriented Programming
Using this for Ambiguity Variable Names
CORRECT
classMain{
int age;
Main(int age){
this.age = age;
}
publicstaticvoidmain(String[] args){
Main obj = new Main(8);
System.out.println("obj.age = " + obj.age);
}
}
CE204 Object-Oriented Programming
this with Getters and Setters
Another common use of this keyword is in setters and getters methods of a class
...
publicstaticvoidmain( String[] args ){
Main obj = new Main();
// calling the setter and the getter method
obj.setName("Toshiba");
System.out.println("obj.name: "+obj.getName());
}
}
CE204 Object-Oriented Programming
Using this in Constructor Overloading
While working with constructor overloading,
we might have to invoke one constructor from another constructor.
In such a case,
we cannot call the constructor explicitly. Instead,
we have to use this keyword.
CE204 Object-Oriented Programming
Using this in Constructor Overloading
classComplex{
privateint a, b;
// constructor with 2 parametersprivateComplex( int i, int j ){
this.a = i;
this.b = j;
}
// constructor with single parameterprivateComplex(int i){
// invokes the constructor with 2 parametersthis(i, i);
}
// constructor with no parameterprivateComplex(){
// invokes the constructor with single parameterthis(0);
}
...
CE204 Object-Oriented Programming
Using this in Constructor Overloading
@Overridepublic String toString(){
returnthis.a + " + " + this.b + "i";
}
publicstaticvoidmain( String[] args ){
// creating object of Complex class// calls the constructor with 2 parameters
Complex c1 = new Complex(2, 3);
// calls the constructor with a single parameter
Complex c2 = new Complex(3);
// calls the constructor with no parameters
Complex c3 = new Complex();
// print objects
System.out.println(c1);
System.out.println(c2);
System.out.println(c3);
}
}
CE204 Object-Oriented Programming
Using this in Constructor Overloading
In the example, we have used this keyword,
to call the constructor Complex(int i, int j) from the constructor Complex(int i)
to call the constructor Complex(int i) from the constructor Complex()
the line, System.out.println(c1); process, the toString() is called Since we override the toString() method inside our class, we get the output according to that method.
CE204 Object-Oriented Programming
Using this in Constructor Overloading
One of the huge advantages of this() is to reduce the amount of duplicate code. However, we should be always careful while using this().
This is because calling constructor from another constructor adds overhead and it is a slow process. Another huge advantage of using this() is to reduce the amount of duplicate code.
CE204 Object-Oriented Programming
Using this in Constructor Overloading
Invoking one constructor from another constructor is called explicit constructor invocation.
CE204 Object-Oriented Programming
Passing this as an Argument
We can use this keyword to pass the current object as an argument to a method
classThisExample{
// declare variablesint x;
int y;
ThisExample(int x, int y) {
// assign values of variables inside constructorthis.x = x;
this.y = y;
// value of x and y before calling add()
System.out.println("Before passing this to addTwo() method:");
System.out.println("x = " + this.x + ", y = " + this.y);
// call the add() method passing this as argument
add(this);
// value of x and y after calling add()
System.out.println("After passing this to addTwo() method:");
System.out.println("x = " + this.x + ", y = " + this.y);
}
voidadd(ThisExample o){
o.x += 2;
o.y += 2;
}
}
In the example, inside the constructor ThisExample(), notice the line, add(this);
Here, we are calling the add() method by passing this as an argument.
Since this keyword contains the reference to the object obj of the class,
we can change the value of x and y inside the add() method.
CE204 Object-Oriented Programming
Java instanceof Operator
CE204 Object-Oriented Programming
Java instanceof Operator
The instanceof operator in Java is used to
check whether an object is an instance of
a particular class or not.
Its syntax is
objectName instanceOf className;
CE204 Object-Oriented Programming
Example: Java instanceof
classMain{
publicstaticvoidmain(String[] args){
// create a variable of string type
String name = "My App";
// checks if name is instance of Stringboolean result1 = name instanceof String;
System.out.println("name is an instance of String: " + result1);
// create an object of Main
Main obj = new Main();
// checks if obj is an instance of Mainboolean result2 = obj instanceof Main;
System.out.println("obj is an instance of Main: " + result2);
}
}
CE204 Object-Oriented Programming
Example: Java instanceof
In the example, we have created a variable name of the String type and an object obj of the Main class.
Here, we have used the instanceof operator to check whether name and obj are instances of the String and Main class respectively. And, the operator returns true in both cases.
CE204 Object-Oriented Programming
Java instanceof during Inheritance
We can use the instanceof operator to check if objects of the subclass is also an instance of the superclass.
CE204 Object-Oriented Programming
Java instanceof during Inheritance
// Java Program to check if an object of the subclass// is also an instance of the superclass// superclassclassAnimal{
}
// subclassclassDogextendsAnimal{
}
classMain{
publicstaticvoidmain(String[] args){
// create an object of the subclass
Dog d1 = new Dog();
// checks if d1 is an instance of the subclass
System.out.println(d1 instanceof Dog); // prints true// checks if d1 is an instance of the superclass
System.out.println(d1 instanceof Animal); // prints true
}
}
CE204 Object-Oriented Programming
Java instanceof during Inheritance
In the above example, we have created a subclass Dog that inherits from the superclass Animal. We have created an object d1 of the Dog class.
Inside the print statement, notice the expression,
d1 instanceof Animal
Here, we are using the instanceof operator to check whether d1 is also an instance of the superclass Animal
CE204 Object-Oriented Programming
Java instanceof in Interface
The instanceof operator is also used to check whether an object of a class is
also an instance of the interface implemented by the class
CE204 Object-Oriented Programming
Java instanceof in Interface
// Java program to check if an object of a class is also// an instance of the interface implemented by the classinterfaceAnimal{
}
classDogimplementsAnimal{
}
CE204 Object-Oriented Programming
Java instanceof in Interface
classMain{
publicstaticvoidmain(String[] args){
// create an object of the Dog class
Dog d1 = new Dog();
// checks if the object of Dog// is also an instance of Animal
System.out.println(d1 instanceof Animal); // returns true
}
}
CE204 Object-Oriented Programming
Java instanceof in Interface
In the example, the Dog class implements the Animal interface. Inside the print statement, notice the expression,
d1 instanceof Animal
Here, d1 is an instance of Dog class. The instanceof operator checks
if d1 is also an instance of the interface Animal.
CE204 Object-Oriented Programming
Java instanceof in Interface
In Java, all the classes are inherited from the Object class. So, instances of all the classes are also an instance of the Object class.