Introduction to Object Oriented ProgrammingMoutaz Haddara
An Introduction to Object-Oriented Programming (OOP)
Download the presentation to view it correctly, as it has some animations that won't show here.
If you have any questions, please contact me. You are free to use it this presentation, but it would be nice at least to give me some credit :)
Content:
1- History of Programming
2. Objects and Classes
3- Abstraction, Inheritance, Encapsulation, and Polymorphism
Wikidata tutorial presented at the U.S. National Archives on October 10, 2015 as part of WikiConference USA.
Contains edits and corrections from version presented.
Released under CC0.
Inheritance in java is a mechanism in which one object acquires all the properties and behaviors of parent object. The idea behind inheritance in java is that you can create new classes that are built upon existing classes.
Introduction to Object Oriented ProgrammingMoutaz Haddara
An Introduction to Object-Oriented Programming (OOP)
Download the presentation to view it correctly, as it has some animations that won't show here.
If you have any questions, please contact me. You are free to use it this presentation, but it would be nice at least to give me some credit :)
Content:
1- History of Programming
2. Objects and Classes
3- Abstraction, Inheritance, Encapsulation, and Polymorphism
Wikidata tutorial presented at the U.S. National Archives on October 10, 2015 as part of WikiConference USA.
Contains edits and corrections from version presented.
Released under CC0.
Inheritance in java is a mechanism in which one object acquires all the properties and behaviors of parent object. The idea behind inheritance in java is that you can create new classes that are built upon existing classes.
OWL stands for Web Ontology Language
OWL is built on top of RDF
OWL is for processing information on the web
OWL was designed to be interpreted by computers
OWL was not designed for being read by people
OWL is written in XML
OWL has three sublanguages
- OWL Lite , OWL DL , OWL Full
OWL is a W3C standard
NP completeness. Classes P and NP are two frequently studied classes of problems in computer science. Class P is the set of all problems that can be solved by a deterministic Turing machine in polynomial time.
Given two integer arrays val[0...n-1] and wt[0...n-1] that represents values and weights associated with n items respectively. Find out the maximum value subset of val[] such that sum of the weights of this subset is smaller than or equal to knapsack capacity W. Here the BRANCH AND BOUND ALGORITHM is discussed .
Problem solving
Problem formulation
Search Techniques for Artificial Intelligence
Classification of AI searching Strategies
What is Search strategy ?
Defining a Search Problem
State Space Graph versus Search Trees
Graph vs. Tree
Problem Solving by Search
What is Abstraction and Encapsulation? Learn by simple example of what is encapsulation and what is abstraction.
Very common interview question and Part of Object Oriented Programming.
Watch Video to understand it well - https://www.youtube.com/watch?v=OCR1i0H-0YM
Visit our site -
http://www.cheezycode.com/
Concept of OOPS with real life examplesNeha Sharma
It includes Programming paradigm and concepts of Object Oriented programming (Features with real life examples) with sample code of class and objects.
For better understanding, you can watch video and subscribe my channel:
For Hindi: https://youtu.be/gsESptJbwno
For English: https://youtu.be/TbmyQePGh4g
OWL stands for Web Ontology Language
OWL is built on top of RDF
OWL is for processing information on the web
OWL was designed to be interpreted by computers
OWL was not designed for being read by people
OWL is written in XML
OWL has three sublanguages
- OWL Lite , OWL DL , OWL Full
OWL is a W3C standard
NP completeness. Classes P and NP are two frequently studied classes of problems in computer science. Class P is the set of all problems that can be solved by a deterministic Turing machine in polynomial time.
Given two integer arrays val[0...n-1] and wt[0...n-1] that represents values and weights associated with n items respectively. Find out the maximum value subset of val[] such that sum of the weights of this subset is smaller than or equal to knapsack capacity W. Here the BRANCH AND BOUND ALGORITHM is discussed .
Problem solving
Problem formulation
Search Techniques for Artificial Intelligence
Classification of AI searching Strategies
What is Search strategy ?
Defining a Search Problem
State Space Graph versus Search Trees
Graph vs. Tree
Problem Solving by Search
What is Abstraction and Encapsulation? Learn by simple example of what is encapsulation and what is abstraction.
Very common interview question and Part of Object Oriented Programming.
Watch Video to understand it well - https://www.youtube.com/watch?v=OCR1i0H-0YM
Visit our site -
http://www.cheezycode.com/
Concept of OOPS with real life examplesNeha Sharma
It includes Programming paradigm and concepts of Object Oriented programming (Features with real life examples) with sample code of class and objects.
For better understanding, you can watch video and subscribe my channel:
For Hindi: https://youtu.be/gsESptJbwno
For English: https://youtu.be/TbmyQePGh4g
Object Oriented Programming For Engineering Students as well as for B.Tech -IT. Covers Almost All From The Basics.
For more:
Google Search:: Prabhaharan Ellaiyan
Object Oriented Programming is a programming concept that works on the principle that objects are the most important part of your program. It allows users create the objects that they want and then create methods to handle those objects. Manipulating these objects to get results is the goal of Object Oriented Programming.
Object Oriented Programming popularly known as OOP, is used in a modern programming language like Java..
he main aim of object-oriented programming is to implement real-world entities for example object, classes, abstraction, inheritance, polymorphism, etc.
Pdf Covers-- Concept of OOPS, Introduction to Java, Java Features, History of Java, Naming of Java, Java version release, Structure of Java Program, Creating a Simple Java Program, Java Virtual Machine
This Presentation describes how to document your work and save the notebook in Google Colab. Most of the People suffers on writing the equation using latex or other software. But Using colab its made easy by markdown scripting.
Cosmetic shop management system project report.pdfKamal Acharya
Buying new cosmetic products is difficult. It can even be scary for those who have sensitive skin and are prone to skin trouble. The information needed to alleviate this problem is on the back of each product, but it's thought to interpret those ingredient lists unless you have a background in chemistry.
Instead of buying and hoping for the best, we can use data science to help us predict which products may be good fits for us. It includes various function programs to do the above mentioned tasks.
Data file handling has been effectively used in the program.
The automated cosmetic shop management system should deal with the automation of general workflow and administration process of the shop. The main processes of the system focus on customer's request where the system is able to search the most appropriate products and deliver it to the customers. It should help the employees to quickly identify the list of cosmetic product that have reached the minimum quantity and also keep a track of expired date for each cosmetic product. It should help the employees to find the rack number in which the product is placed.It is also Faster and more efficient way.
Quality defects in TMT Bars, Possible causes and Potential Solutions.PrashantGoswami42
Maintaining high-quality standards in the production of TMT bars is crucial for ensuring structural integrity in construction. Addressing common defects through careful monitoring, standardized processes, and advanced technology can significantly improve the quality of TMT bars. Continuous training and adherence to quality control measures will also play a pivotal role in minimizing these defects.
Forklift Classes Overview by Intella PartsIntella Parts
Discover the different forklift classes and their specific applications. Learn how to choose the right forklift for your needs to ensure safety, efficiency, and compliance in your operations.
For more technical information, visit our website https://intellaparts.com
Water scarcity is the lack of fresh water resources to meet the standard water demand. There are two type of water scarcity. One is physical. The other is economic water scarcity.
Vaccine management system project report documentation..pdfKamal Acharya
The Division of Vaccine and Immunization is facing increasing difficulty monitoring vaccines and other commodities distribution once they have been distributed from the national stores. With the introduction of new vaccines, more challenges have been anticipated with this additions posing serious threat to the already over strained vaccine supply chain system in Kenya.
Event Management System Vb Net Project Report.pdfKamal Acharya
In present era, the scopes of information technology growing with a very fast .We do not see any are untouched from this industry. The scope of information technology has become wider includes: Business and industry. Household Business, Communication, Education, Entertainment, Science, Medicine, Engineering, Distance Learning, Weather Forecasting. Carrier Searching and so on.
My project named “Event Management System” is software that store and maintained all events coordinated in college. It also helpful to print related reports. My project will help to record the events coordinated by faculties with their Name, Event subject, date & details in an efficient & effective ways.
In my system we have to make a system by which a user can record all events coordinated by a particular faculty. In our proposed system some more featured are added which differs it from the existing system such as security.
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...Dr.Costas Sachpazis
Terzaghi's soil bearing capacity theory, developed by Karl Terzaghi, is a fundamental principle in geotechnical engineering used to determine the bearing capacity of shallow foundations. This theory provides a method to calculate the ultimate bearing capacity of soil, which is the maximum load per unit area that the soil can support without undergoing shear failure. The Calculation HTML Code included.
About
Indigenized remote control interface card suitable for MAFI system CCR equipment. Compatible for IDM8000 CCR. Backplane mounted serial and TCP/Ethernet communication module for CCR remote access. IDM 8000 CCR remote control on serial and TCP protocol.
• Remote control: Parallel or serial interface.
• Compatible with MAFI CCR system.
• Compatible with IDM8000 CCR.
• Compatible with Backplane mount serial communication.
• Compatible with commercial and Defence aviation CCR system.
• Remote control system for accessing CCR and allied system over serial or TCP.
• Indigenized local Support/presence in India.
• Easy in configuration using DIP switches.
Technical Specifications
Indigenized remote control interface card suitable for MAFI system CCR equipment. Compatible for IDM8000 CCR. Backplane mounted serial and TCP/Ethernet communication module for CCR remote access. IDM 8000 CCR remote control on serial and TCP protocol.
Key Features
Indigenized remote control interface card suitable for MAFI system CCR equipment. Compatible for IDM8000 CCR. Backplane mounted serial and TCP/Ethernet communication module for CCR remote access. IDM 8000 CCR remote control on serial and TCP protocol.
• Remote control: Parallel or serial interface
• Compatible with MAFI CCR system
• Copatiable with IDM8000 CCR
• Compatible with Backplane mount serial communication.
• Compatible with commercial and Defence aviation CCR system.
• Remote control system for accessing CCR and allied system over serial or TCP.
• Indigenized local Support/presence in India.
Application
• Remote control: Parallel or serial interface.
• Compatible with MAFI CCR system.
• Compatible with IDM8000 CCR.
• Compatible with Backplane mount serial communication.
• Compatible with commercial and Defence aviation CCR system.
• Remote control system for accessing CCR and allied system over serial or TCP.
• Indigenized local Support/presence in India.
• Easy in configuration using DIP switches.
Saudi Arabia stands as a titan in the global energy landscape, renowned for its abundant oil and gas resources. It's the largest exporter of petroleum and holds some of the world's most significant reserves. Let's delve into the top 10 oil and gas projects shaping Saudi Arabia's energy future in 2024.
Student information management system project report ii.pdfKamal Acharya
Our project explains about the student management. This project mainly explains the various actions related to student details. This project shows some ease in adding, editing and deleting the student details. It also provides a less time consuming process for viewing, adding, editing and deleting the marks of the students.
Courier management system project report.pdfKamal Acharya
It is now-a-days very important for the people to send or receive articles like imported furniture, electronic items, gifts, business goods and the like. People depend vastly on different transport systems which mostly use the manual way of receiving and delivering the articles. There is no way to track the articles till they are received and there is no way to let the customer know what happened in transit, once he booked some articles. In such a situation, we need a system which completely computerizes the cargo activities including time to time tracking of the articles sent. This need is fulfilled by Courier Management System software which is online software for the cargo management people that enables them to receive the goods from a source and send them to a required destination and track their status from time to time.
Welcome to WIPAC Monthly the magazine brought to you by the LinkedIn Group Water Industry Process Automation & Control.
In this month's edition, along with this month's industry news to celebrate the 13 years since the group was created we have articles including
A case study of the used of Advanced Process Control at the Wastewater Treatment works at Lleida in Spain
A look back on an article on smart wastewater networks in order to see how the industry has measured up in the interim around the adoption of Digital Transformation in the Water Industry.
Water Industry Process Automation and Control Monthly - May 2024.pdf
Cs2305 programming paradigms lecturer notes
1. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
1
Unit I – Object Oriented Programming – Fundamentals
1.1 Review of OOP
1.2 Objects and Classes in Java
1.3 Defining Classes
1.4 Methods
1.5 Access Specifiers
1.6 Static Members
1.7 Constructors
1.8 Finalize method
1.9 Arrays
1.10 Strings
1.11 Package
1.12 JavaDoc Comments
Programming Paradigms:
A programming paradigm is a general approach, orientation, or philosophy of programming
that can be used when implementing a program. One paradigm may be generally better for certain
kinds of problems than other paradigms are for those problems, and a paradigm may be better for
certain kinds of problems than for other kinds of problems.
Four most common paradigms:
1. imperative (or procedural) - C
2. applicative (or functional) - ML
3. rule-based (or logic) - prolog
4. object oriented – small talk, C++, Java
1.1 Review of OOP
Process oriented model:
In Process oriented model code is written around what is happening.
This approach characterizes a program as a series of linear steps i.e. the code.
It is the code acting on data.
In a conventional application we typically:
o decompose it into a series of functions,
o define data structures that those functions act upon
o there is no relationship between the two other than the functions act on the data
Steps in process oriented approach:
1. Procedure is determined i.e. Algorithm
2. Appropriate ways to store data i.e. Data Structure.
Algorithm + Data Structure = Programs
Disadvantage of process oriented model:
As program grows larger the complexity increases.
2. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
2
Object Oriented Programming:
It organizes program around its data i.e. Objects and set of well defined interface to that data.
Object oriented programming is characterized as data controlling access to code.
• How is OOP different to conventional programming?
– Decompose the application into abstract data types by identifying some useful
entities/abstractions
– An abstract type is made up of a series of behaviours and the data that those
behaviours use.
Steps in Object Oriented Programming:
1. Puts the data first.
2. Looks for algorithm to operate on the data.
Benefits of OO programming
a. Easier to understand (closer to how we view the world)
b. Easier to maintain (localised changes)
c. Modular (classes and objects)
d. Good level of code reuse (aggregation and inheritance)
• Understanding OOP is fundamental to writing good Java applications
– Improves design of your code
– Improves understanding of the Java APIs
• There are several concepts underlying OOP:
Object
Abstract Types (Classes)
Encapsulation (or Information Hiding)
Aggregation
Inheritance
Polymorphism
Dynamic binding
Message passing
Object
Objects are basic runtime entity in an object oriented system. It is a real world entity & an
bundle of related state and behaviour. Object is an instance of Class, We can access Class
Member using its Object.
e.g-Person, Place ,Book etc
Object in java are created using the new operator.
Eg:
Rectangle rec1; // Declare the object
Rec1 = new Rectangle //instantiate the object
The above statements can also be combined as follows
3. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
3
Rectangle rec1 = new Rectangle;
Abstract Data Types
• Identifying abstract types is part of the modelling/design process
– The types that are useful to model may vary according to the individual application
– For example a payroll system might need to know about Departments, Employees,
Managers, Salaries, etc
– An E-Commerce application may need to know about Users, Shopping Carts,
Products, etc
• Object-oriented languages provide a way to define abstract data types, and then create
objects from them
– It‘s a template (or ‗cookie cutter‘) from which we can create new objects
– For example, a Car class might have attributes of speed, colour, and behaviours of
accelerate, brake, etc
– An individual Car object will have the same behaviours but its own values assigned
to the attributes (e.g. 30mph, Red, etc)
Classes
A class is a prototype from which objects are created. The entire set of data and code of an
object can be made a user defined data-type with the help of a Class. In fact objects are
variables of the type class.
e.g-object ORANGE belongs to Class FRUIT
Defining the Class:
A class is defined by the user is data type with the template that helps in defining the properties.
Once the class type has been defined we can create the variables of that type using declarations
that are similar to the basic type declarations. In java instances of the classes which are actual
objects
Eg:
classclassname [extends superclassname]
{
[fields declarations;]
[methods declaration;]
}
Field Declaration
Data is encapsulated in a class by placing data fields inside the body of the class definition. These
variables are called as instance variables.
4. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
4
Class Rectangle
{
int length;
int width;
}
Method Declaration
A Class with only data fields has no life, we must add methods for manipulating the data contained
in the class. Methods are declared inside the class immediate after the instance variables
declaration.
Eg:
class Rectangle
{
int length; //instance variables
int width;
Void getData(int x, int y) // Method Declartion {
Length =x;
Width = y;
} }
Encapsulation
• The data (state) of an object is private – it cannot be accessed directly.
• The state can only be changed through its behaviour, otherwise known as its public interface
or contract
• This is called encapsulation
Main benefit of encapsulation
o Internal state and processes can be changed independently of the public interface
o Limits the amount of large-scale changes required to a system
Example: Automatic transmission on a car.
It encapsulates hundreds of bit of information about engine such as how much
acceleration is given, pitch of surface, position of shift lever.
All the information about engine is encapsulated.
The method of affecting this complex encapsulation is by moving the gear shift lever.
We can affect transmission only by using gear shift lever and can‘t affect transmission
by using the turn signal or windshield wiper.
Thus gear shift lever is a well defined interface to the transmission.
What occurs inside the transmission does not affect the objects outside the transmission.
o For example, shifting gear does not turn on the head lights.
Private Data
Public Interface
"The Doughnut Diagram"
Showing that an object has
private state and public
behaviour. State can only be
changed by invoking some
behaviour
5. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
5
Aggregation
• Aggregation is the ability to create new classes out of existing classes
– Treating them as building blocks or components
• Aggregation allows reuse of existing code
– ―Holy Grail‖ of software engineering
• Two forms of aggregation
• Whole-Part relationships
– Car is made of Engine, Chassis, Wheels
• Containment relationships
– A Shopping Cart contains several Products
– A List contains several Items
Inheritance
• Inheritance is the ability to define a new class in terms of an existing class
– The existing class is the parent, base or superclass
– The new class is the child, derived or subclass
• The child class inherits all of the attributes and behaviour of its parent class
– It can then add new attributes or behaviour
– Or even alter the implementation of existing behaviour
• Inheritance is therefore another form of code reuse
The bird 'robin ' is a part of the class 'flying bird' which is again a part of the class 'bird'.
Polymorphism
Polymorphism means the ability to take more than one form.
Subclasses of a class can define their own unique behaviors and yet share some of the same
functionality of the parent class.
6. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
6
Dynamic Binding
Binding refers to the linking of a procedure call to the code to be executed.
Dynamic binding means that the code associated with a given procedure call is not known
until the time of the call at run-time.
Message Communication
Objects communicate with one another by sending and receiving information. A message
for an object is a request for execution of a procedure. Message passing involves specifying
the name of the object, the name of the function (message) and the information to be sent.
Basics of Java
Java is a programming language and a platform.
Application of Java
According to sun Microsystems, 3 billion devices run java.
1. Desktop application such as acrobat reader, media player, antivirus,etc
2. Web application such as irctc.co.in,etc
3. Enterprise application such as banking applications
4. Mobile
5. Embedded systems
6. Smart card
7. Games and so on
Types of Java
Basically Java Applications can be 4 types
1. Standalone application(like Microsoft office) Technology: core java
2. Client Server application(like yahoo chat) Technology: core java and web technology
3. Web Application(like orkut, facebook etc) Technology: Servlet, JSP, Struts, Hibernate etc.
Any web server is required to run this application like TOMCAT
4. Distributed Application (like banking application) Technology: EJB application
History of java
James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java language in June
1991.
Originally designed for small, embedded systems in electronic appliances like setup box.
Initially called Oak, and was developed as a part of Green project.
In 1995, Oak was renamed as Java.
Characteristics of Java
Java is simple
Java is object-oriented
Java is distributed
Java is interpreted
Java is robust
Java is secure
Java is architecture-neutral
Java is portable
Java‘s performance
Java is multithreaded
Java is dynamic
7. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
7
JDK Versions
JDK 1.02 (1995)
JDK 1.1 (1996)
Java 2 SDK v 1.2 (a.k.a JDK 1.2, 1998)
Java 2 SDK v 1.3 (a.k.a JDK 1.3, 2000)
Java 2 SDK v 1.4 (a.k.a JDK 1.4, 2002)
Java 2 SDK v 1.5 (a.k.a JDK 1.4, 2004)
Java 2 SDK v 1.6 (a.k.a JDK 1.4, 2006)
Java 2 SDK v 1.7 (a.k.a JDK 1.4, 2011)
JDK Editions
Java Standard Edition (J2SE)
o J2SE can be used to develop client-side standalone applications or applets.
Java Enterprise Edition (J2EE)
o J2EE can be used to develop server-side applications such as Java servlets and Java
ServerPages.
Java Micro Edition (J2ME).
o J2ME can be used to develop applications for mobile devices such as cell phones.
Java IDE Tools
Forte by Sun MicroSystems
Borland JBuilder
Microsoft Visual J++
WebGain Cafe
IBM Visual Age for Java
Basic Structure
Simple Example
1. Create a Java program using notepad and save with extension .java.
2. Install the JDK1.6 or higher, if not , download and install it
3. Set path of the bin directory under jdk.
4. Compile: javac filename.java
5. Run: java filename
First Java Program:
Let us look at a simple code that would print the words Hello World.
public class MyFirstJavaProgram {
/* This is my first java program.
* This will print 'Hello World' as the output
8. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
8
*/
public static void main(String []args) {
System.out.println("Hello World"); // prints Hello World
}
}
Lets look at how to save the file, compile and run the program. Please follow the steps given
below:
Open notepad and add the code as above.
Save the file as : MyFirstJavaProgram.java.
Open a command prompt window and go o the directory where you saved the class. Assume
its C:.
Type ' javac MyFirstJavaProgram.java ' and press enter to compile your code. If there are no
errors in your code the command prompt will take you to the next line.( Assumption : The
path variable is set).
Now type ' java MyFirstJavaProgram ' to run your program.
You will be able to see ' Hello World ' printed on the window.
C : > javac MyFirstJavaProgram.java
C : > java MyFirstJavaProgram
Hello World
Basic Syntax:
About Java programs, it is very important to keep in mind the following points.
Case Sensitivity - Java is case sensitive which means identifier Hello and hello would have
different meaning in Java.
Class Names - For all class names the first letter should be in Upper Case.
If several words are used to form a name of the class each inner words first letter should be
in Upper Case.
Example class MyFirstJavaClass
Method Names - All method names should start with a Lower Case letter.
If several words are used to form the name of the method, then each inner word's first letter
should be in Upper Case.
Example public void myMethodName()
Program File Name - Name of the program file should exactly match the class name.
When saving the file you should save it using the class name (Remember java is case
sensitive) and append '.java' to the end of the name. (if the file name and the class name do
not match your program will not compile).
Example : Assume 'MyFirstJavaProgram' is the class name. Then the file should be saved as
'MyFirstJavaProgram.java'
public static void main(String args[]) - java program processing starts from the main()
method which is a mandatory part of every java program..
Java Basics
Java Identifiers:
All java components require names. Names used for classes, variables and methods are called
identifiers.
9. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
9
In java there are several points to remember about identifiers. They are as follows:
All identifiers should begin with a letter (A to Z or a to z ), currency character ($) or an
underscore (_).
After the first character identifiers can have any combination of characters.
A key word cannot be used as an identifier.
Most importantly identifiers are case sensitive.
Examples of legal identifiers:age, $salary, _value, __1_value
Examples of illegal identifiers : 123abc, -salary
Java Modifiers:
Like other languages it is possible to modify classes, methods etc by using modifiers. There are
two categories of modifiers.
Access Modifiers : default(friend), public , protected, private
Non-access Modifiers : final, abstract, strictfp
Java Variables:
We would see following type of variables in Java:
Local Variables
Class Variables (Static Variables)
Instance Variables (Non static variables)
Java Keywords:
The following list shows the reserved words in Java. These reserved words may not be used as
constant or variable or any other identifier names.
1.2 Object and Classes in Java
The class is at the core of Java. It is the logical construct upon which the entire Java
language is built because it defines the shape and nature of an object. As such, the class forms the
basis for object-oriented programming in Java. The entire set of data and code of an object can be
made of a user defined data type with the help of a class. Thus, a class is a template for an object,
and an object is an instance of a class.
10. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
10
1.3 The General Form of a Class
The class contains data and the code that operates on that data. A class is declared by use of
the class keyword. The data, or variables, defined within a class are called instance variables. The
code is contained within methods. Collectively, the methods and variables defined within a class are
called members of the class. The general form of a class definition is shown here:
class classname
{
type instance-variable1;
type instance-variable2;
// ...
type instance-variableN;
type methodname1(parameter-list){ //
body of method
}
type methodname2(parameter-list) { //
body of method
}
// ...
type methodnameN(parameter-list) { //
body of method
}
}
Here is a class called Box that defines three instance variables: width, height, and depth.
Currently, Box does not contain any methods (but some will be added soon).
class Box
{
double width;
double height;
double depth;
}
Instantiating a class
Class declaration only creates a template; it does not create an actual object. To create a Box
object, you will use a statement like the following:
Box mybox = new Box(); // create a Box object called mybox
The new operator allocates space for the new object, calls a class constructor and returns a
reference to the object.
It should be noted that the class and its constructor have the same name.
After this statement executes, mybox will be an instance of Box. Each time you create an
instance of a class, you are creating an object that contains its own copy of each instance variable
defined by the class. Thus, every Box object will contain its own copies of the instance variables
width, height, and depth. To access these variables, you will use the dot (.) operator. The dot
operator links the name of the object with the name of an instance variable. For example, to assign
the width variable of mybox the value 100, you would use the following statement:
mybox.width = 100;
This statement tells the compiler to assign the copy of width that is contained within the
mybox object the value of 100.
1.4 Methods
A class with only data fields has no life. Objects created by such a class cannot respond to
any messages.
Methods are declared inside the body of the class but immediately after the declaration of
data fields.
11. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
11
The general form of a method declaration is:
modifier returnValueType methodName(list of parameters)
{
// Method body;
}
A method definition consists of a method header and a method body. Here are all the parts
of a method:
Modifiers: The modifier, which is optional, tells the compiler how to call the method. This
defines the access type of the method.
Return Type: A method may return a value. The returnValueType is the data type of the
value the method returns. Some methods perform the desired operations without returning a
value. In this case, the returnValueType is the keyword void.
Method Name: This is the actual name of the method. The method name and the parameter
list together constitute the method signature.
Parameters: A parameter is like a placeholder. When a method is invoked, you pass a value
to the parameter. This value is referred to as actual parameter or argument. The parameter
list refers to the type, order, and number of the parameters of a method. Parameters are
optional; that is, a method may contain no parameters.
Method Body: The method body contains a collection of statements that define what the
method does.
Creating a object:
Declare the Circle class, have created a new data type – Data Abstraction
Can define variables (objects) of that type:
Circle aCircle;
Circle bCircle;
Objects are created dynamically using the new keyword.
aCircle and bCircle refer to Circle objects
aCircle = new Circle();
bCircle = new Circle() ;
bCircle = aCircle;
Accessing Object/Circle Data
ObjectName.VariableName
ObjectName.MethodName(parameter-list)
12. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
12
Example
Circle aCircle = new Circle();
aCircle.x = 2.0 // initialize center and radius
aCircle.y = 2.0
aCircle.r = 1.0
program
// Circle.java: Contains both Circle class and its user class
//Add Circle class code here
class MyMain
{
public static void main(String args[])
{
Circle aCircle; // creating reference
aCircle = new Circle(); // creating object
aCircle.x = 10; // assigning value to data field
aCircle.y = 20;
aCircle.r = 5;
double area = aCircle.area(); // invoking method
double circumf = aCircle.circumference();
System.out.println("Radius="+aCircle.r+" Area="+area);
System.out.println("Radius="+aCircle.r+" Circumference ="+circumf);
}
}
1.5 Access Modifiers :
An access modifier is a Java keyword that indicates how a field or method can be
accessed. Variables and methods in Java have access restrictions, described by the following
access modifiers:
private:
• Used for most instance variables
• private variables and methods are accessible only to methods of the class in which they are
declared
• Declaring instance variables private is known as data hiding
• Example: private int x;
default (friend/ this means no modifier is used):
• Access is limited to the package in which the member is declared
• Example: int x;
protected:
• Access is limited to the package in which the member is declared, as well as all subclasses
of its class
• Example: protected void setName() { . . . }
public:
• The member is accessible to all classes in all packages.
• Declaring public methods is knows as defining the class‘ public interface.
• Example: public String getName() { . . . }
Java Access Specifiers :
13. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
13
• Access specifiers indicates which members of a class can be used by other classes
• We use of public, protected and private for access specifications
• Package access is used when there is no access specifier
• Package access means that all classes in the same package can access the member
• But for all other classes the member is private
1.6 Static
Variables-class variable(static),instance variable(class member variable) and local variable(
variable in method definition)
The static keyword can be used in 3 scenarios
static variables
static methods
static blocks of code.
static (Class) variable
It is a variable which belongs to the class and not to object(instance)
Static variables are initialized only once , at the start of the execution . These variables will
be initialized first, before the initialization of any instance variables
A single copy to be shared by all instances of the class
A static variable can be accessed directly by the class name and doesn‘t need any object
Syntax : <class-name>.<variable-name>
Syntax:
accessSpecifier static dataType variableName;
Example:
public static int countAutos = 0;
static method (Class Method)
It is a method which belongs to the class and not to the object(instance)
A static method can access only static data. It cannot access non-static data (instance
variables)
A static method can call only other static methods and can not call a non-static method
from it.
A static method can be accessed directly by the class name and doesn‘t need any object
Syntax : <class-name>.<method-name>
A static method cannot refer to ―this‖ or ―super‖ keywords in anyway
Example
class Student {
int a; //initialized to zero
static int b; //initialized to zero only when class is loaded not for each object created.
Student(){
//Constructor incrementing static variable b
b++;
14. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
14
}
public void showData(){
System.out.println("Value of a = "+a);
System.out.println("Value of b = "+b);
}
//public static void increment(){
//a++;
//}
}
class Demo{
public static void main(String args[]){
Student s1 = new Student();
s1.showData();
Student s2 = new Student();
s2.showData();
//Student.b++;
//s1.showData();
}
}
static block
The static block, is a block of statement inside a Java class that will be executed when a
class is first loaded in to the JVM
class Test{
static {
//Code goes here
}
}
A static block helps to initialize the static data members, just like constructors help to
initialize instance members
15. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
15
1.7 Constructor
A constructor is a special method that is used to initialize a newly created object and
is called just after the memory is allocated for the object .It can be used to initialize the
objects ,to required ,or default values at the time of object creation. It is not mandatory
for the coder to write a constructor for the class. If no user defined constructor is provided
for a class, compiler initializes member variables to its default values.
numeric data types are set to 0
char data types are set to null character(‗‘)
reference variables are set to null
The constructor is automatically called immediately after the object is created, before the
new operator completes.
Box mybox1 = new Box();
Features of constructor
A constructor has the same name as the class.
A class can have more than one constructor.
A constructor may take zero, one, or more parameters.
A constructor has no return value.
A constructor is always called with the new operator.
Types:
1. Default Constructor
2. Parameterized Constructor
3. Copy Constructor
Below is an example of a cube class containing 2 constructors. (one default and one
parameterized constructor).
public class Cube1 {
int length; int breadth; int height;
public int getVolume() {
return (length * breadth * height); }
Cube1()
{ length = 10; breadth = 10; height = 10; }
Cube1(int l, int b, int h)
{ length = l; breadth = b; height = h; }
public static void main(String[] args) {
Cube1 cubeObj1, cubeObj2;
cubeObj1 = new Cube1();
16. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
16
cubeObj2 = new Cube1(10, 20, 30); System.out.println("Volume of Cube1 is : " +
cubeObj1.getVolume());
System.out.println("Volume of Cube1 is : " + cubeObj2.getVolume()); } }
Copy Constructor in Java
Like C++, Java also supports copy constructor. But, unlike C++, Java doesn‘t create a
default copy constructor if you don‘t write your own.
// filename: Main.java
class Complex {
private double re, im;
// A normal parametrized constructor
public Complex(double re, double im) {
this.re = re;
this.im = im;
}
// copy constructor
Complex(Complex c) {
System.out.println("Copy constructor called");
re = c.re;
im = c.im;
}
// Overriding the toString of Object class
@Override
public String toString() {
return "(" + re + " + " + im + "i)";
}
}
public class Main {
public static void main(String[] args) {
Complex c1 = new Complex(10, 15);
// Following involves a copy constructor call
Complex c2 = new Complex(c1);
// Note that following doesn't involve a copy constructor call as
// non-primitive variables are just references.
Complex c3 = c2;
System.out.println(c2); // toString() of c2 is called here
}}
Output:
Copy constructor called
(10.0 + 15.0i)
17. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
17
a) “this” Keyword
this can be used inside any method to refer to the current object. this keyword has two
meanings:
to denote a reference to the implicit parameter
to call another constructor of the same class.
// A redundant use of this. Box(double w, double h, double d)
{
this.width = w;
this.height = h;
this.depth = d;
}
b) Garbage Collection
The purpose of garbage collection is to identify and discard objects that are no longer
needed by a program so that their resources can be reclaimed and reused.
A Java object is subject to garbage collection when it becomes unreachable to the program
in which it is used.
1.8 Finalize method
Finalizer methods are like the opposite of constructor methods; whereas a constructor
method is used to initialize an object, finalizer methods are called just before the object is
garbage collected and its memory reclaimed.
To create a finalizer method, include a method with the following signature in your class
definition:
void finalize()
{
...
}
Inside the body of that finalize() method, include any cleaning up you want to do for that
object.
protected void finalize() throws Throwable {
try{
System.out.println("Finalize of Sub Class");
//release resources, perform cleanup ;
}catch(Throwable t){
throw t;
}finally{
System.out.println("Calling finalize of Super Class");
super.finalize();
}
}
18. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
18
1.9 Arrays
Java provides a data structure, the array, which stores a fixed-size sequential collection of
elements of the same type. An array is used to store a collection of data, but it is often more
useful to think of an array as a collection of variables of the same type.
Declaring Array Variables:
dataType[] arrayRefVar; // preferred way.
Or
dataType arrayRefVar[]; // works but not preferred way.
Creating Arrays:
dataType[] arrayRefVar = new dataType[arraySize];
The above statement does two things:
1. It creates an array using new dataType[arraySize];
2. It assigns the reference of the newly created array to the variable arrayRefVar.
Alternatively you can create arrays as follows:
dataType[] arrayRefVar = {value0, value1, ..., valuek};
Multidimensional Arrays
In Java, multidimensional arrays are actually arrays of arrays. These, as you might expect,
look and act like regular multidimensional arrays.
int twoD[][] = new int[4][5];
The Arrays Class
The java.util.Arrays class contains various static methods for sorting and searching arrays,
comparing arrays, and filling array elements. These methods are overloaded for all primitive
types.
19. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
19
1.10 String objects
The Java String class (java.lang.String) is a class of object that represents a character array
of arbitrary length. While this external class can be used to handle string objects, Java integrates
internal, built-in strings into the language.
An important attribute of the String class is that once a string object is constructed, its value
cannot change (note that it is the value of an object that cannot change, not that of a string variable,
which is just a reference to a string object). All String data members are private, and no string
method modifies the string‘s value.
String Methods
Although a string represents an array, standard array syntax cannot be used to inquire into it.
These are detailed in the below Table.
20. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
20
String Comparison
String comparison methods listed in below Table.
String Searching
The String class also provides methods that search a string for the occurrence of a single
character or substring. These return the index of the matching substring or character if found, or - 1
if not found.
int indexOf (char ch)
int indexOf (char ch, int begin)
int lastIndexOf (char ch)
int lastIndexOf (char ch, int fromIndex)
int indexOf (String str)
int indexOf (String str, int begin)
int lastIndexOf (String str)
int lastIndexOf (String str, int fromIndex)
The following example shows the usage of these functions: if
(s1.indexOf (‘:‘) >= 0)
{
…
}
String suffix =
s1.substring (s1.lastIndexOf (‘.‘));
int spaceCount = 0;
int index = s1.indexOf (‘ ‘);
while (index >= 0)
{
++spaceCount;
index = s1.indexOf (‘ ‘, index + 1);
}
int index = s1.indexOf (―that‖);
21. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
21
String Concatenation
The String class provides a method for concatenating two strings:
String concat (String otherString)
The + and += String operators are more commonly used: The Java compiler recognizes the + and
+= operators as String operators. For each + expression, the compiler generates calls to methods
that carry out the concatentation. For each += expression, the compiler generates calls to methods
that carry out the concatenation and assignment.
Converting Objects To Strings
The String + operator accepts a non-string operand, provided the other operand is a string.
The action of the + operator on non-string operands is to convert the non-string to a string, then to
do the concatenation. Operands of native types are converted to string by formatting their values.
Operands of class types are converted to a string by the method toString() that is defined for all
classes. Any object or value can be converted to a string by explicitly using one of the static
valueOf() methods defined in class String:
String str = String.valueOf (obj);
If the argument to valueOf() is of class type, then valueOf() calls that object‘s toString() method.
Any class can define its own toString() method, or just rely on the default. The output produced by
toString() is suitable for debugging and diagnostics. It is not meant to be an elaborate text
representation of the object, nor is it meant to be parsed. These conversion rules also apply to the
right-hand side of the String += operator.
Converting Strings To Numbers
Methods from the various wrapper classes, such as Integer and Double, can be used to
convert numerical strings to numbers.
The wrapper classes contain static methods such as parseInt() which convert a string to its
own internal data type.
1.11 Packages
Provides a mechanism for grouping a variety of classes and / or interfaces together.
Grouping is based on functionality.
Benefits:
The classes contained in the packages of other programs can be reused.
In packages, classes can be unique compared with classes in other packages.
Packages provides a way to hide classes.
Two types of packages: 1. Java API packages 2. User defined packages
Java API Packages:
A large number of classes grouped into different packages based on functionality.
Examples:
Package Categories of Classes
java.lang Basic functionality common to many programs, such as the String
class and Math class
java.awt Graphics classes for drawing and using colors
javax.swing User-interface components
java.text Classes for formatting numeric output
java.util The Scanner class and other miscellaneous classes
22. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
22
Included in the Java SDK are more than 2,000 classes that can be used to add functionality to
our programs
APIs for Java classes are published on Sun Microsystems Web site:
www.java.sun.com
Accessing Classes in a Package
1. Fully Qualified class name:
Example:java.awt.Color
2. import packagename.classname;
Example: import java.awt.Color;
or
import packagename.*;
Example: import java.awt.*;
Import statement must appear at the top of the file, before any class declaration.
Creating Your Own Package
1. Declare the package at the beginning of a file using the form
package packagename;
2. Define the class that is to be put in the package and declare it public.
3. Create a subdirectory under the directory where the main source files are stored.
4. Store the listing as classname.java in the subdirectory created.
5. Compile the file. This creates .class file in the subdirectory.
Example:
package firstPackage;
Public class FirstClass
{
//Body of the class
}
Example1-Package
package p1;
public class ClassA
{
public void displayA( )
{
System.out.println(―Class A‖);
}}
23. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
23
Source file – ClassA.java
Subdirectory-p1
ClassA.Java and ClassA.class->p1
import p1.*;
Class testclass
{
public static void main(String str[])
{
ClassA obA=new ClassA();
obA.displayA();
}
}
Source file-testclass.java
testclass.java and testclass.class->in a directory of which p1 is subdirectory.
Creating Packages
Consider the following declaration:
package firstPackage.secondPackage;
This package is stored in subdirectory named firstPackage.secondPackage.
A java package can contain more than one class definitions that can be declared as public.
Only one of the classes may be declared public and that class name with .java extension is
the source file name.
Example2-Package
package p2;
public class ClassB
{
protected int m =10;
public void displayB()
{
System.out.println(―Class B‖);
System.out.println(―m= ―+m);
}
}
import p1.*;
import p2.*;
class PackageTest2
{
public static void main(String str[])
{
ClassA obA=new ClassA();
Classb obB=new ClassB();
obA.displayA();
obB.displayB();
}
}
24. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
24
Example 3- Package
import p2.ClassB;
class ClassC extends ClassB
{
int n=20;
void displayC()
{
System.out.println(―Class C‖);
System.out.println(―m= ―+m);
System.out.println(―n= ―+n);
}
}
class PackageTest3
{
public static void main(String args[])
{
ClassC obC = new ClassC();
obC.displayB();
obC.displayC();
}
}
Default Package
If a source file does not begin with the package statement, the classes contained in the
source file reside in the default package
The java compiler automatically looks in the default package to find classes.
Finding Packages
Two ways:
1.By default, java runtime system uses current directory as starting point and search all the
subdirectories for the package.
2.Specify a directory path using CLASSPATH environmental variable.
CLASSPATH Environment Variable
The compiler and runtime interpreter know how to find standard packages such as java.lang
and java.util
The CLASSPATH environment variable is used to direct the compiler and interpreter to
where programmer defined imported packages can be found
The CLASSPATH environment variable is an ordered list of directories and files
1.12 Documentation Comments
The Java SDK contains a very useful tool, called javadoc, that generates HTML
documentation from your source files. If you add comments that start with the special delimiter /**
to your source code, you too can produce professional-looking documentation easily. This is a very
nice scheme because it lets you keep your code and documentation in one place. If you put your
25. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
25
documentation into a separate file, then you probably know that the code and comments tend to
diverge over time. But since the documentation comments are in the same file as the source code, it
is an easy matter to update both and run javadoc again.
How to Insert Comments
The javadoc utility extracts information for the following items:
• Packages
• Public classes and interfaces
• Public and protected methods
• Public and protected fields
You can (and should) supply a comment for each of these features. Each comment is placed
immediately above the feature it describes. A comment starts with a /** and ends with a */. Each
/** . . . */ documentation comment contains free-form text followed by tags. A tag starts with an @,
such as @author or @param. The first sentence of the free-form text should be a summary
statement. The javadoc utility automatically generates summary pages that extract these sentences.
In the free-form text, you can use HTML modifiers such as <em>...</em> for emphasis,
<code>...</code> for a monospaced ―typewriter‖ font, <strong>...</strong> for strong emphasis,
and even <img ...> to include an image. You should, however, stay away from heading <h1> or
rules <hr> since they can interfere with the formatting of the document.
Class Comments
The class comment must be placed after any import statements, directly before the class
definition. Here is an example of a class comment:
/**
A <code>Card</code> object represents a playing card, such as "Queen of Hearts". A
card has a suit (Diamond, Heart, Spade or Club) and a value (1 = Ace, 2 . . . 10, 11 =
Jack, 12 = Queen, 13 = King).
*/
public class Card
{
. . .
}
Method Comments
Each method comment must immediately precede the method that it describes. In addition
to the general-purpose tags, you can use the following tags:
@param variable description
This tag adds an entry to the ―parameters‖ section of the current method. The description can span
multiple lines and can use HTML tags. All @param tags for one method must be kept together.
@return description
This tag adds a ―returns‖ section to the current method. The description can span multiple lines and
can use HTML tags.
@throws class description
Field Comments
You only need to document public fields—generally that means static constants. For
example,
/**
The "Hearts" card suit */
public static final int HEARTS = 1;
General Comments
The following tags can be used in class documentation comments.
@author name
This tag makes an ―author‖ entry. You can have multiple @author tags, one for each author.
@version text
26. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
26
How to Extract Comments
Here, docDirectory is the name of the directory where you want the HTML files to go. Follow these
steps:
1. Change to the directory that contains the source files you want to document. If you have
nested packages to document, such as com.horstmann.corejava, you must be in the directory
that contains the subdirectory com. (This is the directory that contains the overview.html
file, if you supplied one.)
2. Run the command javadoc -d docDirectory nameOfPackage for a single package. Or run
javadoc -d docDirectory nameOfPackage1 nameOfPackage2... to document multiple
packages. If your files are in the default package, then run javadoc -d docDirectory *.java
instead. If you omit the -d docDirectory option, then the HTML files are extracted to the
current directory. That can get messy, and we don't recommend it. The javadoc program can
be fine-tuned by numerous command-line options. For example, you can use the - author
and -version options to include the @author and @version tags in the documentation. (By
default, they are omitted.)
27. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
1
Unit II – Object Oriented Programming – Inheritance
2.1 Inheritance
2.2 class hierarchy
2.3 polymorphism
2.4 dynamic binding
2.5 final keyword
2.6 abstract classes
2.7 interfaces
2.8 inner classes
2.9 the Object class
2.10 object cloning
2.11 proxies
2.12 Reflection
2.1Inheritance
Inheritance is a process of making a new class that derives from an existing class. The existing class
is called the superclass, base class, or parent class. The new class is called the subclass, derived
class, or child class.
Therefore, a subclass is a specialized version of a superclass. It inherits all of the instance variables
and methods defined by the superclass and add its own, unique elements.
Subclasses of a class can define their own unique behaviors and yet share some of the same
functionality of the parent class.
The following kinds of inheritance are there in java.
Simple Inheritance
Multilevel Inheritance
Simple Inheritance
When a subclass is derived simply from it's parent class then this mechanism is known as simple
inheritance. In case of simple inheritance there is only a sub class and it's parent class. It is also called single
inheritance or one level inheritance.
class A
{
int x;
int y;
int get(int p, int q)
{
x=p; y=q; return(0);
}
void Show()
{
System.out.println(x);
}
}
class B extends A
{
public static void main(String args[]){
28. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
2
A a = new A();
a.get(5,6);
a.Show();
}
void display(){
System.out.println("B");
}
}
Multilevel Inheritance
It is the enhancement of the concept of inheritance. When a subclass is derived from a derived class
then this mechanism is known as the multilevel inheritance. The derived class is called the subclass or child
class for it's parent class and this parent class works as the child class for it's just above ( parent )
class. Multilevel inheritance can go up to any number of level.
class A {
int x;
int y;
int get(int p, int q){
x=p; y=q; return(0);
}
void Show(){
System.out.println(x);
}
}
class B extends A{
void Showb(){
System.out.println("B");
}}
class C extends B{
void display(){
System.out.println("C");
}
public static void main(String args[]){
A a = new A();
a.get(5,6);
a.Show();
}}
Multiple Inheritance
The mechanism of inheriting the features of more than one base class into a single class is known as
multiple inheritance.
Java does not support multiple inheritance but the multiple inheritance can be achieved by using the
interface.
In Java Multiple Inheritance can be achieved through use of Interfaces by implementing more than
one interfaces in a class.
Member Access and Inheritance
A class member that has been declared as private will remain private to its class. It is not accessible by any
code outside its class, including subclasses.
Super keyword
Super is a special keyword that directs the compiler to invoke the super class method. super has two general
forms.
to invoke a superclass constructor.
to invoke a superclass members(variables &methods).
29. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
3
Invoke superclass constructor:
A subclass can call a constructor method defined by its superclass by use of the following form of super:
super(parameter-list);
Here, parameter-list specifies any parameters needed by the constructor in the superclass.
super( ) must always be the first statement executed inside a subclass constructor.
The compiler implicitly calls the base class’s no-parameter constructor or default constructor.
If the superclass has parameterized constructor and the subclass constructor does not call superclass
constructor explicitly, then the Java compiler reports an error.
Invoke superclass members:
Super always refers to the superclass of the subclass in which it is used. This usage has the following
general form:
super.member;
Here, member can be either a method or an instance variable. This second form of super is most
applicable to situations in which member names of a subclass hide members by the same name in the
superclass.
If a parent class contains a finalize() method, it must be called explicitly by the derived class’s
finalize() method.
super.finalize();
When Constructors are Called
Constructors are called in order of derivation, from superclass to subclass. Because a superclass has no
knowledge of any subclass, any initialization it needs to perform is separate from and possibly prerequisite to
any initialization performed by the subclass. Therefore, it must be executed first.
Advantages
Reusability -- facility to use public methods of base class without rewriting the same
Extensibility -- extending the base class logic as per business logic of the derived class
Data hiding -- base class can decide to keep some data private so that it cannot be altered by the
derived class
Overriding--With inheritance, we will be able to override the methods of the base class so that
meaningful implementation of the base class method can be designed in the derived class.
Disadvantages:-
Both classes (super and subclasses) are tightly-coupled.
As they are tightly coupled (binded each other strongly with extends keyword), they cannot work
independently of each other.
Changing the code in super class method also affects the subclass functionality.
If super class method is deleted, the code may not work as subclass may call the super class method
with super keyword. Now subclass method behaves independently.
2.2 Class Hierarchy
The collection of all classes extending from a common superclass is called an inheritance hierarchy;
the path from a particular class to its ancestors in the inheritance hierarchy is its inheritance chain.
Simple class hierarchies consist of only a superclass and a subclass. But you can build hierarchies
that contain as many layers of inheritance as you like.
For example, create three classes called A, B, and C, C can be a subclass of B, which is a subclass
of A. When this type of situation occurs, each subclass inherits all of the traits found in all of its
superclasses. In this case, C inherits all aspects of B and A.
30. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
4
2.3 Polymorphism
Polymorphism means the ability of methods to behave differently based on the kinds of input.
Types of polymorphism
Method Overloading
Method overriding
Overloaded methods
Overloaded methods are methods with the same name but different method signature (either a
different number of parameters or different types in the parameter list).
class A{
void display(){ System.out.println("Hai");
}
}
class B extends A{
void display(String s){
System.out.println(s);
}
}
public class Test{
public static void main(String arg[]){
A a=new A();
a.display();
B b=new B();
b.display("Hello");
}}
Output
Hai
Hello
Method Overriding
The process of a subclass redefining a method contained in the superclass (with the same parameter
types) is called overriding the method.
Overridden methods allow Java to support run time polymorphism. Whenever a method is called for
a subclass object, the compiler calls the overriding version instead of the superclass version. The
version of the method defined by the superclass will be hidden.
Call to an overridden method is resolved at run time, rather than compile time.
Rules:
1. Method have same name as in a parent class
2. Method have same parameter as in a parent class
//Example of method overriding
class Vehicle{
void run()
{
System.out.println("Vehicle is running");}
}
class Bike extends Vehicle{
void run()
{System.out.println("Bike is running safely");}
public static void main(String args[]){
Bike obj = new Bike();
obj.run();
}}
Output:Bike is running safely
31. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
5
2.4 Dynamic Binding
Binding - Connecting a method call to a method body
1. Static binding (Early binding)
2. Dynamic binding (Late binding)
STATIC BINDING OR EARLY BINDING
If the compiler can resolve the binding at the compile time only then such a binding is called Static
Binding or Early Binding. Resolve the call and binding at compile time.
If the method is private, static, final, or a constructor, then the compiler knows exactly which
method to call. This is called static binding.
All the member variables in Java follow static binding.
All the static method calls are resolved at compile time itself.
All private methods are resolved at compile time itself.
class Dog{
private void eat()
{
System.out.println("dog is eating...");
}
public static void main(String args[])
{
Dog d1=new Dog();
d1.eat();
}}
In this example, during compilation, the compiler knows eat() method to be invoked from the class Dog.
Dynamic Binding or Late Binding
Selecting the appropriate method at runtime is called dynamic binding. Dynamic Binding refers to
the case where compiler is not able to resolve the call and the binding is done at runtime only.
All the instance methods in Java follow dynamic binding.
It is important to understand what happens when a method call is applied to an object. Here are the
details:
The compiler looks at the declared type of the object and the method name. The compiler
knows all possible candidates for the method to be called.
Next, the compiler determines the types of the parameters that are supplied in the method
call. If among all the methods called fun there is a unique method whose parameter types are
a best match for the supplied parameters, then that method is chosen to be called. This
process is called overloading resolution.
32. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
6
If the method is private, static, final, or a constructor, then the compiler knows exactly
which method to call.
When the program runs and uses dynamic binding to call a method, then the virtual machine
must call the version of the method that is appropriate for the actual type of the object. The
virtual machine precomputes a method table for each class that lists all method signatures
and the actual methods to be called. When a method is actually called, the virtual machine
simply makes a table lookup. This is used to reduce the time consumed by searching
process.
class Animal{
void eat(){
System.out.println("animal is eating...");
}}
class Dog extends Animal{
void eat(){
System.out.println("dog is eating...");
}
public static void main(String args[]){
Animal a=new Dog();
a.eat();
}}
Output:
Dog is eating…
2.5 FINAL KEYWORD
The final keyword in java used to restrict the user.
The keyword final has three uses.
1. Final Variables - Used to create the equivalent of a named constant.
2. Final Methods - Used to Prevent Overriding
3. Final Class -
Used to Prevent Inheritance
Final variables
A variable can be declared as final.
If you make any variable as final, you cannot change the value of variable at runtime. (It is similar to
constant)
final int a = 1;
Variables declared as final do not occupy memory on a per-instance basis.
Attempts to change it will generate either a compile-time error or an exception.
class Bike{
final int speedlimit=90;//final variable
void run(){
speedlimit=400;
}
public static void main(String args[]){
Bike obj=new Bike();
obj.run();
}}
Output:
Compile – time error occurs.
Since the variables speedlimit is restricted by the user, so it cannot be reinitialized in run() method.
33. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
7
Final Method
Methods declared as final cannot be overridden
since final methods cannot be overridden, a call to one can be resolved at compile time. This is
called early binding.
class Bike{
final void run(){
System.out.println("running");}}
class Honda extends Bike{
void run(){
System.out.println("running safely with 100kmph");}
public static void main(String args[]){
Honda honda= new Honda();
honda.run(); }}
Output:
Compile – time error occurs.
Final class
Declaring a class as final implicitly declares all of its methods as final.
So it prevents a class from being inherited.
final class Bike{}
class Honda extends Bike{
void run(){
System.out.println("running safely with 100kmph");
}
public static void main(String args[]){
Honda honda= new Honda();
honda.run();
}}
Output:
Compile – time error occurs.
2.6 Abstract Classes
When we define a class to be “final”, it cannot be extended. In certain situation, we want to
properties of classes to be always extended and used. Such classes are called Abstract Classes.
Abstraction can achieved by
1. Abstract class (0-100%)
2. Interface (100%)
An Abstract class is a conceptual class.
An Abstract class cannot be instantiated – objects cannot be created.
Abstract Class Syntax
abstract class ClassName
{
...
…
abstract Type MethodName1();
…
…
Type Method2()
{
// method body
}}
When a class contains one or more abstract methods, it should be declared as abstract class.
The abstract methods of an abstract class must be defined in its subclass.
We cannot declare abstract constructors or abstract static methods.
34. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
8
Abstract Class –Example
Shape is a abstract class.
The Shape Abstract Class
public abstract class Shape {
public abstract double area();
public void move() { // non-abstract method
// implementation
}
}
Is the following statement valid?
Shape s = new Shape();
No. It is illegal because the Shape class is an abstract class, which cannot be instantiated to create its
objects.
abstract class Shape{
abstract void draw();
}
class Rectangle extends Shape{
void draw(){
System.out.println("drawing rectangle");
}}
class Circle extends Shape{
void draw(){
System.out.println("drawing circle");
}}
class Test{
public static void main(String args[]){
Shape s=new Circle();//In real scenario, Object is provided through factory method
s.draw();}}
Output:
drawing circle
In the above example, Shape is an abstract class, its implementation is provided by Rectangle and Circle
classes. Mostly, we don’t know about the implementation class (ie hidden to the user) and object
implementation class is provided by Factory method.
A Factory method is the method returns the instance of the class.
Abstract Classes Properties
A class with one or more abstract methods is automatically abstract and it cannot be instantiated.
A class declared abstract, even with no abstract methods cannot be instantiated.
A subclass of an abstract class can be instantiated if it overrides all abstract methods by
implementation them.
A subclass that does not implement all of the superclass abstract methods is itself abstract; and it
cannot be instantiated.
A private method can’t be abstract. All abstract methods must be public.
A class can’t be both abstract and final.
35. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
9
2.7 Interface
In Java, only single inheritance is permitted. However, Java provides a construct called an interface
which can be implemented by a class.
Interfaces are similar to abstract classes.
A class can implement any number of interfaces. In effect using interfaces gives us the benefit of
multiple inheritances without many of its problems.
Interfaces are compiled into bytecode just like classes.
Interfaces cannot be instantiated.
Can use interface as a data type for variables.
Can also use an interface as the result of a cast operation.
Interfaces can contain only abstract methods and constants.
Defining an Interface
An interface must be declared with the keyword interface.
access interface interface-name {
return-type method-name(parameter-list);
type final-varname = value;
}
It is also possible to declare that an interface is protected so that it can only be implemented by
classes in a particular package. However this is very unusual.
Rules for interface constants. They must always be
public
static
final
Once the value has been assigned, the value can never be modified. The assignment happens in the
interface itself (where the constant is declared), so the implementing class can access it and use it,
but as a read-only value.
To make a class implement an interface, have to carry out two steps:
1. Declare that your class intends to implement the given interface.
2. Supply definitions for all methods in the interface.
To declare that a class implements an interface, use the implements keyword:
access class classname implements interfacename
{
//definitions for all methods in the interface
}
interface printable
{
void print();
}
class A implements printable
{
public void print(){
System.out.println("Hello");
}
public static void main(String args[]){
A obj = new A();
obj.print();
}}
Multiple inheritance by interface
A class cannot extend two classes but it can implement two interfaces.
interface printable{
void print();}
interface Showable{
void show();}
36. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
10
class A implements printable,Showable
{
public void print(){
System.out.println("Hello");
}
public void show()
{
System.out.println("Welcome");
}
public static void main(String args[]){
A obj = new A();
obj.print();
obj.show();
}}
Output:
Hello
Welcome
Interface vs. abstract class
2.8 Inner Classes
Inner classes are classes defined within other classes
The class that includes the inner class is called the outer(NESTED) class
There is no particular location where the definition of the inner class (or classes) must be
place within the outer class
Placing it first or last, however, will guarantee that it is easy to find
An inner class definition is a member of the outer class in the same way that the instance variables
and methods of the outer class are members
An inner class is local to the outer class definition
The name of an inner class may be reused for something else outside the outer class
definition
If the inner class is private, then the inner class cannot be accessed by name outside the
definition of the outer class
public class Outer
{
private class Inner
{
// inner class instance variables
// inner class methods
} // end of inner class definition
// outer class instance variables
// outer class methods
}
37. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
11
There are two main advantages to inner classes
They can make the outer class more self-contained since they are defined inside a class
Both of their methods have access to each other's private methods and instance variables
Using an inner class as a helping class is one of the most useful applications of inner classes
If used as a helping class, an inner class should be marked private
Types of nested (outer) classes
Regular Inner Class
You define an inner class within the curly braces of the outer class, as follows:
class MyOuter
{
class MyInner { }
}
And if you compile it, %javac MyOuter.java , you’ll end up with two class files:
MyOuter.class
MyOuter$MyInner.class
The inner class is still, in the end, a separate class, so a class file is generated. But the inner class file
isn’t accessible to you in the usual way. The only way you can access the inner class is through a live
instance of the outer class.
Instantiating an Inner Class
To instantiate an instance of an inner class, you must have an instance of the outer class. An inner class
instance can never stand alone without a direct relationship with a specific instance of the outer class.
Instantiating an Inner Class from Within Code in the Outer Class
From inside the outer class instance code, use the inner class name in the normal way:
class MyOuter {
private int x = 7;
MyInner mi = new MyInner();
class MyInner {
public void seeOuter() {
System.out.println("Outer x is " + x);
} }
public static void main(String arg[]){
MyOuter mo=new MyOuter();
mo.mi.seeOuter();
} }
Output:
Outer x is 7
38. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
12
Method-Local Inner Classes
A method-local inner class is defined within a method of the enclosing class.
class MyOuter {
void inner()
{
final int c=9;
class MyInner {
int x=5;
public void display() {
System.out.println("Inner x is " + x);
System.out.println("Inner c is " + c);
}
}
MyInner mi = new MyInner();
mi.display();
}
public static void main(String arg[]){
MyOuter mo = new MyOuter();
mo.inner();
}}
Anonymous Inner Classes
Anonymous inner classes have no name, and their type must be either a subclass of the named type
or an implementer of the named interface.
An anonymous inner class is always created as part of a statement, so the syntax will end the class
definition with a curly brace, followed by a closing parenthesis to end the method call, followed by a
semicolon to end the statement: });
An anonymous inner class can extend one subclass, or implement one interface. It cannot both
extend a class and implement an interface, nor can it implement more than one interface.
class A{
void display(){
System.out.println("Hai");
}}
class B {
A ob=new A(){
void display(){
System.out.println("Hello");
} }}
public class Test{
public static void main(String arg[]){
B b=new B();
b.ob.display();
} }
Output: Hello
And if you compile it, %javac Test.java , you’ll end up with two class files: A.class
B.class
B$1.class
Test.class
Static Nested Classes
Static nested classes are inner classes marked with the static modifier.
Technically, a static nested class is not an inner class, but instead is considered a top-level nested
class
Because the nested class is static, it does not share any special relationship with an instance of the
outer class. In fact, you don’t need an instance of the outer class to instantiate a static nested class.
39. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
13
Instantiating a static nested class requires using both the outer and nested class names as follows:
A.B b=new A.B();
A static nested class cannot access nonstatic members of the outer class, since it does not have an
implicit reference to any outer instance (in other words, the nested class instance does not get an
outer this reference).
class A {
static class B {
int m=5;
void display(){
System.out.println("m="+m);
} }
}
public class Test{
public static void main(String arg[]){
A.B b=new A.B();
b.display();
}}
Output: m=5
2.9 Object class
In Java, every class is a descendent of the class Object
Every class has Object as its ancestor
Every object of every class is of type Object, as well as being of the type of its own class
If a class is defined that is not explicitly a derived class of another class, it is still automatically a
derived class of the class Object
The class Object is in the package java.lang which is always imported automatically
Having an Object class enables methods to be written with a parameter of type Object
A parameter of type Object can be replaced by an object of any class whatsoever
For example, some library methods accept an argument of type Object so they can be used
with an argument that is an object of any class
The class Object has some methods that every Java class inherits
For example, the equals and toString methods
Every object inherits these methods from some ancestor class
Either the class Object itself, or a class that itself inherited these methods (ultimately) from
the class Object
40. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
14
2.9 Object Cloning
Object cloning is a way to create exact copy of an object.
For this purpose, clone() method of Object class is used to clone an object.
The method Object.clone() does a bit-by-bit copy of the object's data in storage
The Cloneable interface is another unusual example of a Java interface
It does not contain method headings or defined constants
It is used to indicate how the method clone (inherited from the Object class) should be used
and redefined
Syntax:
protected Object clone() throws CloneNotSupportedException
class Student implements Cloneable{
int rollno;
String name;
Student(int rollno,String name){
this.rollno=rollno;
this.name=name;
}
public Object clone()throws CloneNotSupportedException
{
return super.clone();
}
public static void main(String args[]){
try{
Student s1=new Student(101,"amit");
Student s2=(Student)s1.clone();
System.out.println(s1.rollno+" "+s1.name);
System.out.println(s2.rollno+" "+s2.name);
}
catch(CloneNotSupportedException c)
{}
}}
41. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
15
2.11Proxy
Proxy used to create new classes at runtime that implement a given set of interfaces. The proxy class
can create brand-new classes at runtime.
The proxy class can create brand-new classes at runtime. Such a proxy class implements the
interfaces that you specify. In particular, the proxy class has the following methods:
All methods required by the specified interfaces;
All methods defined in the Object class (toString, equals, and so on).
To create a proxy object, you use the newProxyInstance method of the Proxy class. The method has
three parameters:
A class loader. As part of the Java security model, it is possible to use different class loaders
for system classes, classes that are downloaded from the Internet, and so on.
An array of Class objects, one for each interface to be implemented.
An invocation handler.
Proxies can be used for many purposes, such as:
Routing method calls to remote servers;
Associating user interface events with actions in a running program;
Tracing method calls for debugging purposes
2.12 Reflection
Reflection is the ability of the software to analyze itself at runtime.
Reflection is provided by the java.lang.reflect package and elements in class.
The Reflection API is mainly used in:
IDE (Integrated Development Environment) eg. Eclipse, NetBeans
Debugger
Test Tools
This mechanism is helpful to tool builders, not application programmers. The reflection mechanism
is extremely used to
a. Analyze the capabilities of classes at run time
b. Inspect objects at run time
c. Implement generic array manipulation code
Analyze the capabilities of classes at run time - Examine the structure of class.
The java.lang.Class class performs mainly two tasks:
1. Provides methods to get the metadata of a class at runtime.
2. Provides methods to examine and change the runtime behavior of a class.
42. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
16
Field
Provide information about fields.
The getFields() method returns an array containing Field objects for the public fields.
The getDeclaredField() method returns an array of Field objects for all fields. The methods return
an array of length 0 if there are no such fields.
import java.lang.reflect.*;
class Test{
public int var1;
private int var2;
protected int var3;
int var4;}
public class FieldDemo{
public static void main(String args[])throws Exception{
Class c=Class.forName("Test");
Field f[]=c.getFields();
Field fdec[]=c.getDeclaredFields();
System.out.println("public Fields:");
for(int i=0;i<f.length;i++)
System.out.println(f[i]);
System.out.println("All Fields:");
for(int i=0;i<fdec.length;i++)
System.out.println(fdec[i]);
}}
Output:
public Fields:
public int Test.var1
All Fields:
public int Test.var1
private int Test.var2
protected int Test.var3
int Test.var4
Method
Provides information about method
The getMethods() method return an array containing Method objects that give you all the
public methods.
The getDeclaredMethods () return all methods of the class or interface. This includes those
inherited from classes or interfaces above it in the inheritance chain.
import java.lang.reflect.*;
class Test{
public void method1() {}
protected void method2() {}
private void method3() {}
void method4() {}
}
public class MethodDemo{
public static void main(String args[])throws Exception{
Class c=Class.forName("Test");
Method m[]=c.getMethods();
Method mdec[]=c.getDeclaredMethods();
System.out.println("public Methods of class Test & its Super class:");
for(int i=0;i<m.length;i++)
System.out.println(m[i].getName());
System.out.println("All Methods:");
for(int i=0;i<mdec.length;i++) System.out.println(mdec[i].getName());
}
}
43. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
17
Output:
public Methods of class Test & its Super class:
method1 All Methods:
hashCode method1
getClass method2
wait method3
equals method4
notify
notifyAll
toString
Constructor
Provide information about constructors
getConstructors () method return an array containing Constructor objects that give you all
the public constructors
getDeclaredConstructors () method return all constructors of the class represented by the
Class object.
Using Reflection to Analyze Objects at Run Time
Look at the contents of the data fields. It is easy to look at the contents of a specific field of an
object whose name and type are known when you write a program. But reflection lets you look at
fields of objects that were not known at compile time.
f.set(obj, value) sets the field represented by f of the object obj to the new value.
f.get(obj) returns an object whose value is the current value of the field of obj.
import java.lang.reflect.*;
class A{
public int var1,var2; A(int i, int j){
var1=i;
var2=j;
} }
public class ConstructorDemo {
public static void main(String args[]) throws Exception{
A obj=new A(10,20);
System.out.println("Before n var1= "+obj.var1);
Field f1 = obj.getClass().getField("var1");
int v1 = f1.getInt(obj) + 1;
f1.setInt(obj, v1);
System.out.println("After n var1= "+v1);
System.out.println("Before n var2= "+obj.var2);
Field f2 = obj.getClass().getField("var2");
f2.set(obj,21);
System.out.println("After n var2= "+f2.get(obj));
} }
Output:
Before var1= 10
After var1= 11
Before var2= 20
After var2= 21
44. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
18
Using Reflection to implement generic array manipulation code
The Array class in the java.lang.reflect package allows you to create arrays dynamically. First the
given array can be converted to an Object[] array. newInstance() method of Array class, constructs a
new array.
Object newarray= Array.newInstance(ComponentType, newlength)
newInstance() method needs two parameters
Component Type of new array
To get component type
Get the class object using getClass() method.
Confirm that it is really an array using isArray().
Use getComponentType method of class Class, to find the right type for the array.
Length of new array
Length is obtained by getLength() method. It returns the length of any array(method is
static method, Array.getLengh(array name)).
import java.lang.reflect.*;
public class TestArrayRef {
static Object arrayGrow(Object a){
Class cl = a.getClass();
if (!cl.isArray()) return null;
Class componentType = cl.getComponentType();
int length = Array.getLength(a);
int newLength = length + 10;
Object newArray = Array.newInstance(componentType,newLength);
System.arraycopy(a, 0, newArray, 0, length);
return newArray;
}
public static void main(String args[]) throws Exception{
int arr[]=new int[10];
System.out.println(arr.length);
arr = (int[])arrayGrow(arr);
System.out.println(arr.length);
} }
Output:
10
20
45. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
1
Unit III – Event Driven Programming
3.1 Graphics programming
3.2 Frame
3.3 Components
3.4 working with 2D shapes
3.5 Using color, fonts, and images
3.6 Basics of event handling
3.7 event handlers
3.8 adapter classes
3.9 actions
3.10 mouse events
3.11 AWT event hierarchy
3.12 introduction to Swing
3.13 Model-View-Controller design pattern
3.14 buttons
3.15 layout management
3.16 Swing Components
3.1 Graphics Programming
Java contains support for graphics that enable programmers to visually enhance applications
JFC
JFC is a collection of APIs for developing graphical components in Java. It includes the following:
1. AWT (version 1.1 and beyond)
2. 2D API
3. Swing Components
4. Accessibility API
AWT
AWT was original toolkit for developing graphical components. The JFC is based on the AWT
components.
The Abstract Window Toolkit was a part of Java from the beginning
import java.awt.*;
All AWT components must be mapped to platform specific components using peers
The look and feel of these components is tied to the native components of the window
manager
AWT components are considered to be very error prone and should not be used in modern Java
applications
Swing
With the introduction to Swing, lightweight version of many of the AWT components (heavyweight)
are created with the prefix J. For example, JFrame for Frame, JButton for Button, etc.
Since Swing was an extension to AWT, all Swing components are organized in javax.swing package
compared to java.awt for all AWT components.
Swing also provides many components that AWT lacked.
Some of the original method names have been changed to allow uniform naming for all components.
When a method name will no longer be supported in future newer versions, it is said to be
deprecated.
47. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
3
AWT vs Swing
Java 1.0 was introduced with a class library called Abstract Window Toolkit (AWT)
used for basic user interface
delegated creation and behavior of interface elements to the native GUI tookit on the target
platform
Windows vs. Solaris vs. Macintosh, etc
Downside to AWT:
Worked well for simple applications but difficult to write high-quality portable
graphics
Limited graphics programming to the lowest common denominator.
Different platforms had different bugs
In 1996 Sun worked with Netscape to create Swing
In Swing user interface elements are painted onto blank windows
Swing is not a complete replacement of AWT. Instead it works with AWT.
Swing simply gives you more capable user interface components.
However, even though AWT components are still available, you will rarely use them.
Reasons to choose Swing:
much richer and more convenient set of user interface elements
depends far less on the underlying platform so it is less vulnerable to platform-specific bugs
gives a consistent user experience across platforms
fullfill’s Java’s promise of ―Write Once, Run Anywhere‖
Easier to use than AWT
How to Create Graphics in Java
Here are the basic steps you need to take to include graphics in your program:
Create a frame
Create a panel
Override the paintComponent() method in your panel
3.2 Frame
Frame is a top-level window that has a title bar, menu bar, borders, and resizing corners. By default, a
frame has a size of 0 × 0 pixels and it is not visible.
Frames are examples of containers. It can contain other user interface components such as buttons and
text fields.
Class hierarchy for Frame
48. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
4
Component & Window class Methods
java.awt.Component
void setVisible(boolean b) - shows or hides the component depending on whether b is true
or false.
void setSize(int width, int height) - resizes the component to the specified width and height.
void setBounds(int x, int y, int width, int height) - moves and resizes this component. The
location of the top-left corner is given by x and y, and the new size is given by the width and
height parameters.
void setBackground(java.awt.Color) – set Background color to the window.
void setForeground(java.awt.Color)- set Foreground color to the window.
void repaint() - causes a repaint of the component ―as soon as possible
void setTitle(String s) - sets the text in the title bar for the frame to the string s.
Frame class constructors
Frame() - Creates a new instance of Frame that is initially invisible.
Frame(String title) - Creates a new instance of Frame that is initially invisible with the
specified title.
Frame class methods
void setResizable(boolean resizable) - Sets whether or not a frame is resizable
void setTitle(String title) - Sets the title of a frame
void setVisible(boolean visible) - Sets whether or not a frame is visible
void setSize(int width, int height) - Sets the width & height of a frame
String getTitle() - Returns the title of a frame
There are two ways to create a frame
1.Create a frame by extending the Frame class
2.Create a frame by creating an instance of the Frame class
Create a frame by extending the Frame class
import java.awt.*;
class AFrame extends Frame{
public static void main(String[] args){
AFrame frame = new AFrame();
frame.setSize(200, 200);
frame.setVisible(true);
} }
Create a frame by creating an instance of the Frame class
import java.awt.*;
class AFrame{
public static void main(String[] args){
Frame aFrame = new Frame();
aFrame.setSize(200, 200);
aFrame.setVisible(true);
} }
Frame Positioning
Most methods for working the size and position of a frame come from the various superclasses of
JFrame. Some important methods include:
the dispose() method: closes the window and reclaims system resources.
the setIconImage() method: takes an Image object to use as the icon when the window is
minimized
49. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
5
the setTitle() method: changes the text in the title bar.
the setResizable() method: takes a boolean to determine if a frame will be resizeable by the
user.
the setLocation() method: repositions a frame
the setBounds() method: both repositions and resizes a frame.
the setExtendedState(Frame.MAXIMIZED_BOTH): maximizes the size of a frame
Note: If you don’t explicitly size the frame, it will default to being 0 by 0 pixels, which is invisible.
In a professional application, you should check the resolution of the user’s screen to
determine the appropriate frame size.
Java screen coordinate system
Upper-left corner of a GUI component has the coordinates (0, 0)
Contains x-coordinate (horizontal coordinate) - horizontal distance moving right from the
left of the screen
Contains y-coordinate (vertical coordinate) - vertical distance moving down from the top of
the screen
Coordinate units are measured in pixels. A pixel is a display monitor’s smallest unit of resolution.
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Image;
import java.awt.Toolkit;
import javax.swing.JFrame;
public class SizedFrameTest {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
SizedFrame frame = new SizedFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
}
}
class SizedFrame extends JFrame {
public SizedFrame() {
// get screen dimensions
Toolkit kit = Toolkit.getDefaultToolkit();
Dimension screenSize = kit.getScreenSize();
int screenHeight = screenSize.height;
int screenWidth = screenSize.width;
// set frame width, height and let platform pick screen location
setSize(screenWidth / 2, screenHeight / 2);
setLocationByPlatform(true);
// set frame icon and title
Image img = kit.getImage("icon.gif");
setIconImage(img);
setTitle("SizedFrame");
}
}
50. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
6
Display information inside frame
Frames in Java are designed to be containers for other components like button, menu bar, etc.
You can directly draw onto a frame, but it’s not a good programming practice
Normally draw on another component, called panel, using Jpanel
Before JDK5, get the content pane of frame first, then add component on it
Container contentPane = getContentPane();
Component c = …;
contentPane.add(c);
After JDK5, you can directly use frame.add(c);
import javax.swing.*;
import java.awt.*;
class NotHelloWorld
{
public static void main(String[] args)
{
NotHelloWorldFrame frame = new NotHelloWorldFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
/**
A frame that contains a message panel
*/
class NotHelloWorldFrame extends JFrame
{
public NotHelloWorldFrame()
{ setTitle("NotHelloWorld");
setSize(300,300);
// add panel to frame
NotHelloWorldPanel panel = new NotHelloWorldPanel();
add(panel);
}
}
/**
A panel that displays a message.
*/
class NotHelloWorldPanel extends JPanel
{
public void paintComponent(Graphics g)
{
super.paintComponent(g);
g.drawString("Not a Hello, World program", 75,100);
}
}
paintComponent() is a method of JComponent class, which is superclass for all nonwindow Swing
components
Never call paintComponent() yourself. It’s called automatically whenever a part of your application
needs to be drawn
User increase the size of the window
User drag and move the window
Minimize then restore
It takes a Graphics object, which collects the information about the display setting
3.3 Components
The java.awt.Component is one of the cornerstones of AWT programming. It contains approximately
half of the classes in AWT. AWT is built on the Component class.
51. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
7
Component class – an abstract class for GUI components such as buttons, menus, labels,
lists, etc.
Container – An abstract class that extends Component. Classes derived from the Container
class can contain multiple components. Examples are Panel, Applet, Window, Frame, etc.
LayoutManager – An interface for positing and sizing Container objects. Java defines
several default implementations. You can also create your custom layout.
Graphics class– An abstract class that defines methods for performing graphical operations.
Every component has an associated Graphics object.
java.awt.Component subclasses (in java.awt package):
java.awt.Container subclasses (in java.awt package):
java.awt.LayoutManager interface implementations:
Label Displays text in a box
Button A clickable button, can generate event
Canvas Area for painting graphics
Checkbox A button that provides on/off toggle values. Can
be used for both Check box and radio buttons
(when contained in a CheckBoxGroup)
Choice Combo box where a list of items can be displayed
by clicking the button
List A component that displays a list of selectable items
Scrollbar A scrollable bar
TextComponent Superclass for TextField and TextArea
TextArea Multiple line text input box
TextField One line user input text box
Applet Superclass of all applets, an extension of Panel
Dialog Can be modal or non-modal. Extends Window
FileDialog Opens a regular file dialog
Frame All applications are contained in a Frame. Extends
Window. It can have a menubar unlike an applet
Panel A simple container of other components including Panels
Window It is rarely used directly, but useful for spash screen
when an app starts. No menu or border. Parent of
Frame and Dialog
BorderLayout Compoents are layed out in North/South,
East/West and Center
CardLayout Deck of panels where panels are displayed one at a
time
FlowLayout Component flow from left to right, top to bottom.
When there is no real estate to maneuvar on the
right, goes down. Widely used.
GridBagLayout Each componet location is defined using grid.
Most difficult to implement.
GridLayout Components are layed out in a grid. Component is
streched to fill the grid.
52. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
8
3.4Working with 2D shapes
To draw shapes in the Java 2D library, you need to obtain an object of the Graphics2D class. This
class is a subclass of the Graphics class. Ever since Java SE 2, methods such as paintComponent
automatically receive an object of the Graphics2D class. Simply use a cast, as follows:
public void paintComponent(Graphics g)
{
Graphics2D g2 = (Graphics2D) g;
. . .
}
The Java 2D library organizes geometric shapes in an object-oriented fashion. In particular, there are
classes to represent lines, rectangles, and ellipses:
Line2D
Rectangle2D
Ellipse2D
These classes all implement the Shape interface.
To draw a shape, you first create an object of a class that implements the Shape interface and then
call the draw method of the Graphics2D class.
Drawing Rectangle
Rectangle 2D rect = . . .;
g2.draw(rect);
There are two versions of each Shape class
one with float coordinates (conserves memory)
one with double coordinates (easier to use)
Rectangle2D.Float floatRect = new Rectangle2D.Float(10.0F, 25.0F, 22.5F, 20.0F);
Rectangle2D.Double doubleRect = new Rectangle2D.Double(10.0, 25.0, 22.5, 20.0);
Rectangles are simple to construct
Requires four arguments
x- and y-coordinates of the upper-left corner
the width and the height
The Rectangle2D class has over 20 useful methods including:
get Width
getHeight
getCenterX
getCenterY
Sometimes you don’t have the top-left corner readily available.
53. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
9
It is possible to have two diagonal corners of a rectangle that are not the top-left corner and the
bottom-right corner.
To create a rectangle in this case use the setFrameFromDiagonal method.
Rectangle2D rect = new Rectangle2D.Double();
rect.setFrameFromDiagonal(px, py, qx, qy);
If you have a Point2D object, you can also create a rectangle by calling
Rectangle2D rect = new Rectangle2D.Double(p1, p2);
Drawing Ellipse
The class Ellipse2D is inherited from the same Rectangle class that Rectangle2D is.
because of the bounding box surrounding the ellipse
So, creating an Ellipse2D object is very similar to creating a Rectangle2D object.
Ellipse2D e = new Ellipse2D.Double(px, py, qx, qy)
where px, py are the x- and y-coordinates of the top-left corner
and qx, qy are the x- and y-coordinates of the bottom-right corner
of the bounding box of the ellipse
Drawing Line
To construct a line, simple use the Line2D class.
It too, requires 4 arguments (the x and y coordinates of the start and end positions)
These coordinates can be 2 Point2D objects or 2 pairs of numbers.
Line2D line = new Line2D.Double(start, end)
or
Line2D line = new Line2D.Double(px, py, qx, qy)
Filling Shapes
You can fill the interior of closed shape objects with a color.
Simply call the fill instead of draw method on the Graphics object.
Rectangle2D rect = new Rectangle2D.Double(x, y, x2, y2);
g2.setPaint(Color.red);
g2.fill(rect);
/**
* A frame that contains a panel with drawings
*/
class DrawFrame extends JFrame
{
public DrawFrame()
{
setTitle("DrawTest");
setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
// add panel to frame
DrawComponent component = new DrawComponent();
add(component);
}
public static final int DEFAULT_WIDTH = 400;
public static final int DEFAULT_HEIGHT = 400;
}
/**
* A component that displays rectangles and ellipses.
*/
class DrawComponent extends JComponent
{
public void paintComponent(Graphics g)
{
Graphics2D g2 = (Graphics2D) g;
// draw a rectangle
double leftX = 100;
double topY = 100;
double width = 200;
double height = 150;
Rectangle2D rect = new Rectangle2D.Double(leftX, topY, width, height);
g2.draw(rect);
54. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
10
// draw the enclosed ellipse
Ellipse2D ellipse = new Ellipse2D.Double();
ellipse.setFrame(rect);
g2.draw(ellipse);
// draw a diagonal line
g2.draw(new Line2D.Double(leftX, topY, leftX + width, topY + height));
// draw a circle with the same center
double centerX = rect.getCenterX(); double centerY = rect.getCenterY();
double radius = 150;
Ellipse2D circle = new Ellipse2D.Double();
circle.setFrameFromCenter(centerX, centerY, centerX + radius, centerY + radius);
g2.draw(circle);
}
}
3.5 using colors
Class Color declares methods and constants for manipulating colors in a Java
program(java.awt.Color)
Every color is created from a red, a green and a blue component – RGB values
Common Constructors:
Color (int Red, int Green, int Blue) Creates a color with the designated combination of red, green,
and blue (each 0-255).
Color (float Red, float Green, float Blue) Creates a color with the designated combination of red,
green, and blue (each 0-1).
Color (int rgb) Creates a color with the designated combination of red, green, and blue (each 0-255).
Common Methods:
getBlue () Returns the blue component of the color.
getGreen () Returns the green component of the color.
getRed () Returns the red component of the color.
import java.awt.*;
import java.awt.geom.*;
import javax.swing.*;
class FillTest
{
public static void main(String[] args)
{
FillFrame frame = new FillFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.show();
}}
/**
A frame that contains a panel with drawings
Color constant Color RGB value
public final static Color RED red 255, 0, 0
public final static Color GREEN green 0, 255, 0
public final static Color BLUE blue 0, 0, 255
public final static Color ORANGE orange 255, 200, 0
public final static Color PINK pink 255, 175, 175
public final static Color CYAN cyan 0, 255, 255
public final static Color MAGENTA magenta 255, 0, 255
public final static Color YELLOW yellow 255, 255, 0
public final static Color BLACK black 0, 0, 0
public final static Color WHITE white 255, 255, 255
public final static Color GRAY gray 128, 128, 128
public final static Color LIGHT_GRAY lightgray 192, 192, 192
public final static Color DARK_GRAY darkgray 64, 64, 64
55. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
11
*/
class FillFrame extends JFrame
{
public FillFrame()
{
setTitle("FillTest");
setSize(400,400);
// add panel to frame
FillPanel panel = new FillPanel();
Container contentPane = getContentPane();
contentPane.add(panel);
}
}
/**
A panel that displays filled rectangles and ellipses
*/
class FillPanel extends JPanel
{ public void paintComponent(Graphics g)
{ super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
// draw a rectangle
Rectangle2D rect = new Rectangle2D.Double(100,100,200,150);
g2.setPaint(Color.RED);
g2.fill(rect);
// draw the enclosed ellipse
Ellipse2D ellipse = new Ellipse2D.Double();
ellipse.setFrame(rect);
g2.setPaint(new Color(0, 128, 128)); // a dull blue-green
g2.fill(ellipse);
}}
3.5 using font
Class Font
Constructor takes three arguments—the font name, font style and font size
Font name – any font currently supported by the system on which the program is
running
Font style –Font.PLAIN, Font.ITALIC or Font.BOLD. Font styles can be used in
combination
Font sizes – measured in points. A point is 1/72 of an inch.
Methods getName, getStyle and getSize retrieve information about Font object
Graphics methods getFont and setFont retrieve and set the current font, respectively
Method or constant Description
Font constants, constructors and methods
public final static int PLAIN
A constant representing a plain font style.
public final static int BOLD
A constant representing a bold font style.
public final static int ITALIC
A constant representing an italic font style.
public Font( String name, int style, int size )
Creates a Font object with the specified font name, style and
size.
public int getStyle()
Returns an integer value indicating the current font style.
public int getSize()
Returns an integer value indicating the current font size.
56. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
12
import java.awt.*;
import java.awt.font.*;
import java.awt.geom.*;
import javax.swing.*;
class FontTest
{
public static void main(String[] args)
{
FontFrame frame = new FontFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.show();
}
}
/**
A frame with a text message panel
*/
class FontFrame extends JFrame
{
public FontFrame()
{
setTitle("FontTest");
setSize(300,200);
// add panel to frame
FontPanel panel = new FontPanel();
Container contentPane = getContentPane();
contentPane.add(panel);
}
}
/**
A panel that shows a centered message in a box.
*/
class FontPanel extends JPanel
{ public void paintComponent(Graphics g)
{ super.paintComponent(g);
String message = "Hello, World!";
Font f = new Font("Serif", Font.BOLD, 36);
g.setFont(f);
g.drawString(message, 50,100);
Font f1 = new Font("Arial", Font.ITALIC, 30);
g.setFont(f1);
g.drawString(message, 50,150);
}
}
Method or
constant Description
public String getName()
Returns the current font name as a string.
public String getFamily()
Returns the font’s family name as a string.
public boolean isPlain()
Returns true if the font is plain, else false.
public boolean isBold()
Returns true if the font is bold, else false.
public boolean isItalic()
Returns true if the font is italic, else false.
Graphics methods for manipulating Fonts
public Font getFont()
Returns a Font object reference representing
the current font.
public void setFont( Font f )
Sets the current font to the font, style and
size specified by the Font object reference f.
57. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
13
3.5 using images
You can display images on the Graphics object.
You can use images stored locally or someplace on the Internet.
Step1: Loading an image
java.awt.Toolkit
Toolkit getDefaultToolkit()- returns the default toolkit.
Image getImage(String filename) - returns an image that will read its pixel data from a file.
Toolkit object can only read GIF and JPEG files.
Step2: displaying an image
java.awt.Graphics
boolean drawImage(Image img, int x, int y, ImageObserver observer)- draws a scaled image.
boolean drawImage(Image img, int x, int y, int width, int height, ImageObserver observer) - draws a
scaled image. The system scales the image to fit into a region with the given width and height. Note:
This call may return before the image is drawn.
If an image is stored locally call:
String filename = ―…‖;
Image image = ImageIO.read(new File(filename));
If an image is on the Internet, use the url:
String filename = ―…‖;
Image image = ImageIO.read(new URL(url);
import java.awt.*;
class Demo extends Frame{
Demo(String s){
super(s);setSize(300,300);
setVisible(true);
}
public void paint(Graphics g) {
Toolkit tk = Toolkit.getDefaultToolkit();
Image img= tk.getImage("Sunset.jpg");
for (int i = 20; i <300-20; i=i+20)
for (int j = 40; j <300-20; j=j+20)
g.drawImage(img,i,j,20,20,null);
}
public static void main(String arg[]){
Demo ob=new Demo("Image Demo");
}
}
AWT Components
All components are subclass of Component class
Components allow the user to interact with application. A layout manager
arranges components within a container (Frame/Applet/Panel).
Adding and Removing Controls
58. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
14
add(Component compObj)- add components to the conatainer. Once it is added, it will
automatically be visible whenever its parent window is displayed. Here, compObj is an
instance of the control that you want to add.
void remove(Component obj)- remove a control from a window
removeAll( )- remove all controls from a window
Component Constructor Methods
Label Label( ) void setText(String str)
Label(String str) String getText( )
Label(String str, int how)
Button Button( ) void setLabel(String str)
Button(String str) String getLabel( )
List List( ) void add(String name)
List(int numRows) void add(String name, int
List(int numRows, boolean multipleSelect) index)
String getSelectedItem( )
int getSelectedIndex( )
String[ ] getSelectedItems( )
Choice Choice( ) void add(String name)
String getSelectedItem( )
int getSelectedIndex( )
Checkbox Checkbox( ) boolean getState( )
Checkbox(String str) void setState(boolean on)
Checkbox(String str, boolean on) String getLabel( )
Checkbox(String str, boolean on, CheckboxGroup cbGroup) void setLabel(String str)
Checkbox(String str, CheckboxGroup cbGroup, boolean on)
TextField TextField( ) String getText( )
TextField(int numChars) void setText(String str)
TextField(String str) void setEditable(boolean
TextField(String str, int numChars) canEdit)
TextArea TextArea( ) void append(String str)
TextArea(int numLines, int numChars) void insert(String str, int
TextArea(String str) index)
TextArea(String str, int numLines, int numChars)
Label
Labels are components that hold text.
Labels don’t react to user input. It is used to identify components.
Constructors
Label(String str) - constructs a label with left-aligned text.
Label(String str, int how) - constructs a label with the alignment specified by how.
Methods
void setText(String str)- set the text in the label
String getText( )- return the text of label
59. CS2305 Programming Paradigms V.Saravanakumar,AP/CSE
15
Example: The following example creates three labels and adds them to a frame..The labels are
organized in the frame by the flow layout manager.
import java.awt.*; Demo ob=new Demo("Label Demo");
public class Demo extends Frame{ }
Label lb1 = new Label("One"); }
Label lb2 = new Label("Two"); Output:
Label lb3 = new Label("Three");
FlowLayout flow= new FlowLayout();
Demo(String s){
super(s);
setSize(200,200);
setLayout(flow);
add(lb1);add(lb2);add(lb3);
setVisible(true);
}
public static void main(String arg[]){
Button
A push button is a component that contains a label and that generates an event when it is pressed.
Push buttons are objects of type Button.
Constructors
Button( )- creates an empty button
Button(String str)- creates a button that contains str as a label.
Methods
void setLabel(String str) -set the label in the button
String getLabel( ) -return the label of button
Example: The following example creates three buttons and adds them to a frame. The buttons are
organized in the frame by the flow layout manager.
public static void main(String arg[]){
import java.awt.*; Demo ob=new Demo("Button Demo");
public class Demo extends Frame{ } }
FlowLayout flow= new FlowLayout(); Output:
Button b=new Button();
Button b1=new Button();
Button b2=new Button("Button 2");
Demo(String s){
super(s);setSize(200,200);
setLayout(flow);
b1.setLabel("Button 1");
add(b);add(b1);add(b2);
setVisible(true);
}