Object oriented programmingchapter 03

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 34

Chapter Three

Objects and Classes

Slide 1
© Information Technology
OO Programming Concepts
 Object-oriented programming (OOP) involves programming using
objects.
 An object represents an entity in the real world that can be distinctly
identified. For example, a student, a desk, a circle, a button, and
even a loan can all be viewed as objects.
 An object has a unique identity, state, and behaviors.
 The state of an object consists of a set of data fields (also known as
properties) with their current values.
 The behavior of an object is defined by a set of methods.

Slide 2
© Information Technology
Objects
Class Name: Circle A class template

Data Fields:
radius is _______

Methods:
getArea

Circle Object 1 Circle Object 2 Circle Object 3 Three objects of


the Circle class
Data Fields: Data Fields: Data Fields:
radius is 10 radius is 25 radius is 125

Methods: Methods: Methods:


getArea = getArea = getArea =

An object has both a state and behavior. The state defines


the object, and the behavior defines what the object does.
Slide 3
© Information Technology
Classes
 Classes are constructs that define objects of the same type.
 A class is a "blueprint" for creating objects.
 A class in Java can contain:
 Data Fields/state/properties
 Methods
 Constructors
 A Java class uses variables to define data fields and methods to define
behaviors.
 Additionally, a class provides a special type of methods, known as
constructors, which are invoked to construct objects from the class.

Slide 4
© Information Technology
Classes…
class Circle {
/** The radius of this circle */
double radius = 1.0; Data field

/** Construct a circle object */


Circle() {
}
Constructors
/** Construct a circle object */
Circle(double newRadius) {
radius = newRadius;
}

/** Return the area of this circle */


double getArea() { Method
return radius * radius * 3.14159;
}
}
Slide 5
© Information Technology
UML Class Diagram

UML Class Diagram Circle Class name

radius: double Data fields

Circle() Constructors and


Circle(newRadius: double) methods
getArea(): double

circle2: Circle circle3: Circle UML notation


circle1: Circle
for objects
radius = 1.0 radius = 25 radius = 125

Slide 6
© Information Technology
Java Class Attributes(Variables)
A class can contain any of the following variable types.
 Local variables: Variables defined inside methods, constructors or blocks are
called local variables. The variable will be declared and initialized within the
method and the variable will be destroyed when the method has completed.
 Instance variables: Instance variables are variables within a class but outside
any method. These variables are instantiated when the class is loaded. Instance
variables can be accessed from inside any method, constructor or blocks of
that particular class.
 Class variables: Class variables are variables declared with in a class, outside
any method, with the static keyword.

Slide 7
© Information Technology
Java Class Constructors
 A constructor in Java is a special method that is used to construct and initialize
objects.
 It can be used to set initial values for object attributes.
 A constructor with no parameters is referred to as a no-arg constructor.
 Constructors 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.
 A class can have more than one constructor.

Slide 8
© Information Technology
Default Constructor
 A class may be defined without constructors.

 In this case, a no-arg constructor with an empty body is


implicitly defined in the class.
 This constructor, called a default constructor, is provided
automatically only if no constructors are explicitly defined in
the class.

Slide 9
© Information Technology
Constructor…

// Create a Example class


public class Example {
int x; // Create an attribute or instance
variable
// Create a constructor for the Example class
public Example() {
x = 5; // Set the initial value for the
class attribute x
}
}

Slide 10
© Information Technology
Create an Object
 As mentioned previously, a class provides the blueprints for objects. So
basically an object is created from a class. In Java, the new key word is used to
create new objects.
 There are three steps when creating an object from a class:
Declaration: A variable declaration with a variable name with an object type.

Instantiation: The 'new' key word is used to create the object.

Initialization: The 'new' keyword is followed by a call to a constructor. This call


initializes the new object.

Slide 11
© Information Technology
Create an Object…

public class Example {


int x = 5;
public static void main(String[] args) {
Example myObj = new Example(); //create object using default
constructor
System.out.println(myObj.x);
}
}

Slide 12
© Information Technology
Create an Object…
// Create a Example class
public class Example {
int x; // Create instance variable attribute
// Create a constructor for the Example class
public Example() {
x = 5; // Set the initial value for the instance attribute x
}
public static void main(String[] args) {
Example myObj = new Example(); // Create an object of class Example (This will call the constructor)
System.out.println(myObj.x); // Print the value of x
}}
Slide 13
© Information Technology
Create an Object…

// Create a Example class


public class Example {
int x; // Create instance attribute
// Create a constructor with parameter for the Example class
public Example(int y) {
x = y; // Set the initial value for the instance attribute x
}
public static void main(String[] args) {
Example myObj = new Example(7); // Create an object of class Example
(This will call the constructor)
System.out.println(myObj.x); // Print the value of x
}
}
Slide 14
© Information Technology
Create Multiple Objects…
// Create a Example class
public class Example {
int x = 5; // Create a class attribute
public static void main(String[] args) {
Example myObj1 = new Example();
Example myObj2 = new Example();
myObj2.x = 50
System.out.println(myObj1.x); // Outputs 5
System.out.println(myObj2.x); // Outputs
50
}} © Information Technology
Slide 15
Java Methods
 A method is a block of code which only runs when it is called.
 You can pass data, known as parameters, into a method.
 Methods are used to perform certain actions, and they are also known as functions.
 Why we use methods?
To reuse code: define the code once, and use it many times.
Create a Method
 A method must be declared within a class. It is defined with return type, the name of the
method, followed by parentheses ().
 Java provides some pre-defined methods, such as System.out.println(), but you
can also create your own methods to perform certain actions.

Slide 16
© Information Technology
Java Methods…
 Create and call a method

public class ExampleClass {


public void myMethod() {
System.out.println("I just got executed!");
}
public static void main(String[] args) {
ExampleClass obj = new ExampleClass();
obj.myMethod(); // Outputs "I just got executed!"
}
}
Slide 17
© Information Technology
Java Method Parameters…
 Information can be passed to methods as parameter.
 Parameters act as variables inside the method.
 Parameters are specified after the method name, inside the parentheses.
 You can add as many parameters as you want, just separate them with a
comma.
 The following example has a method that takes a String called str as
parameter.

Slide 18
© Information Technology
Java Method Parameters…
 Example

public class ExampleClass {


public void myMethod(String str) {
System.out.println(str);
}
public static void main(String[] args) {
ExampleClass obj = new ExampleClass();
obj.myMethod(“Hello”); // Outputs “Hello"
}
}

Slide 19
© Information Technology
Java Method Overloading…
 With method overloading, multiple methods can have the same name with different
signature(different return type or different parameters).
public class ExampleClass {
public int myMethod(int a, int b) {
return a+b;
}
public void myMethod() {
System.out.println(“I am Overloaded!”);
}
public static void main(String[] args) {
ExampleClass obj = new ExampleClass();
int sum = obj.myMethod(2,5);
System.out.println(sum); // Outputs 7
obj.myMethod(); // Outputs “I am Overloaded!"
}
}
Slide 20
© Information Technology
Java Scope
 In Java, variables are only accessible inside the region they are created. This is
called scope.
 A block of code refers to all of the code between curly braces {}.
 Variables declared inside blocks of code are only accessible by the code
between the curly braces, which follows the line in which the variable was
declared.
 A block of code may exist on its own or it can belong to an if, while or for
statement.

Slide 21
© Information Technology
Java Scope…

public class ExampleClass {


int y = 5; // y is accessible in the entire ExampleClass
public void myMethod() {
int x = 10; // x is accessible only in myMethod
}
public static void main(String[] args) {
ExampleClass obj = new ExampleClass();
int z = 15; // z is accessible only in Example
}
} © Information Technology
Slide 22
Java Modifiers
 By now, you are quite familiar with the public keyword that appears in
almost all of our examples.
 The public keyword is an access modifier, meaning that it is used to set the
access level for classes, attributes, methods and constructors.
 We divide modifiers into two groups:
i. Access Modifiers - controls the access level
ii. Non-Access Modifiers - do not control access level, but provides other functionality

Slide 23
© Information Technology
Java Modifiers…
Access Modifiers
For classes, you can use either public or default

Modifier Description
public The class is accessible by any other class
default The class is only accessible by classes in the
same package. This is used when you don't
specify a modifier.

Slide 24
© Information Technology
Java Modifiers…
Access Modifiers…
For attributes, methods and constructors, you can use the one of the following:
Modifier Description
public The code is accessible for all classes
private The code is only accessible within the declared class
default The code is only accessible in the same package. This is
used when you don't specify a modifier.
protected The code is accessible in the same package
and subclasses. You will learn more about subclasses and
superclasses in the Inheritance(next chapter)

Slide 25
© Information Technology
Java Modifiers…
Non-Access Modifiers
For classes, you can use either final or abstract
Modifier Description
final The class cannot be inherited by other classes (You will learn
more about inheritance in the next chapter)

abstract The class cannot be used to create objects (To access an


abstract class, it must be inherited from another class. You will
learn more about inheritance and abstraction in
the next chapter)

Slide 26
© Information Technology
Java Modifiers…
Non-Access Modifiers…
For attributes and methods, you can use the one of the following:
Modifier Description
final Attributes and methods cannot be overridden/modified
static Attributes and methods belongs to the class, rather than an object
abstract Can only be used in an abstract class, and can only be used on methods. The method
does not have a body, for example abstract void run();. The body is provided by the
subclass (inherited from). You will learn more about inheritance and abstraction in
the next chapter
transient Attributes and methods are skipped when serializing the object containing them
synchronized Methods can only be accessed by one thread at a time
volatile The value of an attribute is not cached thread-locally, and is always read from the
"Example memory"

Slide 27
© Information Technology
Java Modifiers…
Example on: private, default and public

Slide 28
© Information Technology
Java Modifiers…
An object cannot access its private members, as shown in (b). It is OK, however,
if the object is declared in its own class, as shown in (a).

Slide 29
© Information Technology
Java Modifiers…
static vs non-static modifier
blic class Example {
// Static method
static void myStaticMethod() {
System.out.println("Static methods can be called without creating objects");
}
// Public method
public void myPublicMethod() {
System.out.println("Public methods must be called by creating objects");
}
// Example method
public static void main(String[] args) {
myStaticMethod(); // Call the static method
// myPublicMethod(); This would compile an error
Example myObj = new Example(); // Create an object of Example
myObj.myPublicMethod(); // Call the public method on the object
}
Slide 30
© Information Technology
Java Scanner Class

 The Scanner is a built-in class in java used for read the input
from the user in java programming. The Scanner class is defined
inside the java.util package.
 The Scanner object breaks its input into tokens using a delimiter
pattern, the default delimiter is whitespace.

Slide 31
© Information Technology
Java Scanner Class Constructors
S.No
. Constructor with Description
1 Scanner(InputStream source) It creates a new Scanner that produces values read from the
specified input stream.
2 Scanner(InputStream source, String charsetName) It creates a new Scanner that
produces values read from the specified input stream.
3 Scanner(File source) It creates a new Scanner that produces values scanned from the
specified file.
4 Scanner(File source, String charsetName) It creates a new Scanner that produces values
scanned from the specified file.
5 Scanner(String source) It creates a new Scanner that produces values scanned from the
specified string.
6 Scanner(Readable source) It creates a new Scanner that produces values scanned from the
specified source.
7 Scanner(ReadableByteChannel source) It creates a new Scanner that produces values
scanned from the specified channel.
8 Scanner(ReadableByteChannel source, String charsetName) It creates a new Scanner
that produces values scanned from the specified channel. Slide 32
© Information Technology
Java Scanner Class Methods
S.N
o. Methods with Description
1 String next() It reads the next complete token from the invoking scanner.
2 String next(Pattern pattern) It reads the next token if it matches the specified pattern.
3 String next(String pattern) It reads the next token if it matches the pattern constructed from
the specified string.
4 boolean nextBoolean() It reads a boolean value from the user.
5 byte nextByte() It reads a byte value from the user.
6 double nextDouble() It reads a double value from the user.
7 float nextFloat() It reads a floating-point value from the user.
8 int nextInt() It reads an integer value from the user.
9 long nextLong() It reads a long value from the user.
10 short nextShort() It reads a short value from the user.
11 String nextLine() It reads a string value from the user.
12 boolean hasNext() It returns true if the invoking scanner has another token in its input.
13 void close() It closes the invoking scanner.

Slide 33
© Information Technology
Java Scanner Class Methods
import java.util.Scanner;
public class ScannerClassExample {
public static void mian(String[] args) {
Scanner read = new Scanner(System.in); // Input stream is used
System.out.print("Enter any name: ");
String name = read.next();
System.out.print("Enter your age in years: ");
int age = read.nextInt();
System.out.print("Enter your salary: ");
double salary = read.nextDouble();
System.out.print("Enter any message: ");
String msg = read.nextLine();
// the output of Entered values
System.out.println("\n------------------------------------------");
System.out.println("Hello, " + name);
System.out.println("You are " + age + " years old.");
System.out.println("You are earning Rs." + salary + " per month.");
System.out.println("Words from " + name + " - " + msg);
}}
Slide 34
© Information Technology

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy