0% found this document useful (0 votes)
13 views63 pages

Chapter 01 - Introduction

Uploaded by

adikari.seww
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views63 pages

Chapter 01 - Introduction

Uploaded by

adikari.seww
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 63

OBJECT ORIENTED

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.

Eg: class Student{ public static void main(String args[]){


int id; Student s1 = new Student(111,"Karan");
String name; Student s2 = new Student(222,"Aryan");
Student(int i, String n){
id = i; s1.display();
name = n; s2.display();
} }
void display(){ }
16
System.out.println(id+" "+name);
}
Unified Modeling Language (UML) Class Diagrams
• A class and its members can be described graphically using a notation known as the
Unified Modeling Language (UML) notation.
• The top box contains the name of the class.
CourseType The middle box contains the member
- courseName : string variables and their data types. The last box
- courseCredits : int contains the member function name,
parameter list, and the return type of the
+ setCourseInfo(string, int) : void
function.
+ print() : void
• A + (plus) sign in front of a member name
+ getCredits() : int
indicates that this member is a public
+ getCourseNumber() : string
member; a - (minus) sign indicates that this is
+ getCourseName() : string
a private member. The symbol # before the 17

member name indicates that the member is a


protected member.
Example

18
Data field
class Circle {
double radius = 1;
Example
Circle() { // Construct a circle object //
}
Constructors
Circle(double newRadius) { // Construct a circle object //
radius = newRadius;
}

double getArea() { // Return the area of this circle //


return radius * radius * Math.PI;
Methods }

double getPerimeter() { // Return the perimeter of this circle //


return 2 * radius * Math.PI;
}

double setRadius(double newRadius) { // Set new radius for this


circle // 19
return radius = newRadius;
}
}
public static void main(String[] args) { Example
// Create a circle with radius 1
Circle circle1 = new Circle();
System.out.println("The area of radius "+ circle1.radius + " is " + circle1.getArea());

// Create a circle with radius 25


Circle circle2 = new Circle(25);
System.out.println("The Perimeter of radius "+ circle2.radius + " is " + circle2. getPerimeter());

// Create a circle with radius 125


Circle circle3 = new Circle(125);
System.out.println("The area of radius " + circle3.radius + " is " +circle3.getArea());

// Modify circle radius


circle2.radius = 100; // or circle2.setRadius(100)
20
System.out.println("The area of radius “ + circle2.radius + " is " + circle2.getArea());
}
}
Exercise
• The UML diagram for the class TV is shown bellow.

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

Access Modifiers - controls the access level


Non-Access Modifiers - do not control access level, but provides other
functionality

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

– The class, data, or method is visible to any class in any package.


– A class, method, constructor, interface etc declared public can
be accessed from any other class. Therefore fields, methods,
blocks declared inside a public class can be accessed from any
class belonging to the Java Universe.

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:

package pack; package pack;


class A{ class B{
void msg(){ public static void main(String args[]){
System.out.println("Hello"); A obj = new A();
} obj.msg();
} }
}
38
39
Non-Access Modifiers
• Non-access modifiers do not change the accessibility of variables and methods, but
they do provide them special properties.
• They are static, final, abstract, synchronized, transient, volatile, native and strictfp.
• Classes can use either final or abstract
• attributes, methods and constructors can use other non-access modifiers.

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
}

public static void increment(int n) {


n++;
System.out.println("n inside the method is " + n);//2 43
}
}
Final Modifier
Final Variable:

• A final variable can be explicitly initialized only once. Final variable is a


constant; its value cannot be changed after its initialization.
• A reference variable declared final can never be reassigned to refer to an
different object.
• However, the data within the object can be changed. So, the state of the object
can be changed but not the reference.
• With variables, the final modifier often is used with static to make the constant a
class variable. 44
public class Test {
Example:
final int value = 10;
// The following are examples of declaring constants:

public static final int BOXWIDTH = 6;


static final String TITLE = "Manager";

public void changeValue() {


value = 12; // will give an error
}
45
}
Final Modifier
Final Methods:
• A final method cannot be overridden by any subclasses. As mentioned previously,
the final modifier prevents a method from being modified in a subclass.
• The main intention of making a method final would be that the content of the
method should not be changed by any outsider.

public class Test {


public final void changeName() {
// body of method
}
}
46
Final Modifier
Final Class:

• The main purpose of using a class being declared as final is to prevent


the class from being sub-classed. If a class is marked as final then no
class can inherit any feature from the final class.
public final class Test {
// body of class
}

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

methods as well normal methods.


50
Abstract Modifier
Abstract Method:
• An abstract method is a method declared without any implementation. The
methods body (implementation) is provided by the subclass. Abstract methods
can never be final.
• Any class that extends an abstract class must implement all the abstract
methods of the super class, unless the subclass is also an abstract class.
• If a class contains one or more abstract methods, then the class must be
declared abstract. An abstract class does not need to contain abstract methods.
• The abstract method ends with a semicolon.
– Example: public abstract sample(); 51
this Reference
• The this keyword is the name of a reference that an object can use to
refer to it self. It can also be used inside a constructor to invoke another
constructor of the same class.
• Usage of java this keyword
– this keyword can be used to refer current class instance variable.
– this() can be used to invoke current class constructor.
– this keyword can be used to invoke current class method (implicitly)
– this can be passed as an argument in the method call.
– this can be passed as argument in the constructor call.
– this keyword can also be used to return the current class instance. 52
Example: refer current class instance variable
class Student{
int id;
String name;
Student(int id,String name){
this.id = id;
this.name = name;
}
……
53
}
– Calling a constructor from the another
Constructor Chaining
constructor of same class is known as
Constructor chaining.
– The real purpose of Constructor
Chaining is that you can pass
parameters through a bunch of different
constructors, but only have the
initialization done in a single place.
– This allows you to maintain your
initializations from a single location,
while providing multiple constructors
to the user. 54
Example: constructor chaining
class Student { Student(int id,String name){
this ();
int id;
// invoked current class constructor.
String name;
Student(){ this.id = id;
this.name = name;
System.out.println("default constis invoked"); }
} ……
}

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

• A Java enum is a special Java type used to define collections of constants.


More precisely, a Java enum type is a special kind of Java class.
• An enum can contain constants, methods etc. Java enums were added in
Java 5.
• Enum declaration can be done outside a Class or inside a Class but not
inside a Method.

58
Example: enum outside the class
enum Color {
RED, GREEN, BLUE;
}

public class Test


{
// Driver method
public static void main(String[] args) {
Color c1 = Color.RED;
System.out.println(c1);
}
} Output: RED 59
Example: enum inside the class
public class Test {
enum Color {
RED, GREEN, BLUE;
}

public static void main(String[] args) {


Color c1 = Color.RED;
for(Color s:Color.values()){
System.out.println(s);
}
} 60

}
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

You might also like