Вы находитесь на странице: 1из 62

Class, Objects and Methods

Objectives
• Define object‐oriented programming and basic concepts
• Define objects and classes
• Define instance variable and method
• Create classes
• Declare attributes and methods for the classes
• Use this reference to access instance data
• Create and call overloaded methods
• Import and create packages
• Use access modifiers to control access to class members
Object‐oriented programming
• is a type of computer programming based on the premise that all
programs are essentially computer‐based simulations of real‐world
objects or abstract concepts.
• It emphasizes state, behavior and interaction of objects. It provides
the benefits of faster development, increased quality, easier
maintenance, enhanced modifiability and increase software reuse.
Software Reusability
• Java provides the benefits of Software reusability.
• Software programmers can use a class over and over again to create
many objects. Since, are self‐contained units, you can copy an object
from one program and plug it into another program.
• Reusing objects not only simplifies creating new programs, but also
helps create new programs faster because you can reuse objects that
already work.
Object
• An object as the basic unit of OOP is a simulation of objects in
real‐world scenarios.
• It can be characterized through their data (properties/attributes)
variables describing the essential characteristics of the object. Set of
methods (behavior) that describes how an object behaves.
• In Java it is defined as instance variable and instance method. An
object is an instance of a class.
• It is created every time you instantiate a class using the new keyword.
Class
• Class is central to all Java programming. A class isn’t real. It can be
thought of as a template, a prototype or a blueprint of an object.
Class is detailed definition of an object.
• Things defined inside a class known as class member. Members can
be fields (properties or attributes) that can hold the definition of the
object or a method that while methods specify the operations
Methods
• Is a block of statements that has a name and can be executed by
calling (also called invoking) it from some other place in your program
to perform some specific function. Parameters are also called
function arguments. A method can require one or more parameters
that represent additional information it needs to perform its task.
Method call
General Definition:
• callMethods(); //with no argument
• callMethod(argument); //with one argument
• callMethod(argument1, argument2); //arguments separated by
comma
• firstMethod(secondMethod); //method used as
argument
• returnValue=callMethod(argument); //method return a value
Calling Methods
• Calling a method in Java is transferring the execution of the program
to another method. Once the method has finished execution, it may
return a value back to the calling method.
• To call an instance method:
nameOfObject.nameOfMethod( parameters );

• To call a static method:


Classname.staticMethodName(parameter);
Passing Variables to Methods
• Java passes a variable to a method via a parameter. There are two
ways how we passed data to methods. We have the Pass‐by‐value
and the Pass‐by‐reference.
• Pass‐by‐value
• Pass‐by‐reference
Pass‐by‐value
• The method itself receives a copy of the variable’s value, not the
variable itself. If a method changes the value it receives as a
parameter, that change is not reflected in the original variable that
was passed to the method.
Pass‐by‐reference
• The reference to an object is passed to the calling method. This
means that, the method makes a copy of the reference of the variable
passed to the method. If a method changes the value it receives as a
parameter, that change is reflected in the original variable that was
passed to the method.
Command‐line Arguments
• Java application can accept arguments from the command line.
Command‐line parameters are often used to pass file information,
pathnames to console programs. It allows the user to interact and
alters the operations of an application. User enters command‐line
arguments after the name of the class to run. These arguments are
separated by white spaces.
Consider the construction:
public static void main(String[] args)

• The args parameter of the main method is an array of strings that lets you
access any command‐line parameters that are specified by the user when
the program was ran. The number of arguments passed in from the
command line is obtained by accessing the array’s length attribute.

int numOfArgs=args.length;
• Before using command‐line arguments, always check if the number of
arguments before accessing the array elements so that there will be no
exception generated.
Casting, Converting and Comparing Objects
• Conversion of data from one type to another type is known as type
casting. In java, the implicit type casting where in the value of one
data is automatically changed to another data type. Sometimes it can
generate unexpected errors and you run the risk of losing
information. To avoid implicit type coercion, Java provides explicit
conversion through the use of cast operator and it is done
automatically
Converting and Casting between Primitive
Data Types
• Casting between primitive types enables you to convert the value of
one data from one type to another primitive type. In general casting
is not applicable to Boolean data type for it evaluates two conditions.
short s = 5;
int i = s;
• Consider the type casting example above, we assign a short to an
integer. The compiler can handle this casting because integers are
bigger than shorts. The data is then implicitly casted to data type int.
form for explicit casting:
(dataTypeName) expression
• dataTypeName, is the name of the data type you're converting to
expression, is an expression that results in the value of the source
type.
• First, the expression is evaluated. Its value is then converted to a
value of the type specified by dataTypeName.
int i = 5;
short s = (short)i;
Converting and Casting between Objects
• Instances of classes also can be cast into instances of other classes
and inheritance has something to do with conversion and casting of
objects. That is the source and destination classes must be related by
inheritance; one class must be a subclass of the other.
• For example we will have the superclass Shape with a number of
subclasses like square, rectangle and circle. These classes can be
treated as types; you can create instances and store their references
in variables.
Shape shape = new Circle();
• A variable can refer to an object of its own type, or any of its
subclasses. The Circle object returned by the new operator is
implicitly cast to its superclass type before the assignment is done. It’s
because a subclass contains everything that its superclass has, this
indicates that a superclass is "smaller" than its subclass, since it has
less functionality.
• Since a subclass has everything its superclass has. All subclasses can
fulfill the contract of a superclass, since they invariably have more
functionality than their superclass. You must cast them explicitly. You
won't lose any information in the cast, but you gain all the methods
and variables that the subclass defines.
To cast an object to another class, you use the
same operation as for primitive types:
To cast,
(classname)object

where,
classname, is the name of the destination class
object, is a reference to the source object.

Example
Circle circle=new Shape();
Comparing Objects
• In java, we used the equals () method in comparing objects value and
the equality and inequality operators in comparing object reference.
If you need to compare primitive types, you can use == but to
compare strings and any other reference type use equals method
instead.
• The operators == and != compare two values to see if they refer to
the same object not to the value of the object.
For example we take an object with identical
values
public class ComparedObject
{
public static void main(String args[ ])
{
String stud1, stud2;
stud1 = “Spanky";
stud2 = stud1;
System.out.println("Student A: " + stud1);
System.out.println("Student B: " + stud2);
System.out.println("same object: " + (stud1 == stud2));
}
}
Output:
Student A: Spanky
Student B: Spanky
same object: true
public class ComparedObject2
{
public static void main(String args[ ])
{
String stud1, stud2;
stud1 = " Spanky";
stud2 = stud1;
stud2 = new String(stud1);
System.out.println("Student A: " + stud1);
System.out.println("Student B: " + stud2);
//compares values
System.out.println("same object: " + (stud1 == stud2));
//compares values not reference
System.out.println("identical content: " + stud1.equals(stud2));
}
}
References now point to different objects, thus the == operator returns
false while the equals() methods return true because stud1 and stud2
still shares the same value.

Ouput:
Student A: Spanky
Student B: Spanky
same object: false
identical content: true
Laboratory Exercise:
Based on the sample output below: Write the program source code
that display the result “false” in the same object.

Sample Output:
Student A: Spanky
Student B: Spanky
same object: true
identical content: true
Class Fundamentals
Defining your own classes
All classes must be defined by a class declaration that provides the name for
the class and the body of the class. The main reason you write class
declarations is so that other classes can create objects from the class.

Basic class declaration:


public classname
{
Classbody
// <attributedeclaration>,<constructordeclaration>,<methoddeclaration>
}

where in the keyword public indicates that the class is available to


public(optional).
classname
• is an identifier that provides a name for your class. You are allowed to
use any identifier to name a class, still consider an appropriate name.
Begin the class name with a capital letter, whenever possible; use
nouns for your class names. Avoid using the name of a Java API class
and the filename of your class should have the same name as your
public class name.
class body
• class body of a class is everything that goes within the braces at the
end of the class declaration. The class body contains fields, methods
and constructors. The fields, methods, classes, and interfaces place
inside the class body is considered as members of the class.
Example:
public class studentProfile {
some code here…
}
Declaring Attributes
As we work with attributes we can declare it using this syntax:

(modifier) (type) (name) = (default_value);


Instance Variable
• Declare all your instance variables on the top of the class declaration
outside of any of the class’ methods. Like any other variables should
start with a small letter. Use an appropriate data type for each
variable you declare
Example of instance variable:
private String name;
private String address;
private int age;
private double grade;
Instance variables implemented inside the
class studentProfile;
public class studentProfile {
private String name;
private double grade;
private String address;
private int age;
}
Declare attribute as private:

Use the key word private to indicate it is a


private attribute.
private int age;
private String address;
Declaring attribute as final:
Use the key word final to indicate it is a final attribute.

public final int age;


private final int age;

Spell out final in capital letters is acceptable in java, but


remember the value of a final field can’t be changed once it
has been initialized. Use the keyword final to indicate that the
attribute is a final attribute.
Declaring attribute as static:
public final static age;
private final static age;

• These attribute are the same for all the objects of the same class and
it belong to the class as a whole. Use the keyword static to indicate
that the attribute is a static attribute. Remember that you can’t use
the static keyword within a class method. In other words, fields can
be static, but local variables can’t.
Declaring Methods
• As we work with methods we can declare it using this syntax:

(modifier) (returntype) (name) (parameter_list) {


declaration and statements
}

• Naming a method is the same as the rules for creating variable


names. The parameter list in the method declaration lets java know
what types of parameters a method should expect to receive and
provides names so that the statements in the method’s body can
access the parameters as local variables.
Example:
public class studentProfile{
private String name;
private double grade;
private String address;
private int age;
public void int getName(){
return name;
}
public void setName(int n){
// return type of the method should be same datatype as the data in the return
statement.
name = n;
}
}
Accessor and Mutator Methods
• In Java, we implement encapsulation, which is hiding the details of a
class inside the class while carefully controlling what aspects of the
class are exposed to the outside world. In general we avoid creating
public fields. Instead, declaring them in private but can selectively
grant access to the data those fields contain by adding special
methods called accessors and mutators to the class.
Accessor
• An accessor is a method that retrieves values of our class variables
(instance/static). Accessor method is named get<
NameOfInstanceVariable>. This is sometimes referred to as setter.

• Example:
public class studentProfile{
private String name;
private double grade;
private String address;
private int age;
public int getName(){
return name;
} }
Mutator
• A mutator is a method that can write or modify values of our class
variables (instance/static).
• Mutator method is named set< NameOfInstanceVariable>. We also called
this as getter.
• Example:
public class studentProfile{
private String name;
private double grade;
private String address;
private int age;
public setName(int n)
{
// return type of the method should be same dataType as the data in the return statement.
name = n;
}
}
Static Methods
• Static methods are associated with the class itself, not with any particular
object created from the class. You can’t access a non‐static method or field
from a static method because doesn’t have an instance of the class to use
to reference instance methods or fields. It is a declared with the static
keyword.
• Example:
public class studentProfile
{
private String name;
private static int count; // number of objects in memory
public static int getCount(){ // static method to get static count value
return count;
}
}
The this Reference
• In Java, this is a reserve word. It allows the object to have an access to
a reference of itself. Remember we can only use the this reference for
instance variables and not static or class variables.

• Syntax of this reference:


this.<nameoftheinstancevariable>

• The this keyword is usually used to qualify references to instance


variables of the current object.
The this Reference
• Example:
public void setName(int n)
{
this.name=name;
}

• This method will then assign the value of the parameter age to the
instance variable of the object studentProfile.
Overloading Methods
• One of the keys in building flexibility into your classes is using method
overloading. In java it allows us to create two methods with the same
name provided they function differently depending on the
parameters passed on them.
Constructors
• is a block of code that initialized the instance variable. It doesn’t have
a return type and must be the named same as the name of the class.
Constructor cannot be called directly; it can only be called by using
the new operator during class instantiation. Remember that a
constructor can throw exceptions if it encounters situations it can’t
recover from.
To declare a constructor, we write,

<modifier> <classname> (<parameter>) {


<statement>
}

Example:

public studentGrade(){
midterm=90;
finals=89;
Difference between method and constructor
• There is no return type given in a constructor signature (header). The
value is this object itself so there is no need to indicate a return value.
• There is no return statement in the body of the constructor.
• The first line of a constructor must either be a call on another
constructor in the same class (using this), or a call on the superclass
constructor (using super). If the first line is neither of these, the
compiler automatically inserts a call to the parameterless super class
constructor.
Default Constructors
• One reason for coding a constructor is to provide initial values for
class fields when you create the object. If you don’t specify a
constructor, java then an implicit default constructor is created and
that is the default constructor. Default constructor is the constructor
without any parameters. It doesn’t accept any parameters and it
doesn’t do anything, but it does allow your class to be instantiated.

<constructordeclaration> =<modifier> <classname> (<parameter>) {


<statement>
}
Calling Constructors
• Constructor calls can be chained. A constructor can call another
constructor of the same class by using the special keyword this() as a
method call. When using the this() constructor call, it must occur as
the first statement in a constructor. It can only be used in a
constructor definition. Lastly, you can’t create loops where
constructors call each other.
Packages
• In Java, you can group a bunch of classes into something called a
package. Package is grouping related classes and interfaces together
in a single unit. The Java API contains many packages.
Creating Packages 4 Easy Steps
• Define a public class. If the class is not public, it can be used only by
other classes in the same package.
• Choose a package name, and add a package statement to the source
code file for the reusable class definition.
• Compile the class so it is placed in the appropriate package directory
structure.
• Import the reusable class into a program, and use the class.
Access Modifiers
• An access modifier is implemented in order to have restrictions in
accessing some method, attribute or class. In Java, there are two
levels are class level access modifiers and member level access
modifiers.
Class level access modifiers (java classes only)
Only two access modifiers is allowed, public and no modifier
• If a class is public then it can be accessed from anywhere.
• If a class has no modifer then it CAN ONLY be accessed from same
package.
Member level access modifiers (java variables
and java methods)
All the four public, private, protected and default is allowed.
• default access (no modifier)‐ no keyword is use.
• public ‐ the same way as we used in class level.
• private ‐ members CAN ONLY access.
• protected ‐ CAN be accessed from ‘same package’ and a subclass
existing in any package can access.
Default Access
• Only classes in the same package can have access to the class'
variables and methods.
public class studentProfile
{
int name; //default access to instance variable
String getName(){ //default access to method
return name;
}
}
Public Access
• Declaring class in public, meaning other classes can have access of
these class members. Other objects can communicate with objects
created from your class.
public class studentProfile
{
int name; //default access to instance
variable
public String getName(){ //default access to method
return name;
}
}
Private Access
• Declaring class in private, meaning the class members are only
accessible by the class they are defined in. You can use private
attributes/methods within a class but not from other classes.

public class studentProfile


{
int name; //default access to instance
variable
private String getName(){ //default access to method
return name;
}
}
Protected Access
• The class members are accessible only to methods in that class and
the subclasses of the class.
public class studentProfile
{
int name; //default access to instance
variable
protected String getName(){ //default access to
method
return name;
}
}
End….

Вам также может понравиться