Chapter 01 - Introduction
Chapter 01 - Introduction
PROGRAMMING
CS 1032
Chapter – 01
Objects and Classes
2
Object Oriented Programming
• Object Oriented
programming(OOP) is an approach
to organizing programs.
• OOP is a programming paradigm that
uses abstraction to create object
models based on the real world
environment.
3
4
Object Oriented Programming
• The real world consists of objects. Computer programs may contain computer world
representations of the things (objects) that constitute the solutions of real world
problems.
– Real world objects have two parts:
Properties (or state :characteristics that can change),
Behavior (or abilities :things they can do).
– To solve a programming problem in an object-oriented language, the programmer
no longer asks how the problem will be divided into functions, but how it will be
divided into objects. 5
• What kinds of things become objects in object-oriented programs?
– Human entities: Employees, customers, salespeople, worker, manager
– Graphics program: Point, line, square, circle, ...
– Mathematics: Complex numbers, matrix
– Computer user environment: Windows, menus, buttons
– Data-storage constructs: Customized arrays, stacks, linked lists 6
Objects
• An object is a software bundle of related variables and methods which are represents
an entity in the real world that can be distinctly identified.
• An object has a unique identity, state, and behavior.
– The state of an object (also known as its properties or attributes) is represented
by data fields with their current values.
Eg, A rectangle object has the data fields width and height
– The behavior of an object (also known as its actions) is defined by methods. To
invoke a method on an object is to ask the object to perform an action.
7
Eg, getArea() and getPerimeter() for circle objects.
Class
• Objects of the same type are defined using a common class. A class is a template,
prototype, blueprint, or contract that defines the data fields and the methods
common to all objects of a certain kind.
• An object is an instance of a class. Many instances can be created in a class.
Creating an instance is referred to as instantiation.
• A Java class uses variables to define data fields and methods to define actions.
• A class provides methods of a special type, known as constructors, which are
invoked to create a new object. A constructor can perform any action, but
constructors are designed to perform initializing actions, such as initializing the data
8
fields of objects.
Class and Objects
Class
Car
Lamborghini
BMW Ferrari
9
Objects
Class and Objects
Class
name
Name
Height
Weight
Hair color
Walking
Talking
Writing
10
Class and Objects
11
Class and Objects: Example
Mala Object
Data Name=“Mala Muru"
Class members Hair color=Black
Object
Human Peter
Name
Name=“Peter Peris"
Hair color Member Hair color= Brown
talking functions
walking Object
kiril
Name=“Kiril Kasun" 12
Hair color= Gray
Example: Defining the class for circle objects
13
Constructor
• Constructor in java is a special type of method that is used to initialize the object.
• Constructor is a block of code, which runs when you use new keyword in order
to instantiate an object.
• Rules:
– A constructor must have the same name as the class itself.
– Constructors do not have a return type—not even void.
– Constructors are invoked using the new operator when an object is created.
14
Default Constructor
• A constructor that have no parameter is known as default constructor.
• Syntax: <class_name>(){}
• Eg: class Bike{
Bike(){
System.out.println("Bike is created");
}
public static void main(String args[]){
Bike b=new Bike();
}
}
• Note: If there is no constructor in a class, compiler automatically creates a default
15
constructor.
Parameterized Constructor
• A constructor that have parameters is known as parameterized constructor.
• Parameterized constructor is used to provide different values to the distinct objects.
18
Data field
class Circle {
double radius = 1;
Example
Circle() { // Construct a circle object //
}
Constructors
Circle(double newRadius) { // Construct a circle object //
radius = newRadius;
}
21
22
1. Local Variable
• A variable defined inside a method, constructor, or block is referred to as a local
variable. The scope of a local variable starts from its declaration and continues to
the end of the block that contains the variable. A local variable must be declared
and assigned a value before it can be used.
• Local variables are created when the method, constructor or block is entered and
the variable will be destroyed once it exits the method, constructor or block.
• Access Modifiers cannot be used.
• There is no default value for local variables, so local variables should be
declared and an initial value should be assigned before the first use. 23
class Puppy{ Example:
public void puppyAge(){
int age = 0;
age = age + 7;
System.out.println("Puppy age is : " + age); Note: You can declare a
}
local variable with same
public static void main(String[] args){
name in different blocks or
different methods, but you
int age=10;
cannot declare a local
Puppy p= new Puppy();
variable twice in the same
p.puppyAge();
block or in nested blocks,
System.out.println(“Age of the
Puppy”+age); 24
}
}
2. Instance Variable
• Instance variables are declared in a class, but outside a method, constructor or
any block.
• They are created when objects are created with the ‘new’ keyword and
destroyed when the object is destroyed.
• Instance variables hold values that must be referenced by more than one
method, constructor or block.
• Access modifiers can be given for instance variables.
• Instance variables are visible for all methods, constructors and blocks in the
class. Instance variables have default values.
25
• Can be accessed directly by calling the variable name inside the class.
public class Employee{
Example:
int empNum = 12345;
String name = “David”;
String dept = “IT”;
public static void main(String[] args){
Employee emp = new Employee();
System.out.println(“Employee Number”+emp.empNum);
System.out.println(“Name”+emp.name);
System.out.println(“Department”+emp.dept);
} 26
}
3. Class Variable
• Class variables are declared with the static keyword in a class, but outside a
method, constructor or a block.
• They are associated with the class, not with any object. A static variable can
be accessed directly by the ClassName.variableName and doesn’t need any
object.
• Static variables store values for the variables in a common memory
location. Because of this common location, if one object changes the value
of a static variable, all objects of the same class are affected.
• Static variables are initialized only once, at the start of the execution. These
variables will be initialized first, before the initialization of any instance 27
variable.
public class StatVar{
Example:
static int x=10;
public void addTwo(){
x=x+2;
}
public static void main(String[] args){
System.out.println(“Value: "+x); //10
StatVar a = new StatVar();
a.addTwo();
System.out.println(“Value : "+x); //12
28
}
Modifiers
29
Access Modifiers
• An access modifier restricts the access of a class, constructor, data member and
method in another class.
• There are 4 types of java access modifiers:
– Private : Visible to the class only
– default/package : Visible to the package. No modifiers are needed.
– Protected : Visible to the package and all subclasses
– Public : Visible to the world
• Classes and interface can use either public or default
• attributes, methods and constructors can use one among the four access modifiers.
30
Public Modifier
31
class MyClass{ Example 1:
public int myNum=10;
public int getMyNum(){
return myNum;
}
}
class InstanceTest{
public static void main(String[] args){
MyClass mc=new MyClass();
System.out.println(“Value of myNumber: ”+mc.myNum);
System.out.println(“Value return by method: ”+mc.getMyNum());
32
}
}
Example 2:
package mypack;
import pack.*;
package pack;
public class A{
class B{
public void msg(){
public static void main(String args[])
System.out.println("Hello");
{
}
A obj = new A();
}
obj.msg();
}
}
33
Private Modifier
– The data or methods can be accessed only by the declaring class. The
get and set methods are used to read and modify private properties.
– A private member of a class may only be accessed from the code inside
the same class in which this member is declared
– Class and Interface cannot be declared private; it can only be public, or
default
34
Example:
public class Logger {
private String format;
public String getFormat() {
return format;
}
public void setFormat(String format) {
this.format = format;
}
} 35
Protected Modifier
– Variables, methods, and constructors, which are declared protected in a
superclass can be accessed only by the subclasses in other package or within the
package of the protected members' class.
– The protected access modifier cannot be applied to class and interfaces.
– Methods, fields can be declared protected, however methods and fields in a
interface cannot be declared protected.
– Protected access gives the subclass a chance to use the helper method or
variable, while preventing a non-related class from trying to use it.
36
Example:
package mypack;
import pack.*;
package pack;
class B extends A{
public class A{
public static void main(String args[]{
protected void msg(){
B obj = new B();
System.out.println("Hello");
obj.msg();
}
}
}
}
37
Default/Package Modifier
• A variable or method declared without any access control modifier is available
to any other class in the same package.
• Example:
40
Static Modifier
• Static Modifiers are used to create class variable and class methods which can be
accessed without instance of a class.
• Static variable:
– The static keyword is used to create variables that will exist independently of any
instances created for the class. Only one copy of the static variable exists regardless
of the number of instances of the class. Static variables are also known as class
variables. Local variables cannot be declared static.
41
Static
• Static Methods:
– The static keyword is used to create methods that will exist independently of
any instances created for the class. Static methods do not use any instance
variables of any object of the class they are defined in. Static methods take all
the data from parameters and compute something from those parameters, with
no reference to variables.
• Class variables and methods can be accessed using the class name followed by a
dot and the name of the variable or method.
42
public class Increment {
static int x = 1; Example:
public static void main(String[] args) {
System.out.println("Before the call, x is " + x); //1
increment(x);
System.out.println("After the call, x is " + x); //1
x++;
System.out.println("After the call, x is " + x); //2
}
47
48
Abstract Modifier
Abstract Class:
• A class which is having partial
implementation. An abstract class can never abstract class Caravan {
be instantiated. If a class is declared as private double price;
abstract then the sole purpose is for the class private String model;
to be extended. private String year;
• A class cannot be both abstract and final (since public abstract void goFast();
a final class cannot be extended). If a class // an abstract method
contains abstract methods then the class public abstract void changeColor();
should be declared abstract. Otherwise, a }
compile error will be thrown.
• An abstract class may contain both abstract
49
55
Example: invoke current class method
class S{
void m(){
System.out.println("method is invoked");
}
void n(){
this.m(); //no need ,compiler does it for you.
}
void p(){
n(); //complier will add n() method as this.n()
}
…. 56
}
Example: passed as an argument in the method.
class S2{
void m(S2 obj){
System.out.println("method is invoked");
}
void p(){
m(this);
}
….
57
}
Enums
58
Example: enum outside the class
enum Color {
RED, GREEN, BLUE;
}
}
Exercise
class Exercise{ • Make the class Exercise as public
Exercise(String name, int age){ • Class has two instance variables named
as name with public accessibility and
}
address with private accessibility.
void TestExercise(){ • Class has a static constant variable AGE
} with the value 25.
} • Local variable number with value 20.
• Member function and constructor has
public modifier.
61
Exercise:
(The MyPoint class) Design a class named MyPoint to represent a point with x- and
y-coordinates. The class contains:
• The data fields x and y that represent the coordinates with getter methods.
• A no-arg constructor that creates a point (0, 0).
• A constructor that constructs a point with specified coordinates.
• A method named distance that returns the distance from this point to a specified
point of the MyPoint type.
• A method named distance that returns the distance from this point to another point
with specified x- and y-coordinates.
Draw the UML diagram for the class and then implement the class. Write a test
program that creates the two points (0, 0) and (10, 30.5) and displays the distance
62
between them.
Chapter 02
63