Java Chapter 02 Gute Ma
Java Chapter 02 Gute Ma
Object-Oriented
PROGRAMMING
class A
{
// public A()
// Method definition
System.out.println(“Welcome”);
}
class employee
Parameterized Constructors
{
private String Ename, empno;
private float salary;
employee(String eno, String name, float sal)
{
empno = eno;
Ename= name;
salary = sal;
}
public void print()
{
System.out.prinln(empno+”\t”+Ename+”\t”+sal);
}
}
public class demoEmp
{
public static void main(String args[])
{
Employee emp = new employee(“Au196/03”, “Jhon Micheal”, 2563.54);
}}
Cont…Example box public static void main(String
class Box { args[]) {
double width; // declare, allocate, and initialize
double height; Box objects
double depth; Box mybox1 = new Box(10, 20,
// This is the constructor for Box. 15);
Box(double w, double h, double Box mybox2 = new Box(3, 6, 9);
d) { double vol;
width = w; // get volume of first box
height = h; vol = mybox1.volume();
depth = d; System.out.println("Volume is "
} + vol);
// compute and return volume // get volume of second box
double volume() { vol = mybox2.volume();
return width * height * depth; System.out.println("Volume is "
} + vol);
} class BoxDemo7 { }
}
this Keyword
Sometimes a method will need to refer to the object that
invoked it. To allow this, Java defines the this keyword.
Instance can refer to itself with the keyword this
class LightSwitch {
boolean on;
LightSwitch() {
this.on = true; //(same as on=true;)
}
LightSwitch(boolean on) {
this.on = on;
}
}
Recursion
Recursion is the process of return result;
defining something in terms of }
itself. As it relates to Java }
programming, recursion is the class Recursion {
attribute that allows a method to public static void main(String args[]) {
call itself. Factorial f = new Factorial();
A method that calls itself is said to
System.out.println("Factorial of 3 is " +
f.fact(3));
be recursive.
System.out.println("Factorial of 4 is " +
Example: factorial f.fact(4));
class Factorial { System.out.println("Factorial of 5 is " +
// this is a recursive function f.fact(5));
}
int fact(int n) {
}
int result;
if(n==1) return 1;
result = fact(n-1) * n;
Operators
Are symbols that take one or more arguments (operands) and
Operates on them to a produce a result.
Are used to in programs to manipulate data and variables.
They usually form a part of mathematical or logical
expressions.
Expressions can be combinations of variables, primitives and
operators that result in a value.
There are 8 different groups of
operators in Java:
Arithmetic operators
Relational operators
Logical operators
Assignment operator
Increment/Decrement
operators
Conditional operators
Bitwise operators
Special operators