1. Passing objects as Parameters
We can pass an object to a method as parameters, the example below explains
how a method accepts an object as parameter.
class Numbers{
int a,b;
Numbers(int a,int b){
this.a = a;
this.b = b;
}
Numbers(){
this.a = this.b = 0;
}
void printData(){
System.out.println("A : "+this.a+"tB : "+this.b);
}
void sum(Numbers obj1,Numbers obj2){
this.a = obj1.a+ obj2.a;
this.b = obj1.b+ obj2.b;
}
}
public class NewClass{
public static void main(String args[]){
Numbers obj1 = new Numbers(10,20);
Numbers obj2 = new Numbers(40,50);
Numbers obj3 = new Numbers();
obj3.sum(obj1,obj2);
obj1.printData();
obj2.printData();
obj3.printData();
}
}
The output of the following program is :
A : 10 B : 20
A : 40 B : 50
2. A : 50 B : 70
Methods Returning an Objects
A method can return an object of any class, Remember while returning objects
the return-data-type in method should be the same as the class name of the
objects returned.
class Numbers{
int a,b;
Numbers(int a,int b){
this.a = a;
this.b = b;
}
Numbers(){
this.a = this.b = 0;
}
void printData(){
System.out.println("A : "+this.a+"tB : "+this.b);
}
Numbers sum(Numbers obj1,Numbers obj2){
Numbers obj = new Numbers();
obj.a = this.a + obj1.a+ obj2.a;
obj.b = this.b + obj1.b+ obj2.b;
return obj;
}
}
public class NewClass{
public static void main(String args[]){
Numbers obj1 = new Numbers(10,20);
Numbers obj2 = new Numbers(40,50);
Numbers obj3 = new Numbers(56,23);
Numbers obj4 = new Numbers();
obj4 = obj3.sum(obj1,obj2);
obj1.printData();
obj2.printData();
3. obj3.printData();
obj4.printData();
}
}
The output of the following program is :
A : 10 B : 20
A : 40 B : 50
A : 56 B : 23
A : 106 B : 93
Method Overloading
Inside a class we can define many methods with the same name, but the
methods can differ according to the parameters they accept, this concept is
known as Method overloading.
When we are calling such method, the compiler will match the parameters of the
methods, if the parameters match to the method then it will be called.
Example1:
In the following program the method operation is overloaded.
class Numbers{
int a,b;
Numbers(int a ,int b){
this.a = a;
this.b = b;}
void operation(String operation){
if(operation=="Addition")
System.out.println("Addition : "+(a+b));
}
void operation(){
System.out.println("Subtraction : "+(a-b));
}
}
4. public class NewClass{
public static void main(String arsg[]){
Numbers ob = new Numbers(10,20);
ob.operation();
ob.operation("Addition");
}
}
The output of the above program is:
Subtraction : -10
Addition : 30
Example2:
In the following example the method area is overloaded by passing different
objects .
class Square {
int side;
Square(int side){
this.side = side;
}
}
class Rectangle{
int width,length;
Rectangle(int width,int length){
this.width = width;
this.length = length;
}
}
class Circle{
int radius;
Circle(int radius){
this.radius = radius;
5. }
}
class Calculation {
void area(Square obj){
System.out.println("The area of Square is : "+(obj.side*obj.side));
}
void area(Circle obj){
System.out.println("The area of Circle is : "+(obj.radius*2*(3.14)));
}
void area(Rectangle obj){
System.out.println("The area of Rectangle is : "+(obj.width*obj.length));
}
}
public class NewClass{
public static void main(String arsg[]){
Circle circle = new Circle(10);
Rectangle rectangle = new Rectangle(5,2);
Square square = new Square(10);
Calculation ob = new Calculation();
ob.area(circle);
ob.area(square);
ob.area(rectangle);
}
}
The output of the above example is :
The area of Circle is : 62.800000000000004
The area of Square is : 100
The area of Rectangle is : 10
6. Constructor Overloading
Constructor overloading is also a type of method overloading the only difference
is here that we just have constructors overloaded not general methods, the same
thing like methods is applicable in calling constructors,
While an object is declared and passed some parameters then the constructor
will be called that matches the number of parameters that have been passed.
class Numbers{
int a,b;
Numbers(){
this.a = this.b = 0;
}
Numbers(int a,int b){
this.a = a;
this.b = b;
}
Numbers(int a){
this.a = this.b = a;
}
}
public class NewClass{
public static void main(String arsg[]){
Numbers obj1 = new Numbers();
Numbers obj2 = new Numbers(45);
Numbers obj3 = new Numbers(78,100);
}
}
In the above example we have declared and initialized three objects with passing
three types of parameters to constructor, So the constructor is overloaded.
7. Inheritance
It is always nice if we could reuse something that already exist rather than
creating the same all over again, Java supports this concept, Java classes can be
used in several ways, this is basically done by creating new classes, reusing the
properties of existing once. The mechanism of deriving a new class from an old
one is called inheritance, the old class is known as the base class, superclass or
parent class and the new one is called the sub class, derived class or child class.
Types of Inheritance:
1. Single Inheritance [ Only one super].
2. Multiple Inheritance [Several Super classes].
3. Multi-level Inheritance: [ Derived from a derived class]
Class A
Class B
Class C
Class B
Class C
Class B
Class A
Class A
8. 4. Hierarchical Inheritance: [ one super class many sub class]
Hybrid is a combination of Multi-level and Multiple Inheritance, Java
doesn’t directly implement multiple inheritance however their concept is
implemented using a secondary inheritance path in the form of interfaces.
1. Single InheritanceExample : In the following example the class
arithmetic derived from Data class.
class Data{
int a,b;
void getData(int a,int b){
this.a = a;
this.b = b;
}
void putData(){
System.out.println("A : "+this.a+"t B : "+this.b);
}
Class B Class C Class D
Class A
9. }
class Arithmetic extends Data{
void addition(){
System.out.println("A + B ="+(a+b));
}
void subtraction(){
System.out.println("A - B ="+(a-b));
}
}
public class NewClass{
public static void main(String arsg[]){
Arithmetic ob = new Arithmetic();
ob.getData(345,34);
ob.putData();
ob.addition();
ob.subtraction();
}
}
The output for the above program is:
A : 345 B : 34
A + B =379
A - B =311
10. 2. Multi-level Inheritance:In the following example the class
Grade derived from class MarksResult and class MarksResult derived
from class Data.
class Data{
int age,sub1,sub2,sub3;
String name,section;
void getData(int age,int sub1,int sub2,int sub3,String name,String
section)
{
this.age=age;
this.sub1 = sub1;
this.sub2 = sub2;
this.sub3 = sub3;
this.name = name;
this.section = section;
}
void printData(){
System.out.println("Name : "+name);
System.out.println("Section : "+section);
System.out.println("Age : "+age);
System.out.println("Sub1 : "+sub1);
System.out.println("Sub2 : "+sub2);
System.out.println("Sub3 : "+sub3);
}
}
class MarksResult extends Data{
int total;
float average;
void marksResult(){
total = sub1+sub2+sub3;
11. average = total/3;
System.out.println("Total : "+total);
System.out.println("Average : "+average);
}
}
class Grade extends MarksResult{
String grade;
void grade(){
if(average>=60 && average<=100)
grade = "A";
else if(average>=50 && average<=40)
grade = "B";
else grade="Failed";
System.out.println("Grade : "+grade);
}
}
public class NewClass{
public static void main(String arsg[]){
Grade ob = new Grade();
ob.getData(23, 67, 78, 90,"Ahmad Shah", "B5");
ob.printData();
ob.marksResult();
ob.grade();
}
}
The output for the above program is:
Name : Ahmad Shah
12. Section : B5
Age : 23
Sub1 : 67
Sub2 : 78
Sub3 : 90
Total : 235
Average : 78.0
Grade : A
3. Hierarchical Inheritance: in the following example the Square,
Rectangle and Triangle classes are derived from Data class.
class Data{
int width,length;
String Box;
void getData(int width,int length){
this.width = width;
this.length = length;
}
}
class Square extends Data{
void squareArea(){
System.out.println("Square Area is : "+(this.width*this.width));
}
}
class Rectangle extends Data{
void rectangleArea(){
System.out.println("Rectangle Area is : "+(this.width*this.length));
}
}
class Traingle extends Data{
void traingleArea(){
13. System.out.println("Traingle Area is :
"+((this.width*this.length)/2));
}
}
public class NewClass{
public static void main(String arsg[]){
Traingle traingle = new Traingle();
Square square = new Square();
Rectangle rectangle = new Rectangle();
traingle.getData(10,30);
square.getData(34, 89);
rectangle.getData(20,30);
traingle.traingleArea();
square.squareArea();
rectangle.rectangleArea();
}
}
The output of the above program is:
Traingle Area is : 150
Square Area is : 1156
Rectangle Area is : 600
Methods Overriding
In java we can re-define methods in subclass that already has been
defined in super class, this concept is called method overriding, and
then the objects of base class can only access the method that has been
re-defined in subclass.
14. Example: In the following program the method has been redefined
inside class Arithmetic so the object of sub class (class Arithmetic) will
only access the re-defined method.
class Data{
int a,b;
void getData(int a,int b){
this.a = a;
this.b = b;
}
void putData(){
System.out.println("A : "+this.a+"tB : "+this.b);
}
void operation(){
System.out.println("Addition : "+(this.a+this.b));
}
}
class Arithmetic extends Data{
void operation(){
System.out.println("Multiplication : "+(this.a*this.b));
System.out.println("Division : "+(this.a/this.b));
}
}
public class NewClass{
public static void main(String arsg[]){
Arithmetic ob = new Arithmetic();
ob.getData(90, 10);
ob.putData();
ob.operation();
}
}
Output of the above program is:
A : 90 B : 10
15. Multiplication : 900
Division : 9
Sub Class Constructors
A sub class constructor is used to construct the instance variables of
both the sub classes and the superclass, the subclass constructor uses
the keyword super to invoke the constructor method of the super class.
The keyword super is used to subject the following conditions:
Super may only be used within a subclass constructor
method.
The call to the super class constructor must appear as the
first statement within the subclass constructor.
The parameters in the superclass must match the order
and the type of the instance variable declared in the
superclass.
class Data {
String fname,lname,section;
Data(String fname,String lname,String section){
this.fname = fname;
this.lname = lname;
this.section = section;
}
}
class Marks extends Data{
int sub1,sub2,sub3;
16. Marks(String fname,String lname,String section,int sub1,int
sub2,int sub3){
super(fname,lname,section);
this.sub1 = sub1;
this.sub2 = sub2;
this.sub3 = sub3;
}
void printData(){
System.out.println("Records of "+fname+" "+lname+" in section
"+section+" is : ");
System.out.println("Sub1 : "+sub1+"tSub2 : "+sub2+"tSub3 :
"+sub3);
}
}
public class NewClass{
public static void main(String arsg[]){
Marks ob = new Marks("Ahmad","Mohammadi","B4",56,34,78);
ob.printData();
}
}
The output for the above program is:
Records of Ahmad Mohammadi in section B4 is :
Sub1 : 56 Sub2 : 34 Sub3 : 78
Final methods and Variables
All methods and variables can be overridden by default in subclass, if you wish to
prevent the subclasses from overriding the members of the superclass, we
should declare them as final using the keyword final as a modifier.
Ex:
17. Final int size = 100;
Final void showStatus(){
}
Making a method final insures that the functionality defined in this method will
never be altered in any way, similarly the value of a final variable can never be
changed.
class Message{
final int a = 10;
final void message(){
System.out.println("This is a final method");
}
}
class Marks extends Message{
void message(){
System.out.println("The final method is overridden");
}
}
public class NewClass{
public static void main(String arsg[]){
Marks ob = new Marks();
ob.message();
}
}
18. The above program will produce error, because the method message has defined
as a final in Message class and cannot be overridden in Marks class.
Final Class
Sometimes we may like to prevent a class being inherited, for security reason a
class that cannot be inherited is called final class, this is achieved in java using the
keyword final.
final class Data {
int a,b;
void getData(int a,int b){
this.a = a;
this.b = b;
}
void putData(){
System.out.println("A : "+a+"tB : "+b);
}
}
class Operation extends Data{
void addition(){
System.out.println("Addition : "+(a+b));
}
}
public class NewClass{
public static void main(String args[])
{
Operation ob = new Operation();
19. ob.getData(45, 23);
ob.putData();
ob.addition();
}
}
In the above program the class Data declared as final and cannot be inherited in
anyway, so the program will not be run successfully and will produce an error.
Abstract method and classes
By making a method final we insure that the method is not redefine in a subclass
that is the method can never be subclasses. Java allows us to do something that
is exactly opposite to this, that is we can indicate that a method must always be
redefined in a subclass thus making overriding compulsory. This is done using the
modifier keyword abstract in the method definition.
Syntax:
Abstract class class_name {
………
Abstract void method_name();
…………..
}
20. When a class contains one or more abstreact methods it should always be
declared abstract, while using abstract classes, we must satisfy the following
conditions:
We cannot use abstract classes to instantiate objects
directly.
The abstract method s of an abstract class must be defined
in its subclass we cannot declare abstract constructor or
abstract static methods.
Ex:
abstract class A{
abstract void message();
void display(){
System.out.println("Display : This method has been declared inside class A");
}
}
class B extends A{
void message(){
System.out.println("Message : The abstract method has been redefined");
}
}
public class NewClass{
public static void main(String args[]){
B ob = new B();
ob.message();
ob.display();
}
21. }
Output of the above program is:
Message : The abstract method has been redefined
Display : This method has been declared inside class A
Interface (Multiple Inheritance)
Multiple inheritance proves a difficult and adds complexity to the language, java
provides an alternate approach known as interfaces to support the concept of
multiple inheritances, although a java class cannot be a subclass of more than
one superclass, it can implement more than one interface there by enabling us to
create classes that build upon other classes without the problems created by
multiple inheritance.
Defining interfaces: an interfaces is basically a kind of class, like classes,
interfaces contain methods and variables but with a major defines only abstract
methods and final fields this means that interfaces do not specify an code to
implement these methods and data fields contains only constants, therefor it is
the responsibility of the class that implements an interface to define the code for
implementation of this method.
Syntax:
Interface interfacename {
Variables declaration;
Methods declaration;
}
Ex:
22. interface Area{
final float pi = 3.14f;
float compute(float x,float y);
}
class Rectangle implements Area{
public float compute(float x,float y){
return (x*y);
}
}
class Circle implements Area{
public float compute(float x,float y){
return pi*x*y;
}
}
public class JavaApplication2 {
public static void main(String[] args) {
Rectangle obj1 = new Rectangle();
Circle obj2 = new Circle();
System.out.println("The area of Rectangle is : "+obj1.compute(34, 23));
System.out.println("The area of Circle is : "+obj2.compute(12, 90));
}
}
Output:
23. The area of Rectangle is : 782.0
The area of Circle is : 3391.2
Visibility Control
We stated earlier that it is possible to inherit all the members of the class by a
subclass using the keyword extends, we have also seen that the variables and
methods of the class are visible everywhere in the program however it may be
necessary in some situation to restrict the access to certain variables and
methods from outside the class.
We can achieve this in java by applying visibility modifiers to the instance
variables and methods, the visibility modifiers are known as access modifiers,
three types of visibility modifiers are provided by Java, public private and
protected.
The provide different limits of protections as described:
Public access:
Any variable or method is visible to the entire class in which it is defined, what if
you want to make it visible to all the classes outside this class? This is possible by
simply declaring the variable or method as public.
A variable or method declared as public has the widest possible visibility and
accessible everywhere, in fact this is what we would like to prevent in many
programs this takes us to the next level of protection.
Friendly Access:
In many of our previous example we have not use public modifiers, yet they were
still accessible in other classes in the program, when no access modifier is
specified the member default to a limited version of public accessibility known as
24. friendly level of Access, the difference between the public access and friendly
access is that the public modifier makes field visible in all classes regardless of
their packages while the friendly access makes fields visible only in same package
but not in other packages. A package is a group of related classes stored
separately, a package in java is similar to a source file in c, c++.
Protected access:
The visibility level of protected field lies in between public access and friendly
access, that is that protected modifier makes the fields visible not only to all
classes and sub classes in the same package but also to subclasses in other
packages, non-subclasses in other packages cannot access the protected variable
or members.
Private Access:
Private fields enjoy the highest degree of protection, they are accessible only
with their own class, they cannot be inherit by subclasses and therefore not
accessible in subclasses, a method declared as private behaves like a method
declared as final, it prevents method from being subclasses also note that we
cannot overwrite a none private method in a subclass and then make it private.
Ex1:
class A{
public int a,b;
public int sum(){
return (a+b);
}
}
public class JavaApplication1 {
public static void main(String arg[]) {
A ob = new A();
ob.a =34;
ob.b =23;
System.out.println("The Sum is : "+ob.sum());
25. }
}
Output of this program is :
The Sum is :57
Ex2:
class A{
private int a,b;
private int sum(){
return (a+b);
}
}
public class JavaApplication1 {
public static void main(String arg[]) {
A ob = new A();
ob.a =34;
ob.b =23;
System.out.println("The Sum is : "+ob.sum());
}
}
This program will generate an error because the private members are not
accessible outside the class.
Ex3:
class A{
protected int a,b;
protected int sum(){
return (a+b);
}
}
public class JavaApplication1 {
26. public static void main(String arg[]) {
A ob = new A();
ob.a =34;
ob.b =23;
System.out.println("The Sum is : "+ob.sum());
}
}
The output of this program is :
The Sum is :57
Note:
We will discuss some built in methods used generally in Java.
String functions:
Methods Call Task Performed by method
S2 = s1.toLowerCase(); Converts the string s1 to all lower case
S2 = s1.toUpperCase(); Converts the String s1 to all Upper Case
S2 = s1.trime(); Removes white spaces at the beginning and end of
the String s1
S2 = s1.replace(‘x’,’y’); Replace all appearances of x with y
S1.equals(s2); Returns true if s1 is equal to s2
S1.equalIgnoreCase(s2); Returns true if s1 equal to s2 ignoring the case of
characters.
S1.length() Gives the length of s1
S1.charAt(n); Gives the nth character of s1.
S1.compareTo(s2); Returns negative if s1 is lesser than s2, returns
positive if s1 is greater than s2 and zero if s1==s2
S1.concat(s2); Concatenate s1 & s2
S1.subString(n); Gives the substring starting from nth character
27. S1.subString(n,m); Give the substring starting from nth character up to
mth not including mth.
String.valueOf(p); Creates a string object of a parameter p, or converts
the parameter value to string representation.
p.toString(); Creates a string representation of the object p.
S1.IndexOf(‘x’); Give the position of first accurancey in the string s1.
S1.indexOf(‘x’,’n’); Gives the position of x that occurs after nth position
in the strings.
Ex:
public class JavaApplication1 {
public static void main(String arg[]) {
String s1 = " I am an Student of Computer Science ";
String s2;
System.out.println(s1);
s2 = s1.toUpperCase();
System.out.println(s2);
s2 = s1.toLowerCase();
System.out.println(s2);
s2 = s1.trim();
System.out.println(s2);
s2 = s1.replace('a', 'B');
System.out.println(s2);
28. s2 =s1.substring(10);
System.out.println(s2);
s2=s1.substring(10,20);
System.out.println(s2);
}
}
Output:
The output of the above program is:
I am an Student of Computer Science
I AM AN STUDENT OF COMPUTER SCIENCE
i am an student of computer science
I am an Student of Computer Science
I Bm Bn Student of Computer Science
Student of Computer Science
Student o
Following is a sample program for Math general Math methods used.
import java.lang.Math;
public class NewClass{
public static void main(String args[]){
int a=56;
29. System.out.println("A : "+a);
System.out.println("Absolute value : "+Math.abs(a));
System.out.println("Cosine value : "+Math.cos(a));
System.out.println("Sine value : "+Math.sin(a));
System.out.println("Tangent value : "+Math.tan(a));
System.out.println("Cubic Root : "+Math.cbrt(a));
int b = 23;
System.out.println("B : "+b);
System.out.println("Maximum of A & B : "+Math.max(a, b));
System.out.println("Minimum of A & B : "+Math.min(a, b));
System.out.println("Square Root of A : "+Math.sqrt(a));
System.out.println("Square Root of B : "+Math.sqrt(b));
}
}
Output:
A : 56
Absolute value : 56
Cosine value : 0.853220107722584
Sine value : -0.5215510020869119
Tangent value : -0.6112736881917098
Cubic Root : 3.8258623655447783
B : 23
Maximum of A & B : 56
30. Minimum of A & B : 23
Square Root of A : 7.483314773547883
Square Root of B : 4.795831523312719