Mettu University
Advanced Programming - ITec3054
Chapter 1 - Introduction to Java
Prepared by: Sridhar U
Getting used to OOPS way of doing things
Bucket list
• What is Object oriented paradigm
• Everything is objects!
• Objects are instances of class
• 5 OOP Principles
• Advantage of being object-oriented
• Other object-oriented programming languages
• Glance of Static and Final keywords
What is object-oriented paradigm
• OOP can be defined as a pattern that uses “Objects” to
do everything (or) anything, whoever requests for.
» 1. I need to read alphabets---------- I’ll join you
in school
» 2. I’m lazy enough to walk to school----- I’ll give
you a bicycle
» 3. I want to write alphabets -------------- I’ll give
you a pen
Everything is objects!
• School, Bicycle & Pen are objects
• Objects are real-world entity
• Objects have state & behavior
Everything is objects!
• Benefits of using objects
– Modularity (A library in school can be modularized away from all
sections in a school)
– Information-hiding (I don’t care about how the engine works, I want
to reach office @ 9:30 am)
– Code re-use (A single library can be re-used)
– Pluggability & debugging ease (bolts)
Objects are instances of class
• Class is a template (or) blueprint from which objects
are created.
• Each objects are instances of a class
5 oop principles
• Encapsulation/Data Hiding
• Inheritance (Remodeled bicycle)
• Polymorphism (E.g. finding area of shapes)
• Abstraction (If you don’t know something, then don’t do
it!)
• Interface (choosing which mode of travel based on
situation)
Advantage of being oo
• component-specific behavior
• polymorphic expressions
• type abstraction
• separation of concerns
• adaptability
• code reuse
Other oop languages
Static keyword
• The static keyword is used to create fields and methods
that can be accessed without having to make an instance
of the class.
• Static (class) members only exist in one copy, which
belongs to the class itself, whereas instance (non-
static) members are created as new copies for each new
object.
• This means that static methods cannot use instance
members since these methods are not part of an instance.
On the other hand, instance methods can use both static
and instance members.
Static - example
class MyCircle
{
float r = 10; // instance field
static float pi = 3.14F; // static/class field
// Instance method
float getArea() { return newArea(r); }
// Static/class method
static float newArea(float a) { return pi*a*a; }
}
Accessing static members:
public static void main(String[] args)
{
float f = MyCircle.pi;
MyCircle c = new MyCircle();
float g = c.r;
}
Final keyword
• All Methods and variable can be overridden by default in
subclasses. If we wish to prevent the subclasses from
overriding the members of the super class . We can declare
them as final using the keyword final as modifier.
Local Constants:
final double PI = 3.14;
Constant fields
class MyClass
{
final double E = 2.72;
static final double C = 3e8;
}
OPERATORS AND EXPRESSIONS
Operators And Expressions
Operators are used in programs to manipulate data and variables..
Types of Operators are:
Arithmetic Operators - +,-,*, /,%
Relational Operators - <,<=,>,>=,= =, !=
Logical Operators - &&, || , !
Assignment Operators - Variable op = Exp;
Increment & Decrement - ++, --
Conditional Operator - exp ? exp2 : exp3
Bitwise Operators - &, !, ^, <<, >>, >>>
Special Operators - instanceOf, .(dot)
CONTROL FLOW STATEMENTS
Conditionals & Looping
• Conditional statements are used to execute different
code blocks based on different conditions
• Decision Making & Branching
if statement
switch statement
Conditional operator statement
Decision Making & Looping
While Loop
do-while Loop
for loop
for each
CLASSES AND OBJECT
Classes
A class is a template used to create objects. They are made up of
members, the main two of which are fields and methods.
Fields are variables that hold the state of the object, while methods
define what the object can do.
class MyRectangle
{
int x, y;
int getArea() { return x * y; }
}
Object creation
To access a class’s fields and methods from outside the defining class, an object of the
class must first be created.
This is done by using the new keyword, which will create a new
object in the system’s memory.
public class MyApp
{
public static void main(String[] args)
{
// Create an object of MyRectangle
MyRectangle r = new MyRectangle();
}
}
Accessing object members
The members of this object can be reached by using the dot operator after the instance
name.
class MyRectangle
{
public int x, y;
public int getArea() { return x * y; }
}
public static void main(String[] args)
{
MyRectangle r = new MyRectangle();
r.x = 10;
r.y = 5;
int z = r.getArea() // 50 (5*10)
}
Constructors
• The class can have a constructor. This is a special kind
of method used to instantiate (construct) the object.
• It always has the same name as the class and does not
have a return type.
class MyRectangle
{
int x, y;
public MyRectangle() { x = 10; y = 20; }
public static void main(String[] args)
{
MyRectangle r = new MyRectangle();
}
}
Constructor with parameter
• The constructor can have a parameter list, just as any
other method.
• This can be used to make the fields’ initial values
depend on the parameters passed when the object is
created.
class MyRectangle
{
int x, y;
public MyRectangle(int a, int b) { x = a; y = b; }
public static void main(String[] args)
{
MyRectangle r = new MyRectangle(20,15);
}
}
This keyword
• “this” keyword is a reference to the current instance of
the class.
class MyRectangle
{
int x, y;
public MyRectangle(int x, int y)
{
this.x = x; this.y = y;
}
}
Constructor overloading
• To support different parameter lists the
constructor can be overloaded.
class MyRectangle
{
int x, y;
public MyRectangle() { x = 10; y = 20; }
public MyRectangle(int a) { x = a; y = a; }
public MyRectangle(int a, int b) { x = a; y = b; }
}
Encapsulation
• Encapsulation is a mechanism of binding data & code
together
• Accessing the data outside the class is restricted,
which ensures high-security
• Ability to modify our data without interfering other’s
data
• Ensures maintainability, flexibility and extensibility
of our code
Encapsulation
• Power of encapsulated code is that everyone
knows how to access it regardless of its
implementation details
• As a driver, we’re not going to sit and think how the
gear mechanism works. We just need to reach office
at right time
Encapsulation
A class with Private fields; Public methods
class EncapsulatedBicycle
{
private int speed = 0;
public int getSpeed() {
return speed;
}
public void setSpeed(int speed) {
this.speed = speed;
}
}
Abstraction
• Abstraction is the way to skip implementation for some
methods; at the same time giving implementation for some
others
• Have to include a keyword “abstract” in methods and class
• Can mix both abstract & non-abstract methods
• Objects can’t be created for Abstract classes
public abstract class Bicycle {
void changeGear(int newValue) {
gear = newValue;
}
abstract void speedUp(int increment);
}
Polymorphism
• Single name with many forms (only possible in methods)
Polymorphism
• Types of Polymorphism
– Method overloading
– Method Overriding
• Method Overloading (Compile-time or static
polymorphism):
– Methods with same name; but difference in number & type of
arguments
– Should be defined in a same class
e.g. Calculating of areas of different shapes
Polymorphism
Method Overriding:
– Methods with same name, number & type of arguments
– Should be defined in different classes but should be in inheritance
tree.
– Should form IS-A relationship b/w classes
Polymorphism
Method Overriding (Runtime or dynamic polymorphism):
– Can change reference at run time (either can use super class method
implementation or the sub class’)
– Can create objects with either same class or super class as
reference
Creating objects:
1. Bicycle myRemodeledBicycleObj = new ReModeledBicycle();
2. ReModeledBicycle myRemodeledBicycleObj = new ReModeledBicycle();
CONTROL FLOW STATEMENTS
Conditionals & Looping
• Conditional statements are used to execute different
code blocks based on different conditions
• Decision Making & Branching
if statement
switch statement
Conditional operator statement
Decision Making & Looping
While Loop
do-while Loop
for loop
for each
INHERITANCE
Inheritance
• Little boy got greedy and want a Remodeled bicycle where
he can drive @ higher speeds to school
» 1. I want to Remodel my bicycle – Use the power of inheritance!
: extend Bicycle and give your own implementation
Inheritance
• OOP allows classes to inherit commonly used state &
behavior from other classes
Inheritance
• Did you notice one? – Which implementation to use, if
I’m inheriting multiple super classes?
Bicycle without
Bicycle with fuel
fuel
I can’t have a bicycle which has both
above definitions. Since it’s
contradictory
Multiple inheritance – it’s just not
possible!
Inheritance
• Super Class – Bicycle ; Child/Sub class – Remodeled
Bicycle
• Child class can use state & behavior of Super class. In
addition to that, can give its own implementation
• Each super class can have multiple sub classes
• Sub class should use following syntax to be in
inheritance hierarchy
Class SubClass extends SuperClass
{
}
Inheritance
• Types of Inheritance
Overriding members
• A member in a subclass can redefine a member in its
superclass.
class Rectangle
{
public int w = 10, h = 10;
public int getArea() { return w * h; }
}
class Triangle extends Rectangle
{
public int getArea() { return w * h / 2; }
}
Override annotation
• to show that this override was intentional, the
@Override annotation should be placed before the method.
class Triangle extends Rectangle
{
@Override public int getArea()
{
return w * h / 2;
}
}
Hiding members
• This is only true for instance methods, and not for
class methods.
• If a class method called newArea is added to Rectangle,
and redefined in Triangle, then Triangle’s version of
the method will only hide Rectangle’s implementation.
Because of this the @Override annotation is not used.
Example - Hiding members
class Rectangle
{
public int w = 10, h = 10;
public static int newArea(int a, int b) {
return a * b;
}
}
class Triangle extends Rectangle
{
public static int newArea(int a, int b) {
return a * b / 2;
}
}
• Triangle o = new Triangle();
• o.newArea(10,10); // (50) calls Triangle's version
• Rectangle r = o;
• r.newArea(10,10); // (100) calls Rectangle's version
Preventing method inheritance
• To prevent an instance method from being overridden in
subclasses, it can be declared with the final method
modifier.
• public final int getArea() { return w * h; }
Accessing overridden methods
• An overridden method can still be accessed from inside
the subclass’s instance methods by using the super
keyword.
• This keyword is a reference to the current instance of
the superclass.
@Override public int getArea()
{
return super.getArea() / 2;
}
INTERFACE
Interface! Interface!
• Dismantle the cycle, and let the boy implement on his
own.
I’m not defining I’m not defining
anything! anything!
Now, I can give my own definition.
Whether to make bicycle either with
fuel or fuel-free!
What is?
• An interface is a type that decouples “interface” from
implementation.
• They are defined with the interface keyword followed by
a name and a code block.
• When an interface is not nested inside another type, its
access level can be either package-private or public,
just as any other top-level member.
interface MyInterface {}
Interface
• Remove the implementation of all the methods and make
class - an interface
• Objects can’t be created for interface
Interface IBicycle
{
void chanceCadence(int newValue);
void changeGear(int newValue);
void speedUp(int increment);
void applyBrakes(int increment);
void setPrice(int price);
void setColor(String color);
}
Implementing an Interface
• Sub class to implement an interface, should use
implements keyword
• Should implement all methods available in interface
public class ReModeledBicycle implements Bicycle
{
Can implement more than one interface. Hence Multiple Inheritance is
achieved, indirectly!
Implementing an Interface
• Interface forms a contract b/w the class & outside world
• Class will become more formal, as it needs to give
implementation to all the methods it agreed to
EXCEPTION
What is exception?
• An exception is an event that occurs during the
execution of a program that disrupts the normal flow of
instructions.
• Just runtime!
When and Where an Exception can
occur?
• Exception can occur anywhere, anytime, to anyone!
Types of exceptions and its hierarchy
• Types of Exceptions
– Checked – exceptions are checked @ compile time (We know this might
happen!)
Types of exceptions and its hierarchy
• Types of Exceptions
– Unchecked – exceptions that are checked @ runtime (We don’t know )
– Error – exceptional conditions external to the application
(H/W or system malfunction
Types of exceptions and its hierarchy
• Exception Hierarchy
Handling/throwing Checked exceptions
• Two Parties:
– Handlers – where the exceptions are handled
– Throwers – where the exception can occur
• Catching and Handling exceptions using Try-Catch-Finally
• Throwing an exception (escaping from the
responsibility)
Handling unChecked exceptions
• Exceptions caused due to user i/p’s
• Can be thrown using throw new keyword
Throwing an exception
Writing your own exception types
• Should extend either Exception (to be a checked
exception) or Runtime Exception (to be an unchecked
exception)
• Can define any methods or override methods available in
Exception/Runtime Exception
Best practices
• Exceptions are polymorphic. So, Exceptions hierarchy should
be maintained while catching it. Don’t catch top level
exceptions at first
• Don’t create custom exceptions if they don’t provide useful
info for client code
• Cleanup the resource only in finally block
• Don’t suppress or ignore exceptions
• Decide on type of exceptions that your customized class
going to extend
• Preserve Encapsulation (Don’t allow sql exception to
propagate to Business layer; instead throw any other type
of exception)
Best practices
• Avoid empty catch blocks
• Always provide meaning full message on Exception
• Use logging
THANK YOU