Classes and Objects – Unit 2
Creating Package in Java
Program 1
package p1;
public class Student
{
public void
studisplay()
{
System.out.println("Creating
package 1");
}
}
Note: compile
javac Student.java (compile successfully but package not
created)
javac -d . Student.java (compile and package also created)
java Student (to run the program)
Program 2
package com.oracle;
import p1.*;
(or)
import p1.Student;
public class Testpackage
{
public static void
main(String[] a)
{
Student
s=new Student();
s.studisplay();
(or)
new
Student().studisplay();
new
Batch().Batchdispaly();
}
}
// compile:
javac -d . Testpackage.java
// run: java
com.oracle.Testpackage
Access Modifiers in Java
Reference url : https://www.geeksforgeeks.org/java/access-modifiers-java/
Example
program for public access
package a1;
public class Test1
{
public void
hello() // here method is public
access
{
System.out.println("Welcome
from Test1 class");
}
}
package a2;
import a1.*;
class Test2
{
public static void
main(String a[])
{
//Test1
t1 = new Test1();
//t1.
hello();
new
Test1().hello();
System.out.println("Welcome
guys...");
}
}
Example
program for default access
package a1;
public class Test1
{
void hello() // here method is default access
{
System.out.println("Welcome
from Test1 class");
}
}
Example
program for protected access
package a1;
public class Test1
{
protected void
hello() // here method is protected
access
{
System.out.println("Welcome
from Test1 class");
}
}
Example
program for private access
package a1;
public class Test1
{
private void
hello() // here method is private
access
{
System.out.println("Welcome
from Test1 class");
}
}
Example program on Object creation & copy 1 object to other
class Test3
{
void monday()
{
System.out.println("Welcome to class on monday");
}
public static void main(String args[])
{
//Test3 t = new Test3();
t.monday(); (or)
new Test3().monday(); // both are same
// copy 1 object to other
Test3 t1 = new Test3(); // int a = 100;
Test3 t2 = t1; // int b = a;
t2.monday();
System.out.println("Good morning");
}
}
// -->
Parameters / arguments
Class Members
Declared using the static keyword, the variables or
methods belong to the class itself, not to any specific instance.
Static Variables (Class
Variables)
Static Methods (Class
Methods)
Encapsulation
Encapsulation in Java is a process of wrapping data (variables) and code
(methods) together into a single unit.
Encapsulation is nothing but an Data hiding.
The variables of a class will be hidden from
other classes, and can be accessed only through the methods of their current
class. Therefore, it is also known as data hiding.
To achieve encapsulation in Java −
Declare the
variables of a class as private.
Provide public
setter and getter methods to modify and view the variables values.
Example 1
Program
class Programmer
{
private
String name;
public
void setName(String name) //
setter
{ this.name = name; }
public
String getName() // getter
{ return name; }
}
public class Test
{
public static void main(String[] args)
{
Programmer p = new Programmer();
p.setName("John");
System.out.println("Name : " +
p.getName());
}
}
Example 2
Program
class Test111
{
private String
name;
public void
Setname(String name) // setter
{ this.name =
name; }
public String
Getname() // getter
{ return name; }
public static void
main(String a[])
{
Test111
t1 = new Test111();
t1.Setname("ajay");
System.out.println("Student
name is : "+t1.Getname());
}
}
Uses
of Encapsulation in Java
Using encapsulation in Java has many benefits:
·
Data Hiding: The internal data of an object is hidden from the outside
world, preventing direct access.
·
Data Integrity: Only validated or safe values can be assigned to an object’s
attributes via setter methods.
·
Reusability: Encapsulated code is more flexible and reusable for future
modifications or requirements.
·
Security: Sensitive data is protected as it cannot be accessed
directly.
Polymorphism
Polymorphism
is derived from 2 Greek words: poly and morphs.
The word
"poly" means many and "morphs" means forms.
Advantages of Polymorphism
ü Code Reusability
ü Flexibility and Extensibility
ü Dynamic Method Invocation
ü Reduced Code Complexity
This are mainly 2 types
1. Overloading / Compile Time Polymorphism / Static Binding / Early
Binding
2. Overriding / Run Time Polymorphism / Dynamic Binding / Late Binding
Method overloading
class Calculate
{
void add(int a,
int b)
{
System.out.println("Add
is : "+(a+b));
}
void add(int a,
int b,int c)
{
System.out.println("Add
is : "+(a+b+c));
}
{
return a + b;
} */
public static void
main(String a[])
{
Calculate
c = new Calculate();
c.add(3,5);
c.add(3,5,8);
c.add(3,5,12,14);
}
}
Constructor
overloading
class Calculate
{
Calculate(int a, int b)
{
System.out.println("Im
constructor, Add is : "+(a+b));
}
Calculate(int a, int b,int c)
{
System.out.println("Im
constructor, Add is : "+(a+b+c));
}
{
Calculate
c = new Calculate(20,30);
new
Calculate(40,50,10);
}
}
//
Passing object as parameter to methods
(Program
1)
class Demo
{
int a, b;
{
a = i;
b = j;
}
{
return (d.a == a
&& d.b == b); //ob1.45 == ob3.23
&& ob1.65. == ob3.43
}
}
public class DemoTest
{
public static void
main(String args[])
{
Demo ob1 = new Demo(45,
65);
Demo ob2 = new Demo(45,
65);
Demo ob3 = new Demo(23,
43);
System.out.println("ob1 == ob3: "+ ob1.equalTo(ob3));
}
}
//
Passing object as parameter to methods
(Program
2)
class Box {
double width, height, depth;
{
width = ob.width;
height = ob.height;
depth = ob.depth;
}
{
width = w;
height = h;
depth = d;
}
{
return width *
height * depth;
}
}
{
public static void
main(String args[])
{
Box mybox = new Box(10,
20, 15);
vol = mybox.volume();
System.out.println("Volume of mybox is " + vol);
}
}
Java Nested and Inner Class
In Java,
you can define a class within another class. Such class is known as nested class
There are two types of nested
classes you can create in Java.
·
Non-static nested class (inner
class)
·
Static nested class
Non-Static Nested Class (Inner
Class)
ü
A non-static nested class is a class
within another class.
ü
It has access to members of the
enclosing class (outer class). It is commonly known as inner class.
ü
Since the inner class exists
within the outer class, you must instantiate the outer class first, in order to
instantiate the inner class.
Example Program:
class CPU
{
class Processor // nested class
{
void test()
{
sop("hello"); }
}
}
public class Laptop
{
public static void
main(String[] args)
{
CPU cpu = new CPU();
pro.test();
}
}
Static Nested Class
In Java, we can also
define a static
class inside
another class. Such class is known as static nested class
.
Example
Program:
class Outer
{
static int x = 10;
private static int z = 30;
static class Inner // static nested class
{
void display()
{
System.out.println("x value is : " +x); // can access static member of outer class
System.out.println("private value is : "+z); // can access private static member of outer class
Outer out = new Outer();
System.out.println("y value is : " +out.y);
}
}
}
public class StaticNestedClassDemo
{
public static void
main(String[] args)
{
Outer.Inner abc = new Outer.Inner();
abc.display();
}
}
Key Points to Remember
·
Java
treats the inner class as a regular member of a class. They are just like methods and variables
declared inside a class.
·
Since the nested class is a member
of its enclosing outer class, you can use the dot (.)
notation to access the nested class and its members.
Nesting of Methods
In Java,
"nesting methods" typically refers to one method calling another
method within the same class.
class Main
{
method1()
{
// statements
}
method2()
{
//
statements
}
}
Recursive Method
A recursive method is a method that calls
itself to solve a problem. This technique, known as recursion, is often used to break down complex
problems into smaller
Examples of problems commonly solved with recursion:
·
Factorial calculation: n! = n * (n-1)! with a
base case of 0! = 1.
·
Fibonacci series: F(n) = F(n-1) + F(n-2) with base
cases F(0) = 0 and F(1) = 1.
Example program on combination of package creation, encapsulation,
overloading
--------------------------------------------------------------
Create a Java class "WiproOnboarding" (with package com.wipro.joining)
create a method "EmpOnboarding"
provide setters & getters for Emp_Name, Emp_Loc
Create a Java class "WiproPayroll"
(with package com.wipro.payroll)
provide setters & getters for Emp_Salary(basic), Emp_Salary(basic, bonus), Emp_Level
Create a Java WiproEmpDetails as Main class (with package Wipro )
Create a method HR_Info
print the Emp_Salary, Emp_Level, Emp_Name, Emp_Loc by using Setters & Getters
------------------------------------
package com.wipro.joining;
public class WiproOnboarding
{
private
String Emp_Name, Emp_Loc;
public
void EmpOnboarding()
{
System.out.println("Welcome
to Wipro, WISH YOU GOOD LUCK");
}
public
void SetEmp_Name(String Emp_Name)
{
this.Emp_Name
= Emp_Name;
}
public
String GetEmp_Name()
{
return
Emp_Name;
}
public
void SetEmp_Loc(String Emp_Loc)
{
this.Emp_Loc
= Emp_Loc;
}
public
String GetEmp_Loc()
{
return
Emp_Loc;
}
}
Compile: javac -d .
WiproOnboarding
package com.wipro.payroll;
class WiproPayroll
{
private
float Emp_Salary, Emp_Bonus;
private
int Emp_Level;
public
void SetEmp_Salary(float Emp_Salary)
{
this.Emp_Salary
= Emp_Salary;
}
public
void SetEmp_Salary(float Emp_Salary, float Emp_Bonus)
{
this.Emp_Salary
= Emp_Salary;
this.Emp_Bonus = Emp_Bonus;
}
public
float GetEmp_Salary()
{
Emp_Salary
= Emp_Salary + Emp_Bonus;
return
Emp_Salary;
}
public
void SetEmp_Level(int Emp_Level)
{
this.Emp_Level
= Emp_Level;
}
public
int GetEmp_Level()
{
return
Emp_Level;
}
}
Compile: javac -d .
WiproPayroll
package com.wipro;
import com.wipro.joining.*;
import com.wipro.payroll.*;
class WiproEmpDetails
{
public
void HR_Info()
{
WiproOnboarding w = new
WiproOnboarding();
w.EmpOnboarding();
w.SetEmp_Name("John");
w.SetEmp_Loc("Chennai");
System.out.println("******************");
System.out.println("EmpName
:"+w.GetEmp_Name());
System.out.println("EmpLoc
:"+w.GetEmp_Loc());
System.out.println("******************");
}
public
static void main(String a[])
{
WiproEmpDetails
wd = new WiproEmpDetails();
wd.HR_Info();
}
}
String Handling in Java………………..
·
String objects are immutable
in Java (meaning their content cannot be changed after creation),
·
String data is going to store
in “String constant pool”
·
StringBuffer is mutable
Example
program on String Mutable:
public class StringDemo123 {
public static void main(String[] args) {
int a = 10;
a = a + 5;
System.out.println(a); // a = 15
String s = "Good";
s.concat("morning");
System.out.println(s); // Good
String z = new String("Virat");
z.concat("Kholi");
System.out.println(z); // Virat
StringBuffer p = new StringBuffer("Laki");
p.append("reddy");
System.out.println(p); // Lakireddy
}
}
// Diff btwn == & equals() ????
public static void main(String[] args) {
String a = "Hello";
String b = "Hello";
if(a==b)
System.out.println("same");
else
System.out.println("Diff");
String c = new String("laptop");
String d = new String("Laptop");
if(c.equals(d))
System.out.println("name is same");
else
System.out.println("name is Diff");
}
Java String toUpperCase() and toLowerCase() method
1. String s="India";
2. System.out.println(s.toUpperCase());//INIDIA
3. System.out.println(s.toLowerCase());//india
Java String startsWith() and endsWith() method
1. String p="Orange";
2. System.out.println(p.startsWith("Or"));//true
3. System.out.println(p.endsWith("e"));//true
Java String charAt() method
1. String s="Android";
2. System.out.println(s.charAt(0)); // A
3. System.out.println(s.charAt(3)); //r
Java String length() method
1. String s="Computer";
2. System.out.println(s.length());
//8
Java String replace() method
The string replace() method replaces all
occurrence of first sequence of character with second sequence of character.
1. String s1="India is a big
Country. India has many states. India has many religions.";
2. String replaceString=s1.replace("India","China");
3. System.out.println(replaceString);
Output: China is a big Country. China has many states. China has many religions.
Methods for extracting
characters from string in java
Different String methods
compareTo(), concat(), contains(), equals(), equalsIgnoreCase(), format(), getBytes()
getChars(), indexOf(), lastIndexOf(), isEmpty(), join(), length(), matches(), valueOf(),
replaceAll(), replaceFirst(), startsWith(), endsWith(), subSequence(), trim(),
Technical
Programs in Java
Program: 1
Write
a class to Calculate Box Area and Box Volume, where
//
Provide setters & getters.
Provide
the 2 methods to compute Surface area & Volume.
Surface
area = 2(lh) + 2(hw) + 2(wl)
Volume=
l*h*w
Program: 2(Generate current bill)
Write
a class with name customer whose object is to represent 3 data values
Customer
no, (int)
Customer
type, (int)
Units
consumed (int)
Provide
constructors and setters & getters.
Provide
the method to compute bill Amount.
To
calculate the bill the following slab is considered.
Range |
Customer type “1” |
Customer type “2” |
< 200 units
|
250/- |
400/- |
(300-200)
|
250/- + 2.25/- units which are excess of 200 units |
400/- + 3.75/- units which are excess of 200 units |
(450-300)
|
400/- + 3.50/-
units which are excess of 300 units |
600/- + 4.50/- units which are excess of 300 units |
>450 |
550/- + 4.75/-
units which are excess of 450 units |
750/- + 5.25/- units which are excess of 450 units |
Program 3 (Calculate emp salary)
Write
a class with name employee to represent particulars of emp including
emp.no(int), level no(int), basic salary(double)
Provide
setters & getters and constructors.
And
we need to provide following computations.
è Compute Perks of an
Employee
Perks includes HRA @ 15%
of basic
DA
@ 9% of basic
TA
@ 12% of basic
And other allowances
Other allowances depending on level no of an employee.
Level no |
Amount |
1 |
3,500/- |
2 |
2,500/- |
3 |
1,500/- |
4 |
900/- |
è Calculate Gross Salary of
an Employee
-----It includes basic salary + perks
à Calculate Tax Amount
-----Tax
amount is deducted on the basic % to Gross Salary.
Gross salary Tax
>30,000/- 8%
>20,000/- 5%
>10,000/- 3%
à Calculate Net Salary of
an Employee (On hand)
n Net Salary (GrossSalary - TaxAmount)