0% found this document useful (0 votes)
80 views

Chapter Three-I: Classes and Objects in Java

The document discusses object-oriented programming concepts in Java including classes, objects, class attributes, class methods, and visibility modifiers. It provides examples of defining classes like Student and Rectangle that have attributes to store data and methods to perform calculations. Objects are created from classes using the new keyword and can then access class attributes and methods using dot notation.

Uploaded by

Amsalu Fentie
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
80 views

Chapter Three-I: Classes and Objects in Java

The document discusses object-oriented programming concepts in Java including classes, objects, class attributes, class methods, and visibility modifiers. It provides examples of defining classes like Student and Rectangle that have attributes to store data and methods to perform calculations. Objects are created from classes using the new keyword and can then access class attributes and methods using dot notation.

Uploaded by

Amsalu Fentie
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 32

Object Oriented

Programming (OOP)

CHAPTER THREE-I

Classes and Objects


in Java

10/02/22 by: A.F 1


Classes
• Classes are “blueprints”for creating a group of objects.
A bird class to create bird objects
A car class to create car objects
A shoe class to create shoe objects
• The blueprint defines
The class’s state/attributes as variables
The class’s behavior as methods
• We’ve already seen, how to use classes and the objects
created from them...
Scanner input = newScanner(System.in);
• How to invoke their methods using the dot notation
int num = input.nextInt();
02/10/22 2
Cont…
• A class is a logical framework or blue print or template of
an object .
• A Java class uses variables to define data fields and methods
to define behaviors
• A class is a programmer defined data type for which access
to data is restricted to specific set of functions in that class.
• A class has a state (field) and behavior (method).
Fields: Say what a class is
Methods: Say what a class does

02/10/22 3
Example –class song

02/10/22 4
Example-class student
• An object which recorded information about a University
of Gondar student might record a first name, a last name
and an identification number.
• We would represent this as follows in Java.
class Student {
public String firstName;
public String lastName;
public String idNumber;
}

02/10/22 5
Example-class student

• This is a class definition.


• The identifier of the class being defined is Student.
• Objects of this class will have three fields;
firstName
 lastName
 idNumber
• The purpose of the Student class is to allow us to store
together these three related data items.
• It seems appropriate to store these three data items together
because they are the firstName, lastName and idNumber
respectively of one person.
02/10/22 6
Instance variable
• A variable that is created inside the class but outside the
method.
• Instance variable doesn't get memory at compile time.
• It gets memory at runtime when object(instance) is created.
• That is why, it is known as instance variable.
Local variables
• Variables that are declared in a method are called local
variables.
• They are called local because they can only be referenced
and used locally in the method in which they are declared

02/10/22 7
class variable
• A class variable or static variable is defined in a class, but
there is only one copy regardless of how many objects are
created from that class.
• It's common to define static final variables (constants) that
can be used by all methods, or by other classes.

02/10/22 8
Definition and declaration of a class:

Syntax:
class ClassName{
//member attributes (instance or class variables)
//member Methods
}

02/10/22 9
Definition and declaration of a class:
• A class definition defines the class blueprint.
• The behaviors/operations of a class are implemented
methods. Also known as member functions
• The state of the class is stored in its data members. Also
known as fields, attributes, or instance variables

Class Data Fields


• A class definition typically includes one or more fields
that declare data of various types.
• When the data field declaration does not assign an explicit
value to the data, default values will be used

02/10/22 10
Class methods
• Objects are sent messages which in turn call methods.
• Methods may be passed arguments and may return something
as well.
• Methods are available to all instances of the class.
• Like data members, methods are also referenced using the dot
operator.
• A class definition typically includes one or more methods,
which carry out some action with the data.
• Methods resemble the functions and subroutines in other
languages.
• A method will be called, or invoked, by code in some other
method.

02/10/22 11
Class methods
• The structure of a method includes a method signature and a
code body:

[access modifier] return type


method name (list of arguments)
{
statements, including local variable
declarations
}
• The first line shows a method signature consisting of access
modifier - determines what other classes and subclasses can
invoke this method.
02/10/22 12
cont…

return type - what primitive or class type value will return


from the invocation of the method.
If there is no value return, use void for the return type.
method name - follows the same identifier rules as for
data names.
Normally, a method name begins with a lower case letter.
list of arguments - the values passed to the method.
statements - the code to carry out the task for the
particular method.

13
Example
class Circle{
float r;
void showArea(){
float area = r*r*PI;
System.out.println(“The area is:” + area);
}
void showCircumference(){
float circum=2* PI*r;
System.out.println(“The circumference is:” +
circum);
}
...}
02/10/22 14
Objects
 An object is an instance of a class. It can be uniquely identified by its
name and defined state, represented by the values of its attributes in a
particular time.
 An object represents something with which we can interact in a
program.
 A class represents a concept, and an object represents the
embodiment of a class. A class is a blueprint for an object.
• An Object has two primary components:
• state – properties of the object
• behavior – operations the object can perform
EXAMPLE
object state behavior
dog breed, isHungry eat, bark
grade book grades mean, median
02/10/22
light on/off switch 15
Constructing Objects
• We use the new keyword to construct a new instance of an Object
• We can assign this instance to a variable with the same type of the
Object
• Note: classes define new datatypes !

LightSwitch ls = new LightSwitch();


• To access the field of an instance of an Object use instance.field
Creating an object from class
Creating an object is a two-step process.
1.Creating a reference variable
Syntax:
<class idn><ref. idn>; eg. Circle c1;
2. Setting the reference with the newly created object.
Syntax:
<ref. idn> = new <class idn>(…);
c1 = new Circle();
•The two steps can be done in a single statement
Circle c2 = new Circle();
•To access members of an object we use ‘.’ (dot) operator together
with the reference to an object.
Syntax:
<ref. idn>.<member>;
02/10/22 17
Example
 Consider the already defined class Circle and define another class
TestClass
class TestClass{
public static void main(String args[])
{
Circle c1 = new Circle();
c1.r = 2.3;
c1.showArea();
c1.showCircumference();
}
}
The new keyword is used to allocate memory at runtime.
02/10/22 18
Object creating example
class Student{

 int id;//data member (also instance variable)  

String name;//data member(also instance variable)  

   public static void main(String args[]){ 

   Student s=new Student();//creating object of Student   

 System.out.println(s.id);  //output=?

  System.out.println(s.name); //output=?

  } 

 } 
02/10/22 19
We can create multiple objects by one type only as we
do in case of primitives.
i.e like int x,y,z; in primitves
We can say Student s1,s2,s3;

02/10/22 20
Class activity 1
Create a rectangle class that calculate
the area of rectangle.
Create an object from the rectangle
class to access class members.
Create an insert method to insert width
and length of a rectangle.
Create calculateArea method to
compute the area of a rectangle
respectively.
02/10/22 21
class Rectangle{  
  int length;   
int width;    
void insert(int l,int w){  
  length=l;   
 width=w;  
 }   
    
02/10/22 22
void calculateArea(){
System.out.println(length*width);
}   
  public static void main(String args[]){  
 Rectangle r1=new Rectangle();    
Rectangle r2=new Rectangle();    
  r1.insert(11,5);  
  r2.insert(3,15);    
  r1.calculateArea();  
  r2.calculateArea();  }  }
02/10/22 23
Visibility Modifiers
 The following are common visibility modifiers
Public
Default
Private
Protected
You can use the public visibility modifier for classes,
methods, and data fields to denote that they can be
accessed from any other classes(even outside package).
• If no visibility modifier is used, then by default the
classes, methods, and data fields are accessible by any
class in the same package.
• Also called default modifier.

02/10/22 24
• The private modifier makes methods and data fields accessible only
from within its own class.
• It indicates that instance variables are accessible only to methods of
the class; this is known as data hiding
• The get and set methods are used to read and modify private properties.
• The private modifier restricts access to its defining class
• The default modifier restricts access to a package,
• The public modifier enables unrestricted access.
• If a class is not defined public, it can be accessed only within the same
package.
02/10/22 25
• protected : Often it is desirable to allow subclasses to
access data fields or methods defined in the superclass,
but not allow non subclasses to access these data fields
and methods.

• To do so, you can use the protected keyword.

• A protected data field or method in a superclass can be


accessed in its subclasses.(will see in the next chapter)

02/10/22 26
Summery on visibility modifiers
Accessible to: public protected Package private
(default)

Same Class Ye s Ye s Ye s Ye s

Class in package Ye s Ye s Ye s No

Subclass in Ye s Ye s No No
different package

Non-subclass Ye s No No No
different package
02/10/22 27
The static keyword
• The static keyword is used when a member variable of a class has to be
shared between all the instances of the class.
• All static variables and methods belong to the class and not to any
instance of the class
• When can we access static variable?
When a class is loaded by the virtual machine all the static variables
and methods are available for use.
Hence we don’t need to create any instance of the class for using the
static variables or methods.
Variables which don’t have static keyword in the definition are
implicitly non static.
02/10/22 28
Example
Class staticDemo{
public static int a = 100; // All instances of staticDemo have this variable as a common variable
public int b =2 ;
public static showA(){
System.out.println(“A is “+a); } }
public static void main(String args[]){
staticDemo.a = 35; // when we use the class name, the class is
loaded, direct access to a without any instance
staticDemo.b=22; // ERROR this is not valid for non static variable
staticDemo demo = new staticDemo();
demo.b = 200; // valid to set a value for a non static variable after
creating an instance.
staticDemo.showA(); //prints 35
}}
02/10/22 29
Static and Non-static
• We can access static variables without creating an instance of the
class
• As they are already available at class loading time, we can use them
in any of our non static methods.
• We cannot use non static methods and variables without creating an
instance of the class as they are bound to the instance of the class.
• They are initialized by the constructor when we create the object
using new operator.

02/10/22 30
final fields
• The keyword final means: once the value is set, it can never be
changed.

• Typically used for constants.

static final int BUFSIZE=100;


final double PI=3.14159;

31
Any ?
02/10/22 32

You might also like