CC102 Lesson 6 Classes and Methods
CC102 Lesson 6 Classes and Methods
and Methods
LEARNING OUTCOMES:
At the end of the session, the students should be
able to:
• Identity the different class according to structure
and characteristics
• Create methods with different parameters and
arguments
• Develop code that declares classes, and includes
the appropriate use of package and import
statements.
Defining a method
• A method is a self-contained block of code
that performs specific operations on the
data by using some logic
Method declaration:
• Name
• Parameter(s)
• Argument(s)
• Return type
• Access modifier
CC102- PROGRAMMING FUNDAMENTALS
5
LESSON VI – Java Classes and Methods
a method syntax
1 2 3 4
1. Access modifier
2. Return type
3. Name
4. Parameter(s)
5. Argument(s)
a method example
1 2 3 4
1. Access modifier
2. Return type
3. Name
4. Parameter(s)
5. Argument(s)
a method example
1 3 4
1. Access modifier
3. Name
4. Parameter(s)
1. Access modifier
2. Return type
3. Name
4. Parameter(s)
1. Access modifier
2. Return type
3. Name
4. Parameter(s)
5. Argument(s)
Defining Classes
The general syntax:
<modifier> class <className> { }
<className> specifies the name of the class
Class Example
Nested Classes
• allows you to define a class (like a variable or a method)
inside a top-level class (outer class or enclosing class)
SYNTAX:
Nested Classes
• allows you to define a class (like a variable or a method)
inside a top-level class (outer class or enclosing class)
SYNTAX:
Nested Class
Example
Creating an Object
SYNYAX:
Example program:
public class Value{
public int InitialValueA() {
int a=5;
return a;
}
public int InitialValueB(){
int b=10;
return b;
}
}//1st class initializing the values for the 2nd class
public class compute{
public int sum(int num1,int num2){
return num1+num2;
}
}//second class with method for arithmetic operation
Example program:
1 public class displaysum{
2 public void display(){
3 int a,b,ValueA,ValueB;
4 //class compute and its method
5 compute addition = new compute();
6 //class value and its method
7 Value Initial = new Value();
8
9 ValueA=Initial.InitialValueA();
10 ValueB=Initial.InitialValueB();
11 a=addition.sum(ValueA,ValueB);
12 System.out.println(a);
13 System.out.println(addition.sum(10,20));
14 }
15}
//3rd class calling the 2 class and methods to perform
//the arithmetic operation with initial value and
//another sample output using the values 10 and 20
Example program:
public class main{
public static void main(String[] args){
displaysum print = new displaysum();
print.display();
}
}
//last class is the main class, on this class the
//output of the previous class display will be called
//as the output of the program.
//the file name of this program is main.java
// all of the 4 classes in under this source code.
display()
InitialValueA()
InitialValueB()
sum(num1,num2)
Variable number
parameters example