0% found this document useful (0 votes)
82 views16 pages

Test String: Public Class Public Static Void Int While Out Print Out Print

The document contains examples of different flow control statements in Java like while, for, do-while loops, break and continue statements. It also includes examples demonstrating inheritance, polymorphism, arrays and overriding methods in subclasses. Key concepts covered are invoking parent constructors and methods using super keyword, differentiating members using super, overriding methods, and polymorphic calls depending on reference variable type.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
82 views16 pages

Test String: Public Class Public Static Void Int While Out Print Out Print

The document contains examples of different flow control statements in Java like while, for, do-while loops, break and continue statements. It also includes examples demonstrating inheritance, polymorphism, arrays and overriding methods in subclasses. Key concepts covered are invoking parent constructors and methods using super keyword, differentiating members using super, overriding methods, and polymorphic calls depending on reference variable type.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 16

Flow Controls Samples

WHILE CONDITION

public class Test {

public static void main(String args[]) {


int x = 10;

while( x < 20 ) {
System.out.print("value of x : " + x );
x++;
System.out.print("\n");
}
}
}

OUTPUT:
value of x : 10
value of x : 11
value of x : 12
value of x : 13
value of x : 14
value of x : 15
value of x : 16
value of x : 17
value of x : 18
value of x : 19

FOR LOOP CONDITON

public class Test {

public static void main(String args[]) {

for(int x = 10; x < 20; x = x + 1) {


System.out.print("value of x : " + x );
System.out.print("\n");
}
}
}

OUTPUT:
value of x : 10
value of x : 11
value of x : 12
value of x : 13
value of x : 14
value of x : 15
value of x : 16
value of x : 17
value of x : 18
value of x : 19

DO WHILE CONDITION

public class Test {

public static void main(String args[]) {


int x = 10;

do {
System.out.print("value of x : " + x );
x++;
System.out.print("\n");
}while( x < 20 );
}
}

OUTPUT:
value of x : 10
value of x : 11
value of x : 12
value of x : 13
value of x : 14
value of x : 15
value of x : 16
value of x : 17
value of x : 18
value of x : 19
USING BREAK

public class Test {

public static void main(String args[]) {


int [] numbers = {10, 20, 30, 40, 50};

for(int x : numbers ) {
if( x == 30 ) {
break;
}
System.out.print( x );
System.out.print("\n");
}
}
}

OUTPUT:
10
20

USING CONTINUE

public class Test {

public static void main(String args[]) {


int [] numbers = {10, 20, 30, 40, 50};

for(int x : numbers ) {
if( x == 30 ) {
continue;
}
System.out.print( x );
System.out.print("\n");
}
}
}

OUTPUT:
10
20
40
50
ARRAY

public class TestArray {

public static void main(String[] args) {


double[] myList = {1.9, 2.9, 3.4, 3.5};

// Print all the array elements


for (int i = 0; i < myList.length; i++) {
System.out.println(myList[i] + " ");
}

// Summing all elements


double total = 0;
for (int i = 0; i < myList.length; i++) {
total += myList[i];
}
System.out.println("Total is " + total);

// Finding the largest element


double max = myList[0];
for (int i = 1; i < myList.length; i++) {
if (myList[i] > max) max = myList[i];
}
System.out.println("Max is " + max);
}
}

OUTPUT:
1.9
2.9
3.4
3.5
Total is 11.7
Max is 3.5
INHERITANCE

class Calculation {
int z;

public void addition(int x, int y) {


z = x + y;
System.out.println("The sum of the given numbers:"+z);
}

public void Subtraction(int x, int y) {


z = x - y;
System.out.println("The difference between the given
numbers:"+z);
}
}

public class My_Calculation extends Calculation {


public void multiplication(int x, int y) {
z = x * y;
System.out.println("The product of the given numbers:"+z);
}

public static void main(String args[]) {


int a = 20, b = 10;
My_Calculation demo = new My_Calculation();
demo.addition(a, b);
demo.Subtraction(a, b);
demo.multiplication(a, b);
}
}

OUTPUT:

The sum of the given numbers:30


The difference between the given numbers:10
The product of the given numbers:200

In the given program, when an object to My_Calculation class is created, a copy of the
contents of the superclass is made within it. That is why, using the object of the subclass
you can access the members of a superclass.
The Superclass reference variable can hold the subclass object, but using that variable
you can access only the members of the superclass, so to access the members of both
classes it is recommended to always create reference variable to the subclass.
If you consider the above program, you can instantiate the class as given below. But
using the superclass reference variable ( cal in this case) you cannot call the
method multiplication(), which belongs to the subclass My_Calculation.
Calculation demo = new My_Calculation();
demo.addition(a, b);
demo.Subtraction(a, b);
Note − A subclass inherits all the members (fields, methods, and nested classes) from
its superclass. Constructors are not members, so they are not inherited by subclasses,
but the constructor of the superclass can be invoked from the subclass.

The super keyword


The super keyword is similar to this keyword. Following are the scenarios where the
super keyword is used.
 It is used to differentiate the members of superclass from the members of subclass, if they
have same names.
 It is used to invoke the superclass constructor from subclass.

Differentiating the Members


If a class is inheriting the properties of another class. And if the members of the
superclass have the names same as the sub class, to differentiate these variables we
use super keyword as shown below.
super.variable
super.method();
class Super_class {
int num = 20;

// display method of superclass


public void display() {
System.out.println("This is the display method of
superclass");
}
}

public class Sub_class extends Super_class {


int num = 10;

// display method of sub class


public void display() {
System.out.println("This is the display method of subclass");
}

public void my_method() {


// Instantiating subclass
Sub_class sub = new Sub_class();

// Invoking the display() method of sub class


sub.display();

// Invoking the display() method of superclass


super.display();

// printing the value of variable num of subclass


System.out.println("value of the variable named num in sub
class:"+ sub.num);

// printing the value of variable num of superclass


System.out.println("value of the variable named num in super
class:"+ super.num);
}

public static void main(String args[]) {


Sub_class obj = new Sub_class();
obj.my_method();
}
}

OUTPUT:

This is the display method of subclass


This is the display method of superclass
value of the variable named num in sub class:10
value of the variable named num in super class:20
Invoking Superclass Constructor
If a class is inheriting the properties of another class, the subclass automatically acquires
the default constructor of the superclass. But if you want to call a parameterized
constructor of the superclass, you need to use the super keyword as shown below.
super(values);

class Superclass {
int age;

Superclass(int age) {
this.age = age;
}

public void getAge() {


System.out.println("The value of the variable named age in
super class is: " +age);
}
}

public class Subclass extends Superclass {


Subclass(int age) {
super(age);
}

public static void main(String argd[]) {


Subclass s = new Subclass(24);
s.getAge();
}
}

OUTPUT:
The value of the variable named age in super class is: 24

POLYMORPHISM

/* File name : Employee.java */


public class Employee {
private String name;
private String address;
private int number;

public Employee(String name, String address, int number) {


System.out.println("Constructing an Employee");
this.name = name;
this.address = address;
this.number = number;
}

public void mailCheck() {


System.out.println("Mailing a check to " + this.name + " " +
this.address);
}

public String toString() {


return name + " " + address + " " + number;
}

public String getName() {


return name;
}

public String getAddress() {


return address;
}

public void setAddress(String newAddress) {


address = newAddress;
}

public int getNumber() {


return number;
}
}
Now suppose we extend Employee class as follows −
/* File name : Salary.java */
public class Salary extends Employee {
private double salary; // Annual salary

public Salary(String name, String address, int number, double


salary) {
super(name, address, number);
setSalary(salary);
}

public void mailCheck() {


System.out.println("Within mailCheck of Salary class ");
System.out.println("Mailing check to " + getName()
+ " with salary " + salary);
}
public double getSalary() {
return salary;
}

public void setSalary(double newSalary) {


if(newSalary >= 0.0) {
salary = newSalary;
}
}

public double computePay() {


System.out.println("Computing salary pay for " + getName());
return salary/52;
}
}
Now, you study the following program carefully and try to determine its output −
/* File name : VirtualDemo.java */
public class VirtualDemo {

public static void main(String [] args) {


Salary s = new Salary("Mohd Mohtashim", "Ambehta, UP", 3,
3600.00);
Employee e = new Salary("John Adams", "Boston, MA", 2,
2400.00);
System.out.println("Call mailCheck using Salary reference --
");
s.mailCheck();
System.out.println("\n Call mailCheck using Employee
reference--");
e.mailCheck();
}
}

OUTPUT:

Constructing an Employee
Constructing an Employee

Call mailCheck using Salary reference --


Within mailCheck of Salary class
Mailing check to Mohd Mohtashim with salary 3600.0

Call mailCheck using Employee reference--


Within mailCheck of Salary class
Mailing check to John Adams with salary 2400.0
ABSTRACTION

/* File name : Employee.java */


public abstract class Employee {
private String name;
private String address;
private int number;

public Employee(String name, String address, int number) {


System.out.println("Constructing an Employee");
this.name = name;
this.address = address;
this.number = number;
}

public double computePay() {


System.out.println("Inside Employee computePay");
return 0.0;
}

public void mailCheck() {


System.out.println("Mailing a check to " + this.name + " " +
this.address);
}

public String toString() {


return name + " " + address + " " + number;
}

public String getName() {


return name;
}

public String getAddress() {


return address;
}

public void setAddress(String newAddress) {


address = newAddress;
}

public int getNumber() {


return number;
}
}
You can observe that except abstract methods the Employee class is same as normal
class in Java. The class is now abstract, but it still has three fields, seven methods, and
one constructor.
Now you can try to instantiate the Employee class in the following way −
/* File name : AbstractDemo.java */
public class AbstractDemo {

public static void main(String [] args) {


/* Following is not allowed and would raise error */
Employee e = new Employee("George W.", "Houston, TX", 43);
System.out.println("\n Call mailCheck using Employee
reference--");
e.mailCheck();
}
}

When you compile the above class, it gives you the following error −
Employee.java:46: Employee is abstract; cannot be instantiated
Employee e = new Employee("George W.", "Houston, TX", 43);
^
1 error

INHERITING THE ABSTRACT CLASS

/* File name : Salary.java */


public class Salary extends Employee {
private double salary; // Annual salary

public Salary(String name, String address, int number, double


salary) {
super(name, address, number);
setSalary(salary);
}

public void mailCheck() {


System.out.println("Within mailCheck of Salary class ");
System.out.println("Mailing check to " + getName() + " with
salary " + salary);
}

public double getSalary() {


return salary;
}
public void setSalary(double newSalary) {
if(newSalary >= 0.0) {
salary = newSalary;
}
}

public double computePay() {


System.out.println("Computing salary pay for " + getName());
return salary/52;
}
}
Here, you cannot instantiate the Employee class, but you can instantiate the Salary
Class, and using this instance you can access all the three fields and seven methods of
Employee class as shown below.
/* File name : AbstractDemo.java */
public class AbstractDemo {

public static void main(String [] args) {


Salary s = new Salary("Mohd Mohtashim", "Ambehta, UP", 3,
3600.00);
Employee e = new Salary("John Adams", "Boston, MA", 2,
2400.00);
System.out.println("Call mailCheck using Salary reference --
");
s.mailCheck();
System.out.println("\n Call mailCheck using Employee
reference--");
e.mailCheck();
}
}

OUTPUT:
Constructing an Employee
Constructing an Employee
Call mailCheck using Salary reference --
Within mailCheck of Salary class
Mailing check to Mohd Mohtashim with salary 3600.0

Call mailCheck using Employee reference--


Within mailCheck of Salary class
Mailing check to John Adams with salary 2400.0
Abstract Methods
If you want a class to contain a particular method but you want the actual implementation
of that method to be determined by child classes, you can declare the method in the
parent class as an abstract.
 abstract keyword is used to declare the method as abstract.
 You have to place the abstract keyword before the method name in the method declaration.
 An abstract method contains a method signature, but no method body.
 Instead of curly braces, an abstract method will have a semoi colon (;) at the end.
Following is an example of the abstract method.

public abstract class Employee {


private String name;
private String address;
private int number;

public abstract double computePay();


// Remainder of class definition
}

Declaring a method as abstract has two consequences −


 The class containing it must be declared as abstract.
 Any class inheriting the current class must either override the abstract method or declare itself
as abstract.
Note − Eventually, a descendant class has to implement the abstract method; otherwise,
you would have a hierarchy of abstract classes that cannot be instantiated.
Suppose Salary class inherits the Employee class, then it should implement
the computePay() method as shown below −
/* File name : Salary.java */
public class Salary extends Employee {
private double salary; // Annual salary

public double computePay() {


System.out.println("Computing salary pay for " + getName());
return salary/52;
}
// Remainder of class definition
}
Encapsulation is one of the four fundamental OOP concepts. The other three are
inheritance, polymorphism, and abstraction.
Encapsulation in Java is a mechanism of wrapping the data (variables) and code acting
on the data (methods) together as a single unit. In encapsulation, 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.
/* File name : EncapTest.java */
public class EncapTest {
private String name;
private String idNum;
private int age;

public int getAge() {


return age;
}

public String getName() {


return name;
}

public String getIdNum() {


return idNum;
}

public void setAge( int newAge) {


age = newAge;
}

public void setName(String newName) {


name = newName;
}

public void setIdNum( String newId) {


idNum = newId;
}
}

The public setXXX() and getXXX() methods are the access points of the instance
variables of the EncapTest class. Normally, these methods are referred as getters and
setters. Therefore, any class that wants to access the variables should access them
through these getters and setters.
The variables of the EncapTest class can be accessed using the following program −
/* File name : RunEncap.java */
public class RunEncap {

public static void main(String args[]) {


EncapTest encap = new EncapTest();
encap.setName("James");
encap.setAge(20);
encap.setIdNum("12343ms");

System.out.print("Name : " + encap.getName() + " Age : " +


encap.getAge());
}
}

OUTPUT:

Name : James Age : 20

You might also like