Skip to content

Commit 9954233

Browse files
committed
feat: Add Practice and A classes to demonstrate instance fields with add and mul methods
WHAT the code does: Defines class A with instance fields x, y, sum, and res. add(int x, int y) assigns arguments to instance fields using this, computes their sum, and prints it. mul() multiplies the stored instance fields and prints the result. Defines a Practice class with main() that: - Creates an object of A - Calls add(5, 7) to compute and print 12 - Calls mul() to compute and print 35 WHY this matters: Demonstrates how instance fields retain values across method calls in the same object. Shows the use of the this keyword to distinguish between method parameters and instance variables. Highlights a basic form of object state: results from one method (add) persist for use in another method (mul). Introduces a foundational concept for object-oriented programming: encapsulating behavior (methods) with data (fields). HOW it works: In main(), an A object is created. add(5, 7) sets x = 5, y = 7, computes sum = 12, and prints 12. mul() then multiplies the stored x and y → 5 * 7 = 35, and prints 35. Because x and y were stored as instance fields, mul() could use them without requiring arguments. Tips and gotchas: Relying on mutable instance fields can make objects harder to reason about; consider returning values instead of printing directly. Better design would compute results and return them, letting main() decide how to use or print values. In larger designs, separating computation logic from I/O improves testability and reuse. Using constructors instead of setter-style methods (like add) could make object initialization more explicit. Use-cases: Educational demonstration of instance variables and method chaining. Introductory example of how object state persists across method calls. Foundation for more complex classes where multiple operations depend on shared internal state. Short key: class-practice object-state this-keyword add-mul. Signed-off-by: https://github.com/Someshdiwan <[email protected]>
1 parent 678da37 commit 9954233

File tree

1 file changed

+7
-11
lines changed

1 file changed

+7
-11
lines changed

Section10Methods/src/Practice.java

Lines changed: 7 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,21 @@
1-
class Practice
2-
{
3-
public static void main(String[] args)
4-
{
1+
class Practice {
2+
public static void main(String[] args) {
53
A a=new A();
64
a.add(5,7);
75
a.mul();
86
}
97
}
10-
class A
11-
{
8+
class A {
129
int x,y,sum,res;
13-
void add(int x,int y)
14-
{
10+
11+
void add(int x,int y) {
1512
this.x=x;
1613
this.y=y;
1714
sum=x+y;
1815
System.out.println(sum);
1916
}
20-
void mul()
21-
{
17+
void mul() {
2218
res=x*y;
2319
System.out.println(res);
2420
}
25-
}
21+
}

0 commit comments

Comments
 (0)