Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Chapter 3
1. Chapter 2 The inside of objects and classes
By
Sirage Zeynu (M.Tech)
School of Computing
2. 13-04-2021 class and object 2
Outline of this chapter
1. member methods and their components
2. instantiation and initializing class objects
3. constructors
1. default and parameterized
2. overloaded constructors
4. methods
5. access specifiers
6. accessors and mutators
7. calling and returning methods
8. static and instance members
3. 13-04-2021 class and object 3
What is class ?
• A class is a blueprint from which individual objects are
created.
A class can be defined as a template/blueprint that describes
the behaviour/state that the object of its type support.
• a class is a template for an object, and an object is an instance
of a class. Because an object is an instance of a class, you will
often see the two words, object and instance, used
interchangeably.
Class Fundamentals
4. 13-04-2021 class and object 4
What is class ?
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 initialized when
the class is instantiated. Instance variables can be accessed from
inside any method, constructor or blocks of that particular class.
Class variables: Class variables are variables declared within a
class, outside any method, with the static keyword.
Class Fundamentals
5. 13-04-2021 class and object 5
what are objects?
If we consider the real-world, we can find many objects around
us, cars, dogs, humans, etc. All these objects have a state and a
behaviour.
If we consider a dog, then its state is - name, breed, color, and
the behaviour is - barking, wagging the tail, running.
If you compare the software object with a real-world object, they
have very similar characteristics.
Software objects also have a state and a behaviour. A software
object's state is stored in fields and behaviour is shown via
methods.
So in software development, methods operate on the internal state
of an object and the object-to-object communication is done via
methods.
6. 13-04-2021 class and object 6
The General Form of a class
To create a class, a source file with the class keyword in it followed by a
legal identifier and a pair of curly braces for the body is required. The
general form of a class definition is shown here:
class ClassName {
type instance-variable1;
type instance –variable2;
type instance-variableN;
type methodName ( Parameter-list )
{
// body of the method
}
}
Collectively, the
methods and variables
defined within a class
are called members of
the class.
7. 13-04-2021 class and object 7
Example of sample class
// Class declaration with a method
public class Dog {
String breed; //instance variable
String color; //instance variable
int age; //instance variable
void hungry()
{
// body of the method
}
void sleeping()
{
// body of the method
}
void barking()
{
// body of the method
}
8. 13-04-2021 class and object 8
new is a Java keyword. It creates a Java object and allocates
memory for it on the heap. new is also used for array creation, as
arrays are also objects.
Syntax:
JavaType variable = new JavaObject();
className object= new className();
If you create an instance of a class, you are creating an object that
contains its own copy of each instance variable defined by the
class.
The New Keyword
9. 13-04-2021 class and object 9
Example of the use new oprator
// A program that uses the Box class
public class Box {
double width;
double height;
double depth;
}
class BoxVolum {
public static void main(String[] args){
Box mybox = new Box();
double vol;
mybox.width = 20;
mybox.height = 30;
mybox.depth = 10;
vol = mybox.width * mybox.height * mybox.depth;
System.out.println("Volume is " + vol);
}
}
10. 13-04-2021 class and object 10
Declaring Objects
A typical Java program creates many objects, which as you
know, interact by invoking methods.
Through these object interactions, a program can carry out
various tasks, such as implementing a GUI, running an
animation, or sending and receiving information over a
network.
Once an object has completed the work for which it was
created, its resources are recycled for use by other objects.
The general declaration of object
JavaType variable = new JavaObject();
className object= new className();
11. 13-04-2021 class and object 11
obtaining objects of a class is a two-step process .
First , you must declare a variable of the class type . This
variable does not define an object. Instead, it is simply a
variable that can refer to an object.
Second , you must acquire an actual, physical copy of the
object and assign it to that variable. You can do this using a
new operator . The new operator dynamically allocates ( that is,
allocates at run time) memory for an object and returns a
reference to it. This reference is, more or less, the address in
memory of the object allocated by new.
Example Box mybox = new Box ( ) ;
12. 13-04-2021 class and object 12
Assigning Object Reference Variables
Object reference variables act differently than you might expect when an
assignment take place.
For example, what do you think the following fragment does
Box b1 = new Box( );
Box b2 = b1;
You might think that b2 is being assigned a reference to a copy of the
object referred to by b1. That is , you might think that b1 and b2 refer to
separate and distinct objects. However, this would be wrong. Instead , after
this fragment executes, b1 and b2 will both refer to the same object. The
assignment of b1 and b2 did not allocate any memory or copy any part of
the original object . It simply makes b2 refer to the same object as does b1.
Thus, any changes made to the object through b2 will affect the object to
which b1 is referring, since they are the same object.
13. 13-04-2021 class and object 13
Methods
Methods are functions that operate on instances of classes in
which they are defined.
Objects can communicate with each other using methods and
can call methods in other classes.
Just as there are class and instance variables, there are class
and instance methods .
Instance methods apply and operate on an instance of the
class while class methods operate on the class .
14. 13-04-2021 class and object 14
Defining Methods
Method definition has four parts .
They are , name of the method, type of object or primitive type
the method returns, a list of parameters and body of the method.
Java permits different methods to have the same name as long as
the argument list is different.
Returntype methodname ( type1 arg1 , type2 arg2 ) {
// Body of the methods
}
The returntype is the primitive type or class of the value this
method returns .
It should be void if the method does not return a value at all .
The parameters become local variables in the body of the method
whose values are passed when the method is called
15. 13-04-2021 class and object 15
Modifiers—such as public, private, and others
The return type
The method name
The parameter list in parenthesis—a comma-delimited list of input parameters,
preceded by their data types. If there are no parameters, you must use empty
parentheses.
An exception list—to be discussed later.
The method body, enclosed between braces—the method's code, including the
declaration of local variables, goes here.
Here is an example of a typical method declaration:
public double calculateAnswer(double wingSpan, int numberOfEngines, double length, double
grossTons) {
//do the calculation here}
More generally, method declarations have
17. 13-04-2021 class and object 17
Although a method name can be any legal identifier, code conventions
restrict method names.
By convention, method names should be a verb in lowercase or a multi-
word name that begins with a verb in lowercase, followed by adjectives,
nouns, etc. In multi-word names, the first letter of each of the second and
following words should be capitalized.
Here are some examples:
run runFast
getBackground getFinalData
compareTo setX
isEmpty getName
Naming a Method
18. 13-04-2021 class and object 18
Calling methods
Calling method is similar to calling or referring to an instance
variable .
The methods are accessed using the dot notation .
The object whose method is called is on the left of the dot,
while the name of the method and its arguments are on the
right .
Obj.methodName ( param1, param2,paramN )
19. 13-04-2021 class and object 19
Class Methods
Class methods, like class variables, are available to instance of the class
and can be made available to other classes Methods that operate on a
particular object should be defined as instance methods.
Methods that provide some general utility but do not directly. affect an
instance of the class are declared as class methods.
Class method is defined as given below :
static returntype methodname ( type1 arg1 , type2 arg2, .. )
{
// Body of the method
}
The static keyword indicates that it is a class method and can be accessed
without creating a object .
20. 13-04-2021 class and object 20
Parameters refers to the list of variables in a method
declaration.
Arguments are the actual values that are passed in when the
method is invoked.
When you invoke a method, the arguments used must match the
declaration's parameters in type and order.
The objects that are passed to the body of the method are passed
by reference and the basic types are passed by value
Passing Argument to methods
23. 13-04-2021 class and object 23
A constructor method is a special kind of method that
determines how an object is initialized when created.
They have the same name as the class and do not have any
return type.
Constructor declarations look like method declaration except
that they use the name of the class and have no return type.
When the keyword new is used to create an instance of a class,
Java allocates memory for the object, initializes the instance
variables and calls the constructor methods.
Constructors can also be overloaded.
Constructor
26. 13-04-2021 class and object 26
In Java it is possible to define two or more methods within the
same class that share the same name, as long as their parameter
declarations are different.
The methods are said to be overloaded , and the process is referred
to as method overloading.
Method Overloading is one of the ways that Java implements
polymorphism.
While overloaded methods may have different return types, the
return type alone is insufficient to distinguish two versions of a
method . When Java encounters a call to an overloaded method,
it simply executes the version of the method whose parameters
match the arguments used in the call.
Overloading Method
29. 13-04-2021 class and object 29
Constructors can also take varying numbers and types of
parameters.
This enables creation of objects with the properties required.
Overloading Constructors
31. 13-04-2021 class and object 31
Access control is controlling visibility of a variable or method . When a method
or variable is visible to another class, its methods can references the method or
variable.
Java's access specifiers are
public,
private,
protected
default
A public class member can be accessed by any other code.
A private class member can only be accessed within its class.
A default access class member has no access specifiers. A class's default features
are accessible to any class in the same package.
A protected feature of a class is available to all classes in the same package(like
a default) and to its subclasses. protected applies only when inheritance is
involved.
Java Access Control
32. 13-04-2021 class and object 32
class A{
private int j; // private to A
}
class B extends A {
int total;
void sum() {
total = j; // ERROR, j is not accessible here
} }
33. 13-04-2021 class and object 33
The following table shows the access matrix for Java. Yes means
accessible, no means not accessible.
34. 13-04-2021 class and object 34
static keyword always fixed the memory that means that will be located
only once in the program
When a member is declared static, it can be accessed before any objects
of its class are created , and without reference to any object you can
declare both methods and variables to be static.
The most common example of a static member is main( ). main( ) is
declared as static because it must be called before any objects exist.
where as final keyword always fixed the value that means it makes
variable values constant.
Note: As for as real time statement there concern every final variable
should be declared the static but there is no compulsion that every static
variable declared as final.
Static methods and Final variables Static methods
35. 13-04-2021 class and object 35
They can only call other static methods.
They must only access static data.
They cannot refer to this or super in any way(this, super we
will see later).
The static variable can be used to refer to the common
property of all objects.
for example, the company name of employees, college name
of students, etc.
The static variable gets memory only once in the class area at
the time of class loading.
Methods declared as static have several restrictions:
36. 13-04-2021 class and object 36
A static member that can be used by itself, without reference
to a specific instance.
Syntax
Here shows how to declare static method and static variable.
static int intValue; // static variable
static void aStaticMethod() //static method
{ }
38. 13-04-2021 class and object 38
A variable can be declared as final. Doing so prevents its contents
from being modified. This means that you initialize a final variable
when it is declared (in this usage, final is similar to const in C /
C++)
A final variable cannot be modified. You must initialize a final
variable when it is declared. A final variable is essentially a
constant.
. For example
final int FILE_NEW =1 ;
final int FILE_OPEN =2;
final int FILE_SAVE = 3;
Final Key Word
39. 13-04-2021 class and object 39
public class FinalMethod {
final void meth() {
System.out.println("This is a final method.");
}
}
class B extends FinalMethod {
void meth() { // ERROR! Can't override.
System.out.println("Illegal!");
}
}
40. 13-04-2021 class and object 40
A class usually provides methods to indirectly access and
modify the private data values
An accessor method returns the current value of a variable
A mutator method changes the value of a variable
The names of accessor and mutator methods take the form
getX and setX, respectively, where X is the name of the value
They are sometimes called “getters” and “setters”
Accessors and Mutators
41. 13-04-2021 class and object 41
The use of mutators gives the class designer the ability to
restrict a client’s options to modify an object’s state
A mutator is often designed so that the values of variables can
be set only within particular limits
42. 13-04-2021 class and object 42
Getters, or accessors, are methods that provide access
to an object's instance variables. In essence, we are
providing a layer of indirection. Simple classes often
have getters that return the associated instance variable
and nothing more.
43. 13-04-2021 class and object 43
public String getTitle(){
return title;
}
public String getAuthor(){
return author;
}
public int getRating(){
return rating;
}
Example Accessors mutators
public void setTitle(String title){
this.title = title;
}
public void setAuthor(String
author){
this.author = author;
}
public void setRating(int rating){
this.rating = rating;
}
The class Area has two instance variables, len and bre, which are initialized when an object is created. The calc method, which does not return any value , is defined in line 5.
This method calculates the area and displays it.
In the main method, an instance of the class , Area is created. The calcu method of the class , which calculates and displays the area, is called in line 10
Class methods can be used anywhere regardless of whether an instance of the class exists or not .
The class methods , unlike instance method, are not allowed to use instance variables, as these methods do not operate on an object .
The results in the change in original value of the object if the value is modified in the method
The output appears as shown :
The square of 15 is 225 .
The calcu method, which takes an integer as argument is defined in line 2. This method calculates the square of the parameter passed and display it . In the main() method an
object of this class is created . Then , calcu method is invoked with an argument 15. The calcu method calculates the square of the argument passed and displays it.
A constructor – has the same name as the class it constructs
has no return type (not even void)
• If the class implementer does not define any constructors, the Java compiler automatically creates a constructor that has no parameters.
• Constructors may be (and often are) overloaded.
• Itʼs good programming practice to always implement a constructor with no parameters.
If you have never used a language that allows the overloading of methods, then the concept may seem
strange at first . But as you will see , method overloading is one of Java’s most exciting and useful features.
As you can see, test() is overloaded four times. The first version takes no parameters, the second takes one integer parameter, the third takes two integer parameters, and the fourth
takes one double parameter. The fact that the fourth version of test() also returns a value is of no consequence relative to overloading, since return types do not play a role in overload
resolution.
public:
o When a member of a class is specified by the public specifier, then that member can be accessed by any other code.
o The public modifier makes a method or variable completely available to all classes.
o Also when the class is defined as public, it can be accessed by any other class.
private:
o To hide a method or variable from other classes, private modifier is used.
o A private variable can be used by methods in it’s own class but not by objects of any other class.
o Neither private variables nor private methods are inherited by subclass.
o The only place these variables and methods can be seen is from within their own class.
protected:
o protected applies only when inheritance is involved.
o If you want to allow an element to be seen outside your current package, but only to classes that are inherited from your class directly, then declare that element as protected.
default:
o We have seen that when no access control modifier is specified, it is called as default access.
o Classes written like this are not accessible in other package.
o Any variable declared without a modifier can be read or changed by any other class in the same package.
o Any method declared the same way can be called by any other class in the same package.
o When a member does not have an explicit access specification,
o it is visible to subclasses as well as to other classes in the same package.
Default access modifier means we do not explicitly declare an access modifier for a class, field, method, etc.
A variable or method declared without any access control modifier is available to any other class in the same package. The fields in an interface are implicitly public static final and the methods in an interface are by default public.
Example
Variables and methods can be declared without any modifiers, as in the following examples −
String version = "1.5.1";
boolean processOrder() {
return true; }
Normally, if you want to access a class member in Java, you must first create an instance of the class. But, there will be cases when you have to define a class member that will be used independently without creating an instance of that class.
However, in Java it is possible to create a class members (variables and methods) that can be accessed and invoked without creating an instance of the class. In order to to create such a member, you have to use static keyword while declaring a class member.
Static variable
If any variable we declared as static is known as static variable.
Static variable is used for fulfill the common requirement. For Example company name of employees,college name of students etc. Name of the college is common for all students.
The static variable allocate memory only once in class area at the time of class loading.
Advantage of static variable
Using static variable we make our program memory efficient (i.e it saves memory).
When and why we use static variable
Suppose we want to store record of all employee of any company, in this case employee id is unique for every employee but company name is common for all. When we create a static variable as a company name then only once memory is allocated otherwise it allocate a memory space each time for every employee.
Restrictions
Methods declared as static have several restrictions:
They can only call other static methods.
They must only access static data.
They cannot refer to this or super in any way.
All instances of the class share the same static variable. You can declare a static block to initialize your static variables. The static block gets only called once when the class is first loaded.
Subsequent parts of your program can now use FILE_OPEN , etc., as if they were constants, without fear that a value has been changed.
It is a common coding convention to choose all uppercase identifiers for final variables. Variables declared as final do not occupy memory on a per-instance basis. Thus, a final
variable is essentially a constant.
The keyword final can also be applied to methods, but its meaning is substantially different than when it is applied to variables.
A static constant is used to symbolically represent a constant value.
• In Java, constants derive from regular variables, by “finalizing” them – The declaration for a static defined constant must include the modifier final, which indicates that its value cannot be changed. public static final float PI = 3.142; (The modifier final is also overloaded, and means other things in other contexts, as we shall see later.)
• Static constants belong to the class as a whole, not to each object, so there is only one copy of a static constant
• When referring to such a defined constant outside its class, use the name of its class in place of a calling object. float radius = MyClass.PI * radius * radius;
Getters, or accessors, are methods that provide access to an object's instance variables. In essence, we are providing a layer of indirection. Simple classes often have getters that return the associated instance variable and nothing more.
Setters, or mutators, are methods that provider the caller with an opportunity to update the value of a particular instance variable. Similar to getters, setters are often named by prefixing the corresponding instance variable with "set".
Accessor method allow an outside class to read instance variable and often start with get word
Mutator method allow an outside class to write instance variable and often can be start set
Instance variables should be declare using the key word privet
package ch2;
import java.util.*;
public class Students {
private int rollNumber;
private String name;
private int marks1;
private int marks2;
private int marks3;
public void setName(String s) {
name = s;
}
public String getName() {
return name;
}
public void setRollMumber(int r) {
if (r > 0) {
rollNumber = r;
} else {
rollNumber = 1;
} }
public int getRollNumber() {
return rollNumber;
}
public void setMarks1(int m) {
if (m >= 0 && m <= 100) {
marks1 = m;
} else {
marks1 = 0;
}
}
public int getMarks1() {
return marks1;
}
public void setMarks2(int m) {
if ((m >= 0) && (m <= 100)) {
marks2 = m;
} else {
marks2 = 0;
}
}
public int getMarks2() {
return marks2;
}
public void setMarks3(int m) {
if ((m >= 0) && m <= 100) {
marks3 = m;
} else {
marks3 = 0;
}
}
public int getMarks3() {
return marks3;
}
public double getAverage() {
return (marks1+ marks2 + marks3) / 3;
}
public void printDetails() {
System.out.println("Roll Number: " + rollNumber);
System.out.println("Name: " + name);
System.out.println("Marks in first subject: " + marks1);
System.out.println("Marks in second subject: " + marks2);
System.out.println("Marks in second subject: " + marks3);
System.out.println("Average: " + getAverage());
}
}
class StudentTest {
public static void main(String[] args) {
Students student = new Students();
Scanner scanner = new Scanner(System.in);
System.out.print("Enter Name: ");
String name = scanner.nextLine();
student.setName(name);
System.out.print("Enter roll number: ");
int rollNumber = scanner.nextInt();
student.setRollMumber(rollNumber);
System.out.print("Enter marks1: ");
int marks1 = scanner.nextInt();
student.setMarks1(marks1);
System.out.print("Enter marks2: ");
int marks2 = scanner.nextInt();
student.setMarks2(marks2);
System.out.print("Enter marks3: ");
int marks3 = scanner.nextInt();
student.setMarks3(marks3);
System.out.println();
System.out.println("Printing details using printDetails() method: =");
student.printDetails();
System.out.println();
System.out.println("Printing details without using printDetails() method:");
System.out.println("Name: " + student.getName());
System.out.println("Roll Number: " + student.getRollNumber());
System.out.println("Marks1: " + student.getMarks1());
System.out.println("Marks2: " + student.getMarks2());
System.out.println("Marks3: " + student.getMarks3());
System.out.println("Average: " + student.getAverage());
}}