SlideShare a Scribd company logo
Chapter 2 The inside of objects and classes
By
Sirage Zeynu (M.Tech)
School of Computing
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
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
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
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.
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.
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
}
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
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);
}
}
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();
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 ( ) ;
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-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 .
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
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
13-04-2021 class and object 16
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
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 )
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 .
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
13-04-2021 class and object 21
13-04-2021 class and object 22
Returning a Value
Out put
Volume is 3000.0
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
13-04-2021 class and object 24
13-04-2021 class and object 25
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
13-04-2021 class and object 27
13-04-2021 class and object 28
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
13-04-2021 class and object 30
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
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
} }
13-04-2021 class and object 33
The following table shows the access matrix for Java. Yes means
accessible, no means not accessible.
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
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:
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
{ }
13-04-2021 class and object 37
Example of static variable
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
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!");
}
}
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
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
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.
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;
}
13-04-2021 class and object 44
13-04-2021 class and object 45
13-04-2021 class and object 46
13-04-2021 class and object 47
13-04-2021 class and object 48
13-04-2021 class and object 49

More Related Content

What's hot

9. Input Output in java
9. Input Output in java9. Input Output in java
9. Input Output in java
Nilesh Dalvi
 
Interfaces in java
Interfaces in javaInterfaces in java
Interfaces in java
Abishek Purushothaman
 
C# classes objects
C#  classes objectsC#  classes objects
C# classes objects
Dr.Neeraj Kumar Pandey
 
Packages,static,this keyword in java
Packages,static,this keyword in javaPackages,static,this keyword in java
Packages,static,this keyword in java
Vishnu Suresh
 
Enumeration in Java Explained | Java Tutorial | Edureka
Enumeration in Java Explained | Java Tutorial | EdurekaEnumeration in Java Explained | Java Tutorial | Edureka
Enumeration in Java Explained | Java Tutorial | Edureka
Edureka!
 
ITFT-Constants, variables and data types in java
ITFT-Constants, variables and data types in javaITFT-Constants, variables and data types in java
ITFT-Constants, variables and data types in java
Atul Sehdev
 
Constructors and destructors
Constructors and destructorsConstructors and destructors
Constructors and destructors
Vineeta Garg
 
Switch Case in C Programming
Switch Case in C ProgrammingSwitch Case in C Programming
Switch Case in C Programming
Sonya Akter Rupa
 
Normal forms
Normal formsNormal forms
Normal forms
Samuel Igbanogu
 
Java oops PPT
Java oops PPTJava oops PPT
Java oops PPT
kishu0005
 
Database Concept - Normalization (1NF, 2NF, 3NF)
Database Concept - Normalization (1NF, 2NF, 3NF)Database Concept - Normalization (1NF, 2NF, 3NF)
Database Concept - Normalization (1NF, 2NF, 3NF)
Oum Saokosal
 
Polymorphism in C++
Polymorphism in C++Polymorphism in C++
Polymorphism in C++
Rabin BK
 
Java Tokens
Java  TokensJava  Tokens
Learn C# Programming - Decision Making & Loops
Learn C# Programming - Decision Making & LoopsLearn C# Programming - Decision Making & Loops
Learn C# Programming - Decision Making & Loops
Eng Teong Cheah
 
1z0-808-certification-questions-sample
1z0-808-certification-questions-sample1z0-808-certification-questions-sample
1z0-808-certification-questions-sample
java8certificationquestions
 
encapsulation, inheritance, overriding, overloading
encapsulation, inheritance, overriding, overloadingencapsulation, inheritance, overriding, overloading
encapsulation, inheritance, overriding, overloading
Shivam Singhal
 
Ppt on this and super keyword
Ppt on this and super keywordPpt on this and super keyword
Ppt on this and super keyword
tanu_jaswal
 
Interface in java ,multiple inheritance in java, interface implementation
Interface in java ,multiple inheritance in java, interface implementationInterface in java ,multiple inheritance in java, interface implementation
Interface in java ,multiple inheritance in java, interface implementation
HoneyChintal
 

What's hot (20)

9. Input Output in java
9. Input Output in java9. Input Output in java
9. Input Output in java
 
Interfaces in java
Interfaces in javaInterfaces in java
Interfaces in java
 
C# classes objects
C#  classes objectsC#  classes objects
C# classes objects
 
String, string builder, string buffer
String, string builder, string bufferString, string builder, string buffer
String, string builder, string buffer
 
Packages,static,this keyword in java
Packages,static,this keyword in javaPackages,static,this keyword in java
Packages,static,this keyword in java
 
Enumeration in Java Explained | Java Tutorial | Edureka
Enumeration in Java Explained | Java Tutorial | EdurekaEnumeration in Java Explained | Java Tutorial | Edureka
Enumeration in Java Explained | Java Tutorial | Edureka
 
ITFT-Constants, variables and data types in java
ITFT-Constants, variables and data types in javaITFT-Constants, variables and data types in java
ITFT-Constants, variables and data types in java
 
Constructors and destructors
Constructors and destructorsConstructors and destructors
Constructors and destructors
 
Switch Case in C Programming
Switch Case in C ProgrammingSwitch Case in C Programming
Switch Case in C Programming
 
Normal forms
Normal formsNormal forms
Normal forms
 
Java oops PPT
Java oops PPTJava oops PPT
Java oops PPT
 
Java interface
Java interfaceJava interface
Java interface
 
Database Concept - Normalization (1NF, 2NF, 3NF)
Database Concept - Normalization (1NF, 2NF, 3NF)Database Concept - Normalization (1NF, 2NF, 3NF)
Database Concept - Normalization (1NF, 2NF, 3NF)
 
Polymorphism in C++
Polymorphism in C++Polymorphism in C++
Polymorphism in C++
 
Java Tokens
Java  TokensJava  Tokens
Java Tokens
 
Learn C# Programming - Decision Making & Loops
Learn C# Programming - Decision Making & LoopsLearn C# Programming - Decision Making & Loops
Learn C# Programming - Decision Making & Loops
 
1z0-808-certification-questions-sample
1z0-808-certification-questions-sample1z0-808-certification-questions-sample
1z0-808-certification-questions-sample
 
encapsulation, inheritance, overriding, overloading
encapsulation, inheritance, overriding, overloadingencapsulation, inheritance, overriding, overloading
encapsulation, inheritance, overriding, overloading
 
Ppt on this and super keyword
Ppt on this and super keywordPpt on this and super keyword
Ppt on this and super keyword
 
Interface in java ,multiple inheritance in java, interface implementation
Interface in java ,multiple inheritance in java, interface implementationInterface in java ,multiple inheritance in java, interface implementation
Interface in java ,multiple inheritance in java, interface implementation
 

Similar to Chapter 3

Chapter 7 java
Chapter 7 javaChapter 7 java
Chapter 7 java
Ahmad sohail Kakar
 
packages and interfaces
packages and interfacespackages and interfaces
packages and interfaces
madhavi patil
 
Lecture 5
Lecture 5Lecture 5
Lecture 5
talha ijaz
 
Oops
OopsOops
ObjectOrientedSystems.ppt
ObjectOrientedSystems.pptObjectOrientedSystems.ppt
ObjectOrientedSystems.ppt
ChishaleFriday
 
3_ObjectOrientedSystems.pptx
3_ObjectOrientedSystems.pptx3_ObjectOrientedSystems.pptx
3_ObjectOrientedSystems.pptx
RokaKaram
 
Ch-2ppt.pptx
Ch-2ppt.pptxCh-2ppt.pptx
Ch-2ppt.pptx
ssuser8347a1
 
Delphi qa
Delphi qaDelphi qa
Delphi qa
sandy14234
 
Use Classes with Object-Oriented Programming in C++.ppt
Use Classes with Object-Oriented Programming in C++.pptUse Classes with Object-Oriented Programming in C++.ppt
Use Classes with Object-Oriented Programming in C++.ppt
manishchoudhary91861
 
Classes,object and methods java
Classes,object and methods javaClasses,object and methods java
Classes,object and methods java
Padma Kannan
 
classandobjectunit2-150824133722-lva1-app6891.ppt
classandobjectunit2-150824133722-lva1-app6891.pptclassandobjectunit2-150824133722-lva1-app6891.ppt
classandobjectunit2-150824133722-lva1-app6891.ppt
manomkpsg
 
Application package
Application packageApplication package
Application packageJAYAARC
 
Object & classes
Object & classes Object & classes
Object & classes
Paresh Parmar
 
Object Oriented PHP - PART-1
Object Oriented PHP - PART-1Object Oriented PHP - PART-1
Object Oriented PHP - PART-1
Jalpesh Vasa
 
OOSD1-unit1_1_16_09.pptx
OOSD1-unit1_1_16_09.pptxOOSD1-unit1_1_16_09.pptx
OOSD1-unit1_1_16_09.pptx
ShobhitSrivastava15887
 

Similar to Chapter 3 (20)

Chapter 7 java
Chapter 7 javaChapter 7 java
Chapter 7 java
 
packages and interfaces
packages and interfacespackages and interfaces
packages and interfaces
 
Lecture 5
Lecture 5Lecture 5
Lecture 5
 
Oops
OopsOops
Oops
 
ObjectOrientedSystems.ppt
ObjectOrientedSystems.pptObjectOrientedSystems.ppt
ObjectOrientedSystems.ppt
 
3_ObjectOrientedSystems.pptx
3_ObjectOrientedSystems.pptx3_ObjectOrientedSystems.pptx
3_ObjectOrientedSystems.pptx
 
Ch-2ppt.pptx
Ch-2ppt.pptxCh-2ppt.pptx
Ch-2ppt.pptx
 
Lecture 4
Lecture 4Lecture 4
Lecture 4
 
Delphi qa
Delphi qaDelphi qa
Delphi qa
 
Use Classes with Object-Oriented Programming in C++.ppt
Use Classes with Object-Oriented Programming in C++.pptUse Classes with Object-Oriented Programming in C++.ppt
Use Classes with Object-Oriented Programming in C++.ppt
 
Classes,object and methods java
Classes,object and methods javaClasses,object and methods java
Classes,object and methods java
 
My c++
My c++My c++
My c++
 
Oops
OopsOops
Oops
 
classandobjectunit2-150824133722-lva1-app6891.ppt
classandobjectunit2-150824133722-lva1-app6891.pptclassandobjectunit2-150824133722-lva1-app6891.ppt
classandobjectunit2-150824133722-lva1-app6891.ppt
 
Application package
Application packageApplication package
Application package
 
Lecture 5.pptx
Lecture 5.pptxLecture 5.pptx
Lecture 5.pptx
 
Ruby object model
Ruby object modelRuby object model
Ruby object model
 
Object & classes
Object & classes Object & classes
Object & classes
 
Object Oriented PHP - PART-1
Object Oriented PHP - PART-1Object Oriented PHP - PART-1
Object Oriented PHP - PART-1
 
OOSD1-unit1_1_16_09.pptx
OOSD1-unit1_1_16_09.pptxOOSD1-unit1_1_16_09.pptx
OOSD1-unit1_1_16_09.pptx
 

More from siragezeynu

2 programming with c# i
2 programming with c# i2 programming with c# i
2 programming with c# i
siragezeynu
 
6 database
6 database 6 database
6 database
siragezeynu
 
Recovered file 1
Recovered file 1Recovered file 1
Recovered file 1
siragezeynu
 
Chapter one
Chapter oneChapter one
Chapter one
siragezeynu
 
Chapter 4
Chapter 4Chapter 4
Chapter 4
siragezeynu
 
Chapter 3i
Chapter 3iChapter 3i
Chapter 3i
siragezeynu
 
Chapter 5
Chapter 5Chapter 5
Chapter 5
siragezeynu
 
Lab4
Lab4Lab4
Chapter 6
Chapter 6Chapter 6
Chapter 6
siragezeynu
 
Chapter 1
Chapter 1Chapter 1
Chapter 1
siragezeynu
 
Chapter 2
Chapter 2Chapter 2
Chapter 2
siragezeynu
 
6 chapter 6 record storage and primary file organization
6 chapter 6  record storage and primary file organization6 chapter 6  record storage and primary file organization
6 chapter 6 record storage and primary file organization
siragezeynu
 

More from siragezeynu (12)

2 programming with c# i
2 programming with c# i2 programming with c# i
2 programming with c# i
 
6 database
6 database 6 database
6 database
 
Recovered file 1
Recovered file 1Recovered file 1
Recovered file 1
 
Chapter one
Chapter oneChapter one
Chapter one
 
Chapter 4
Chapter 4Chapter 4
Chapter 4
 
Chapter 3i
Chapter 3iChapter 3i
Chapter 3i
 
Chapter 5
Chapter 5Chapter 5
Chapter 5
 
Lab4
Lab4Lab4
Lab4
 
Chapter 6
Chapter 6Chapter 6
Chapter 6
 
Chapter 1
Chapter 1Chapter 1
Chapter 1
 
Chapter 2
Chapter 2Chapter 2
Chapter 2
 
6 chapter 6 record storage and primary file organization
6 chapter 6  record storage and primary file organization6 chapter 6  record storage and primary file organization
6 chapter 6 record storage and primary file organization
 

Recently uploaded

Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Product School
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
DianaGray10
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
Product School
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
Guy Korland
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Tobias Schneck
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
Sri Ambati
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
Paul Groth
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
Alan Dix
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
Cheryl Hung
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Product School
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
Safe Software
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
Laura Byrne
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
Kari Kakkonen
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
Jemma Hussein Allen
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
DianaGray10
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Jeffrey Haguewood
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
Elena Simperl
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
Product School
 
PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)
Ralf Eggert
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
Thijs Feryn
 

Recently uploaded (20)

Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
 
Key Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdfKey Trends Shaping the Future of Infrastructure.pdf
Key Trends Shaping the Future of Infrastructure.pdf
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
 
PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
 

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
  • 16. 13-04-2021 class and object 16
  • 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
  • 21. 13-04-2021 class and object 21
  • 22. 13-04-2021 class and object 22 Returning a Value Out put Volume is 3000.0
  • 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
  • 24. 13-04-2021 class and object 24
  • 25. 13-04-2021 class and object 25
  • 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
  • 27. 13-04-2021 class and object 27
  • 28. 13-04-2021 class and object 28
  • 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
  • 30. 13-04-2021 class and object 30
  • 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 { }
  • 37. 13-04-2021 class and object 37 Example of static variable
  • 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; }
  • 44. 13-04-2021 class and object 44
  • 45. 13-04-2021 class and object 45
  • 46. 13-04-2021 class and object 46
  • 47. 13-04-2021 class and object 47
  • 48. 13-04-2021 class and object 48
  • 49. 13-04-2021 class and object 49

Editor's Notes

  1. 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
  2. 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 .
  3. The results in the change in original value of the object if the value is modified in the method
  4. 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.  
  5. 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.
  6. 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.
  7. 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.
  8. 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; }
  9. 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.
  10. 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.
  11. 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.
  12. 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;
  13. 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
  14. 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()); }}