0% found this document useful (0 votes)
17 views74 pages

05 Class and Object PR

The document provides a comprehensive overview of class and object-oriented programming concepts in Java, including class declaration, member variables, methods, and constructors. It explains the structure of classes, how to create and manipulate objects, and the significance of method parameters and overloading. Additionally, it covers access control, instance vs class members, and the use of keywords like public, private, and final.

Uploaded by

rigiiih10
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views74 pages

05 Class and Object PR

The document provides a comprehensive overview of class and object-oriented programming concepts in Java, including class declaration, member variables, methods, and constructors. It explains the structure of classes, how to create and manipulate objects, and the significance of method parameters and overloading. Additionally, it covers access control, instance vs class members, and the use of keywords like public, private, and final.

Uploaded by

rigiiih10
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 74

CLASS

Content
• Declaring Classes
• Declaring Member Variables
• Defining Methods
• Providing Constructors for Your Classes
• Passing Information to a Method or a Constructor
• Objects
• Creating Objects
• Using Objects
• Using the this Keyword
• Controlling Access to Members of a Class
• Understanding Instance andAIClass Members
11/27/2024 2
Object Oriented Concepts
• .

11/27/2024 AI 3
Class / Objects
• A class is a blueprint or prototype from which objects are
created
• Real word entities that has their own properties and
behavior e,g student, Book, Car, Employee
• Everything in Java is associated with classes and objects,
along with its attributes and methods. For example: in
real life, a car is an object. The car has attributes, such as
weight and color, and methods, such as drive and brake.
• For example, if you want to create a class for students. In
that case, "Student" will be a class, and student records
(like student1, student2, etc) will be objects.
11/27/2024 AI 4
Defining Classes
• To define a class, use the class keyword and the name of
the class:
• class MyClassName { ... }
• If this class is a subclass of another specific class (that is,
inherits from another class), use extends to indicate the
superclass of this class:
• class myClassName extends mySuperClassName { ... }

11/27/2024 AI 5
Working with Classes
• A class can be declared using one of the following key
words.
• Public – the class can be accessed globally
• Abstract – the class cannot be instantiated
• Extends – the class inherits the proprties of a super class
• Implements runnable – creates an interface through which
a class inherits properties, which it could not have
inherited from a superclass.
• Implements ActionListener – class is able to respond to
the events triggered by user.

6
Declaring Classes
• class MyClass { // field, constructor, and // method
declarations } - This is a class declaration.
• The class body (the area between the braces) contains all
the code that provides for the life cycle of the objects
created from the class: constructors for initializing new
objects, declarations for the fields that provide the state of
the class and its objects, and methods to implement the
behavior of the class and its objects.
• You can provide more information about the class, such
as the name of its superclass, whether it implements any
interfaces, and so on, at the start of the class declaration.
11/27/2024 AI 7
Declaring Classes
• For example,
• class MyClass extends MySuperClass implements
YourInterface { // field, constructor, and // method
declarations }
• means that MyClass is a subclass of MySuperClass and
that it implements the YourInterface interface.
• You can also add modifiers like public or private at the
very beginning—so you can see that the opening line of a
class declaration can become quite complicated. The
modifiers public and private, which determine what other
classes can access MyClass.
11/27/2024 AI 8
Declaring Classes
• In general, class declarations can include these components,
in order:
• Modifiers such as public, private, and a number of others
that you will encounter later.
• The class name, with the initial letter capitalized by
convention.
• The name of the class's parent (superclass), if any, preceded
by the keyword extends. A class can only extend (subclass)
one parent.
• A comma-separated list of interfaces implemented by the
class, if any, preceded by the keyword implements. A class
can implement more than one interface.
AI 9
• The class body, surrounded by braces, {}.
10
Create an Object
public class Book {
int pgs = 200;
String bkTitle="Introduction to Java";
public static void main(String[] args) {
Book bk = new Book();
System.out.println(bk.pgs);
System.out.println(bk.bkTitle);
}}
11/27/2024 AI 11
override existing values:
public class Book
{ int pgs = 200;
String bkTitle="Introduction to Java";
public static void main(String[] args)
{ Book bk = new Book();
System.out.println(bk.pgs);
bk.pgs=220;
System.out.println(bk.pgs);
System.out.println(bk.bkTitle);
}
AI 12
}
public class Book .
{ int pgs;
String bkTitle;
public void display(String bkTitle, int pgs)
{ System.out.println("Book Title :"+bkTitle);
System.out.println("Number of Pages :"+pgs);
}
public static void main(String[] args)
{ Book bk = new Book();
bk.display(" INTRODUCTION TO JAVA", 200);
bk.display(" INTRODUCTION TO DATABASE
SYSTEMS", 400);
}
}
13
MODIFY ATTRIBUTES
If you don't want the ability to override existing values, declare the
attribute as final . The final keyword is useful when you want a variable
to always store the same value, like PI (3.14159...).
public class Book
{ final int pgs = 200;
String bkTitle="Introduction to Java";
public static void main(String[] args)
{ Book bk = new Book();
System.out.println(bk.pgs);
bk.pgs=220;
System.out.println(bk.pgs);
System.out.println(bk.bkTitle);
}
14
}
Class Body
The class body comprises of the following:-
i. Variables
ii. Methods
iii. Constructor methods
iv. Finalize methods

11/27/2024 AI 15
Member Variables
Variables are categorized into two:-
i. Member variable – variables that are directly associated
with class. They are defined in a class body but not
inside a method. Member variables in a class—these are
called fields.

ii. Non-member variable – variables not directly


associated with a class they are defined inside a method
body or as parameters to a method. Variables in a
method or block of code—these are called local
variables.
AI 16
Declaring Member Variables
• Variables in method declarations—these are called
parameters.

• NB same naming rules and conventions are used for


method and class names, except that the first letter of a
class name should be capitalized, and the first (or only)
word in a method name should be a verb.

11/27/2024 AI 17
In summary, a member variable
declaration.
[accessSpecifier][static] [final][transient]type
variableName
accessSpecifier defines which other classes have access to
the variable
static indicates that the variable is a class member variable
as opposed to an instance member variable
final indicates that the variable is a constant
transient variables are not part of the object's persistent state
Return_type: Refers to the return value.Can be void(no
return value), or any of the Java data types such as float.

11/27/2024 MUNYAO 18
Multiple Objects
public class Book {
int pg1 = 150;
String title1 = "Introduction to Java";
String title2 = "Introduction to DBMS";
int pg2 = 200;
public static void main(String[] args) {
Book bk1 = new Book();
Book bk2 = new Book();
System.out.println("First book title is " + bk1.title1);
System.out.println(bk1.pg2);
System.out.println("_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ ");
System.out.println("Second book title is " + bk2.title2);
System.out.println(bk2.pg2);
19
}}
public class Student {
String name; int age;
.
double marks;
public Student(String name) { this.name = name; }
public void stAge(int stAge) { age = stAge; }
public void stSalary(double stSalary) { marks = stSalary; }
public void printStudent() {
System.out.println("Students Name is :"+ name );
System.out.println("Students Age is :" + age ); System.out.println("Student
Marks are :" + marks); System.out.println("_ _ _ _ _ _ _ _ _ _ _ _ _ "); }
public static void main(String args[]) {
Student stOne = new Student("James Kimeu");
Student stTwo = new Student("Mary Wambui");
stOne.stAge(26);
stOne.stSalary(1000);
stOne.printStudent();
stTwo.stAge(21);
stTwo.stSalary(500);
stTwo.printStudent(); }} 20
METHODS
• A method is a block of code which only runs when it is
called.
• You can pass data, known as parameters, into a method.
• Methods are used to perform certain actions, and they are
also known as functions.
• Why use methods? To reuse code: define the code once,
and use it many times.

11/27/2024 AI 21
Constructor with attributes
public class Student {
int age;
public Student(int y) { age = y; }
public static void main(String[] args) {
Student st1 = new Student(22);
Student st2 = new Student(24);
System.out.println("Age of First student is "+st1.age);
System.out.println("Age of Second student is "+st2.age);
}}

AI 22
11/27/2024 AI 23
Defining Methods/ Declaration
A method must be declared within a class.
It is defined with the name of the method, followed by parentheses ().
Java provides some pre-defined methods, such as System.out.println(),
but you can also create your own methods to perform certain actions:

• The only required elements of a method declaration are the


method's return type, name, a pair of parentheses, (), and a
body between braces, {}.

• public double calculateAnswer(double wingSpan, int


numberOfEngines, double length, double grossTons) { //do
the calculation here }
11/27/2024 AI 24
11/27/2024 AI 25
Defining Methods/ Declaration
• More generally, method declarations have six components,
in order:
• Modifiers—such as public, private, and protected
• The return type—the data type of the value returned ..
• The method name—the rules for field names apply to
method names as well, but the convention is a little
different.
• The parameter list in parenthesis—a comma-delimited list
of input parameters, preceded by their data types, enclosed
by parentheses, ()..
• An exception list—to be discussed later.
• The method body, enclosed between
AI
braces—the method's 26
code, including the declaration of local variables, goes here.
Call a Method
public class Main
{
static void myMethod()
{ System.out.println("I just got executed!");
}
public static void main(String[] args)
{
myMethod();
}
}

11/27/2024 AI 27
Parameters and Arguments
• Information can be passed to methods as a parameter.
Parameters act as variables inside the method.

• Parameters are specified after the method name, inside


the parentheses. You can add as many parameters as you
want, just separate them with a comma.

11/27/2024 AI 28
EXAMPLE of Methods
public class Main
{
static void myMethod(String fname, int age)
{
System.out.println("My name is " + fname); System.out.println("My
age is "+age); System.out.println("_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _");
}
public static void main(String[] args)
{ myMethod("Liam", 5);
myMethod("Jenny", 8);
myMethod("Anja", 31);
}}
11/27/2024 AI 29
To call a method, write the method's name followed
by two parentheses () and a semicolon;

public class Book {


static void myMethod() {
System.out.println("Introduction to Java"); }
public static void main(String[] args) {
myMethod();
}}

11/27/2024 AI 30
/** the snippet returns the minimum between two numbers */
public static int minFunction(int n1, int n2)
{ int min;
if (n1 > n2) min = n2;
else min = n1;
return min;
}
double computeSalary(double hrs, double hrlypay)
{
double salary=hrs*hrlypay;
11/27/2024
return salary; AI 31

}
Naming a Method
• 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
• Typically, a method has a unique name within its class.
However, a method might have the same name as other
methods due to method overloading.
11/27/2024 AI 32
• A class contains code that describes the
properties the object has and behavior it is
capable of.
• Syntax for defining method
– Public returnType methodname (parameter list)
{//code for method goes here.
}// end of method body

11/27/2024 AI 33
Java Method Parameters
• Parameters and Arguments
Information can be passed to methods as parameter.
Parameters act as variables inside the method.
Parameters are specified after the method name, inside the
parentheses.
You can add as many parameters as you want, just separate
them with a comma.
The following example has a method that takes a String
called fname as parameter.
When the method is called, we pass along a first name,
which is used inside the method to print the full name:
11/27/2024 AI 34
public class Book {
static void myMethod(String bkTitle) {
System.out.println(" Introduction to "+bkTitle);
}
public static void main(String[] args) {
myMethod("Java");
myMethod("C++");
myMethod("SQL"); }}

11/27/2024 AI 35
import java.util.Scanner;
public class RectangleAreaCalculator
{ public static void main(String[] args).
{ Scanner scanner = new Scanner(System.in);
System.out.print("Enter the length of the rectangle: ");
double length = scanner.nextDouble();
System.out.print("Enter the width of the rectangle: ");
double width = scanner.nextDouble();
double area = calculateArea(length, width);
display(length, width, area); }
public static double calculateArea(double length, double width)
{ return length * width; }
public static void display(double length, double width, double area)
{ System.out.println("\nRectangle Details:");
System.out.println("Length: " + length);
System.out.println("Width: " + width);
System.out.println("Area: " + area);
}}
11/27/2024 AI 36
import java.util.Scanner;
public class RectangleAreaCalculator {
.
public static double calculateArea(double length, double width)
{ return length * width; }
public static void display(double length, double width, double area)
{ System.out.println("\nRectangle Details:");
System.out.println("Length: " + length);
System.out.println("Width: " + width);
System.out.println("Area: " + area);
}
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the length of the rectangle: ");
double length = scanner.nextDouble();
System.out.print("Enter the width of the rectangle: ");
double width = scanner.nextDouble();
double area = calculateArea(length, width);
37
display(length, width, area); } }
Overloading Methods
• The Java programming language supports overloading
methods, and Java can distinguish between methods with
different method signatures. This means that methods
within a class can have the same name if they have different
parameter lists
• Overloaded methods are differentiated by the number and
the type of the arguments passed into the method.
• You cannot declare more than one method with the same
name and the same number and type of arguments, because
the compiler cannot tell them apart.
• Note: Overloaded methods should be used sparingly, as
they can make code much less readable.
11/27/2024 AI 38
OVERLOADED METHOD
public class Polygon {
static double myarea(double x, double y)
{ return x*y/2;}
static int myarea(int x, int y) { return x*y;}
public static void main(String[] args) {
double area1 = myarea(8.0, 6.0);
int area2 = myarea(10, 12);
System.out.println("AREA OF THE TRIANGLE IS " +
area1+" M2");
System.out.println("AREA OF THE RECTANGLE IS " +
area2+" M2");}}
11/27/2024 AI 39
public class OverloadVolume {
public static double volume(double l, double w, double h)
{ return l*w*h; }
public static float volume(float l)
{ return l*l*l; }
public static double volume(float r, float h)
{ return 3.1416 * r * r * h; }
public static void main(String[] args)
{ double rectangleBox = volume(5.0, 8.0, 9.0);
System.out.println("Area of ractangular box is " + rectangleBox);
System.out.println("");
double cube = volume(5);
System.out.println("Area of cube is " + cube);
System.out.println("");
double cylinder = volume(6, 12);
System.out.println("Area of cylinder is " + cylinder);
} AI 40

}
public class OverloadArea{
.
public static int area(int l, int w)
{ return l*w; }
public static float area(float l, float h)
{ return l*h/2; }
public static void main(String[] args)
{ int rectangleArea = area(5, 8);
System.out.println("Area of ractangular box is " +
rectangleArea);
System.out.println("");
float traigleArea = area(4.0, 2.0);
System.out.println("Area of Trianle is " +
traigleArea);
System.out.println(""); AI
11/27/2024 41
}
Providing Constructors for
Your Classes

11/27/2024 AI 42
Constructors
• A constructor has same name as the class
• They have no return values
• The constructor is responsible for setting up the
initial state of an object.
• To create a new object, you use the new operator
with the name of the class you want to create an
instance of, then parentheses after that.
– String str = new String();
– Random r = new Random();
– Motorcycle m2 = new Motorcycle(); 43
Constructors
• A method that creates objects.
• Constructors are invoked using the new keyword
• You can declare more than one constructor in a class
declaration.
• E.g
• Student st= new Student( );

11/27/2024 AI 44
Instantiating a Class
• The new operator instantiates a class by allocating memory
for a new object and returning a reference to that memory.
The new operator also invokes the object constructor.
• Note: The phrase "instantiating a class" means the same
thing as "creating an object." When you create an object,
you are creating an "instance" of a class, therefore
"instantiating" a class.
• The new operator requires a single, postfix argument: a call
to a constructor. The name of the constructor provides the
name of the class to instantiate.
• The new operator returns a reference to the object it
created. This reference is usually assigned to a variable of
the appropriate type, like:
• Point originOne = new Point(23, 94);
Initializing an Object
• Here's the code for the Point class:
• public class Point { public int x = 0; public int y = 0;
//constructor public Point(int a, int b) { x = a; y = b; } }
• This class contains a single constructor. You can recognize a
constructor because its declaration uses the same name as the class
and it has no return type. The constructor in the Point class takes two
integer arguments, as declared by the code (int a, int b). The
following statement provides 23 and 94 as values for those
arguments:
• Point originOne = new Point(23, 94);

11/27/2024 AI 46
Using Objects
• Once you've created an object, you probably want to use
it for something. You may need to use the value of one of
its fields, change one of its fields, or call one of its
methods to perform an action.
• Referencing an Object's Fields
• Object fields are accessed by their name. You must use a
name that is unambiguous.
• You may use a simple name for a field within its own
class. For example, we can add a statement within the
Rectangle class that prints the width and height:
• System.out.println("Width and height are: " + width + ", "
11/27/2024
+ height); AI 47
• In this case, width and height are simple names.
• Code that is outside the object's class must use an object
reference or expression, followed by the dot (.) operator,
followed by a simple field name, as in:
• objectReference.fieldName
• For example, the code in the CreateObjectDemo class is
outside the code for the Rectangle class. So to refer to the
origin, width, and height fields within the Rectangle object
named rectOne, the CreateObjectDemo class must use the
names rectOne.origin, rectOne.width, and rectOne.height,
respectively. The program uses two of these names to
display the width and the height of rectOne:
System.out.println("Width ofAI rectOne: " + rectOne.width);48
•11/27/2024
System.out.println("Height of rectOne: " + rectOne.height);
public class Rectangle {
int length, width; int Area =0;
public int calculateArea (int l, int w){
length = l; width = w;
int A ;
A = l*w;
Area =A;
return Area; }
public void showDimension(){
System.out.println("The length ="+length);
System.out.println("The width ="+width);
System.out.println("Thee Area ="+Area);
}
public static void main(String[] args){
Rectangle rect = new Rectangle ();
rect.calculateArea(90, 45);
AI 49
rect.showDimension();
Multiple Objects
• Creating multiple objects of one class:
public class Book
{ int pgs = 5;
public static void main(String[] args)
{ Book bkJava = new Book();
Book bkDbms = new Book();
bkJava.pgs=300;
bkJava.pgs=400;
System.out.println(bkJava.pgs);
System.out.println(bkDbms.pgs);
}
}
11/27/2024 AI 50
class Person {
String name; int age;
Person(String n, int a) {
name = n; age = a;}
void printPerson()
{System.out.print("Hi, my name is " + name);
System.out.println(". I am " + age + " years old.");}
public static void main (String args[])
{Person p= new Person("Lawrence", 20);
p.printPerson();
System.out.println("--------");
Person q = new Person(“Dominic", 3);
q.printPerson();
System.out.println("--------");} 51

}
// This program declares two Box objects.
public class Box { double width; double height;
double depth; }
.
class BoxDemo2
{ public static void main(String args[])
{ Box mybox1 = new Box();
Box mybox2 = new Box();
double vol; // assign values to mybox1's instance variables
mybox1.width = 10; mybox1.height = 20;
mybox1.depth = 15; /* assign different values to mybox2's inst*/
mybox2.width = 3; mybox2.height = 6;
mybox2.depth = 9; // compute volume of first box
vol = mybox1.width * mybox1.height * mybox1.depth;
System.out.println("Volume is " + vol);
// compute volume of second box
vol = mybox2.width * mybox2.height * mybox2.depth;
52
System.out.println("Volume is " + vol);
}
Invoking an Object’s method
• Java uses “dot notation”
• referenceToAnObject.memberOfObject
• E.g len=str1.length( ):

11/27/2024 AI 53
Access Modifiers
Modifier Description

public The code is accessible for all classes

private The code is only accessible within the declared class

default The code is only accessible in the same package. This is used when
you don't specify a modifier.

protected The code is accessible in the same package and subclasses. You will
learn more about subclasses and superclasses in the Inheritance
chapter

11/27/2024 AI 54
Calling an Object's Methods
• You append the method's simple name to the object reference,
with an intervening dot operator (.). Also, you provide, within
enclosing parentheses, any arguments to the method. If the
method does not require any arguments, use empty parentheses.
• objectReference.methodName(argumentList);
• or: objectReference.methodName();
• System.out.println("Area of rectOne: " + rectOne.getArea());
• As with instance fields, objectReference must be a reference to
an object.
• Some methods, such as getArea(), return a value. For methods
that return a value, you can use the method invocation in
expressions...
55
Returning a Value from a Method

• A method returns to the code that invoked it when it:


• completes all the statements in the method,
• reaches a return statement, or
• throws an exception (covered later),
• The getArea() method in the Rectangle Rectangle class
that was discussed in the sections on objects returns an
integer:
• // a method for computing the area of the rectangle public
int getArea() { return width * height; }
• This method returns the integer that the expression
width*height evaluates to. AI
11/27/2024 56
public class Employee {
String name; .
int age;
public void setName(String name) { this.name = name; }
public void setAge(int age) { this.age = age; }
public void printDetails() {
System.out.println("Employee Details:");
System.out.println("Employee Name is :"+ this.name);
System.out.println("Employee age is " + this.age);
}
public static void main(String[] args) {
Employee emp = new Employee();
emp.setName("Brian Atiko");
emp.setAge(24);
emp.printDetails();
}} 57
Using Circle Class
// Circle.java: Contains both Circle class and its user class
//Add Circle class code here
class MyMain
{
public static void main(String args[])
{
Circle aCircle; // creating reference
aCircle = new Circle(); // creating object
aCircle.x = 10; // assigning value to data field
aCircle.y = 20;
aCircle.r = 5;
double area = aCircle.area(); // invoking method
double circumf = aCircle.circumference();
System.out.println("Radius="+aCircle.r+" Area="+area);
System.out.println("Radius="+aCircle.r+" Circumference ="+circumf);
}
}
[raj@mundroo]%: java MyMain
58 Radius=5.0 Area=78.5
Radius=5.0 Circumference =31.400000000000002
parameters to the constructor.

11/27/2024 AI 59
class Box
{ double width; double height; double depth;
Box(double w, double h, double d)
{ width = w; height = h; depth = d; }
double volume()
{ return width * height * depth; }
}
class BoxDemo
{ public static void main(String args[])
{
Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box(3, 6, 9);
double vol;
vol = mybox1.volume();
System.out.println("The Volume of mybox1 is " + vol);
vol = mybox2.volume();
System.out.println("The Volume of mybox2 is " + vol);
}
Static vs. Public Method
You will often see Java programs that have either static or
public attributes and methods.
A static method means that it can be accessed without
creating an object of the class, unlike public, which can only
be accessed by objects:
Static - Attributes and methods belongs to the class, rather
than an object

11/27/2024 AI 61
Static method
public class Book
{ static void display()
{ System.out.println("Introduction to Java");
}
public static void main(String[] args)
{ display();
}
}
Nb: try change static to public

62
.
public class Book
{ static void StaticDisplay()
{ System.out.println("Static methods: No Object");
}
public void publicDisplay()
{System.out.println("Public methods Must use objects");
}
public static void main(String[] args)
{ StaticDisplay();
Book bk = new Book();
bk.publicDisplay();
}
} 63
Java Recursion
• Recursion is the technique of making a
function call itself. This technique provides
a way to break complicated problems down
into simple problems which are easier to
solve.

11/27/2024 AI 64
public class Main { public static void
main(String[] args)
{ int result = sum(10);
System.out.println(result);
} public static int sum(int k) { if (k > 0) {
return k + sum(k - 1);
} else { return 0; }
}}
11/27/2024 AI 65
11/27/2024 AI 66
11/27/2024 AI 67
The this Keyword
• Sometimes a method will need to refer to the object that
invoked it. To allow this, Java defines the this keyword.
this can be used inside any method to refer to the
current object.
• That is, this is always a reference to the object on which
the method was invoked. You can use this anywhere a
reference to an object of the current class' type is
permitted.
• The most common reason for using the this keyword is
because a field is shadowed by a method or constructor
parameter
11/27/2024 AI 68
example,
• public class Point { public int x = 0; public int y = 0; //
constructor public Point(int a, int b) { x = a; y = b; } }

but it could have been written like this:
• public class Point { public int x = 0; public int y = 0; //
constructor public Point(int x, int y) { this.x = x; this.y =
y; } }

11/27/2024 AI 69
public class Rectangle{
public int w,h;
public Rectangle(int w,int h){
this.w=w;
this.h=h; }
public int area(int w,int h){ return w*h; }
public static void main(String args[]){
Rectangle rect1=new Rectangle(10,20);
System.out.println("The Area of Rectangle
is"+rect1.area(rect1.w,rect1.h));
} AI 70
}
11/27/2024 AI 71
Message Passing:
• Refers to a statement that invokes a
method from one class to another. Classes
interact via message passing.
• It has the following format:
• Object_name.method_name(param_list)
;

11/27/2024 MUNYAO 72
MANAGING INHERITANCE
IN METHODS
• A mechanism that enables one class to
inherit the characteristics of another class.
• The extends clause declares that your class
is a subclass of another class.
• Java does not support multiple inheritance
• The top most class, the class from which
all other classes are derived, is the Object
class defined in java.lang
11/27/2024 AI 73
END
11/27/2024 MUNYAO 74

You might also like