Showing posts with label class. Show all posts
Showing posts with label class. Show all posts

Wednesday, October 28, 2015

Inheritance with Java GUI

Prepare a input form which will take 2 input for range of values. After getting input from the user, find sum of all primes from the given range using a button named Generate-Sum. After getting the sum check whether the sum is even or not.  All the process will be done by a class followed by Inheritance in Java. You have to display the output in a label at Form.

Inheritance in Java Programming

Inheritance in java is a mechanism in which one object acquires all the properties and behaviors of parent object.
The idea behind inheritance in java is that you can create new classes that are built upon existing classes. When you inherit from an existing class, you can reuse methods and fields of parent class, and you can add new methods and fields also.
Inheritance represents the IS-A relationship, also known as parent-child relationship.

Why use inheritance in java

  • For Method Overriding (so runtime polymorphism can be achieved).
  • For Code Reusability.

Syntax of Java Inheritance

  1. class Subclass-name extends Superclass-name  
  2. {  
  3.    //methods and fields  
  4. }  
The extends keyword indicates that you are making a new class that derives from an existing class.
In the terminology of Java, a class that is inherited is called a super class. The new class is called a subclass.

Understanding the simple example of inheritance

 inheritance in java

 As displayed in the above figure, Programmer is the subclass and Employee is the superclass. Relationship between two classes is Programmer IS-A Employee.It means that Programmer is a type of Employee.
  1. class Employee{  
  2.  float salary=40000;  
  3. }  
  4. class Programmer extends Employee{  
  5.  int bonus=10000;  
  6.  public static void main(String args[]){  
  7.    Programmer p=new Programmer();  
  8.    System.out.println("Programmer salary is:"+p.salary);  
  9.    System.out.println("Bonus of Programmer is:"+p.bonus);  
  10. }  
  11. }  


 Programmer salary is:40000.0
 Bonus of programmer is:10000

In the above example, Programmer object can access the field of own class as well as of Employee class i.e. code reusability.

Types of inheritance in java

On the basis of class, there can be three types of inheritance in java: single, multilevel and hierarchical.
In java programming, multiple and hybrid inheritance is supported through interface only. We will learn about interfaces later.
types of inheritance in java

 

Note: Multiple inheritance is not supported in java through class.

When a class extends multiple classes i.e. known as multiple inheritance. For Example:
multiple inheritance in java

Why multiple inheritance is not supported in java?

To reduce the complexity and simplify the language, multiple inheritance is not supported in java.
Consider a scenario where A, B and C are three classes. The C class inherits A and B classes. If A and B classes have same method and you call it from child class object, there will be ambiguity to call method of A or B class.
Since compile time errors are better than runtime errors, java renders compile time error if you inherit 2 classes. So whether you have same method or different, there will be compile time error now.
  1. class A{  
  2. void msg(){System.out.println("Hello");}  
  3. }  
  4. class B{  
  5. void msg(){System.out.println("Welcome");}  
  6. }  
  7. class C extends A,B{//suppose if it were  
  8.  Public Static void main(String args[]){  
  9.    C obj=new C();  
  10.    obj.msg();//Now which msg() method would be invoked?  
  11. }  
  12. }  

Compile Time Error

Tuesday, October 20, 2015

Simple Interest Calculation using jframe(Java GUI)

Write a Java program to calculate a simple interest. This program must be focused on an object oriented approach.

video tutorial link: video

N.B. : Java source code is case sensitive
Source code:  java_simple_interest . java

package java_simple_interest;
//class
class simple_interest
{
    //instance variable
    float principal_amount;
    float year_of_interest;
    float rate_of_interest;
    //method with arguments and return type
    float si(float pa, float yi, float ri)
    {
        return pa*yi*ri;
    }
}

Source Code: calculate_simple_interest . java

(Source code under action button ( jButton1 ))

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                        
       

 // TODO add your handling code here:
        //create object
        simple_interest si =new simple_interest();
        //instance variable getting value from text box
        si.year_of_interest=Float.parseFloat(yoi.getText());
        si.rate_of_interest=Float.parseFloat(roi.getText());
        si.principal_amount=Float.parseFloat(pa.getText());
        //method si called by object si
        jLabel4.setText ("Your Payable interest  is: " + si.si(si.year_of_interest,si.rate_of_interest ,si.principal_amount ));
       
    }          


Sunday, March 22, 2015

Sum and Count of Prime Number With Method and Parameter

Write a Java program to calculate the SUM and COUNT of Primes from a given range of numbers. Formatting required for the Input and Output statements. Use Method with Parameter and return value to the Main function.

Reference:
(1) Course Book(The Complete Reference Java j2se) ; Page 116
(2) http://c-programming-sourcecode.blogspot.com/2012/08/prime-number.html?updated-min=2012-01-01T00:00:00-08:00&updated-max=2013-01-01T00:00:00-08:00&max-results=14


Source Code:

package Prime;
import java.util.Scanner;
class PrimeCheeck
{
int sum=0;
int get_Prime_Sum(int range)
{
for(int i=1;i<=range;i++)
{
int flag=0;
for(int j=2;j<i;j++)
{
if(i%j==0)
flag=1;
}
if(flag==0)
{
System.out.print(i+" ");
sum=sum+i;
}

}
System.out.println();
return sum;
}
}
public class Prime {
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);

PrimeCheeck pr =new PrimeCheeck();
int range,result;
System.out.print("Enter your last Range : ");
range = in.nextInt();
System.out.println("Sum of all prime number giving in range = " +pr.get_Prime_Sum(range));
}
}

Reverse an Integer Number


Write a Java program to reverse an Integer number. After print the output, make the sum of all digits. Use Method. Do not use parameter. Return value from Method to the Main function.


Reference:
(1) Course Book (The Complete Reference Java j2se) ; Page 114
(2) http://c-programming-sourcecode.blogspot.com/2012/08/integer-number.html?updated-min=2012-01-01T00:00:00-08:00&updated-max=2013-01-01T00:00:00-08:00&max-results=14

Source Code:

package ReverseNumber;
import java.util.Scanner;

class Reversnum
{
int number;
int sum=0;
int reverse(){
int reverse = 0;
int remainder = 0;
do{
remainder = number%10;
reverse = reverse*10 + remainder;
number = number/10;
sum=sum+reverse;
}while(number > 0);

return reverse;
}
int getsum()
{
return sum;
}
}

public class ReverseNumber
{
public static void main(String args[]) {
Scanner input =new Scanner(System.in);
Reversnum r =new Reversnum();
int number;
System.out.println("Please enter number to be reversed using Java program: ");
r.number = input.nextInt();
int a = r.reverse();
System.out.println("After Reverse : "+a);
System.out.println("Sum of : "+r.getsum());
}
}

Java Calculator using instance variable

Design and Write  a simple java class program which can perform all basic operation of a Calculator. Define necessary instance variable but do not use method.

Reference:
1. http://c-programming-sourcecode.blogspot.com/2012/06/write-program-performing-as-calculator.html?q=simple+interest

2. Course Book(The Complete Reference Java j2se) ; Page 106

Source Code:

package calculator_shohan;
import java.util.Scanner;
import java.io.*;
public class Calculator_shohan {
public static void main(String[] args) {
calculator_ c=new calculator_();
int num1=0,num2=0;
Scanner input=new Scanner(System.in);
System.out.println("Enter the first number:");
num1=input.nextInt();
System.out.println("Enter the second number:");
num2=input.nextInt();
c.cal(num1, num2);
}

}
class calculator_
{
int add=0,sub=0,div=0,mul=0,mod=0;
public void cal(int x,int y)
{
Scanner input=new Scanner(System.in);

char ch;
System.out.println("Enter your choice:");
System.out.println("Addition for + :");
System.out.println("Subtraction for - :");
System.out.println("Multiplication for * :");
System.out.println("Divition for /:");
System.out.println("Modulation for %:");
ch=input.next().charAt(0);
switch(ch)
{
case '+':
System.out.println(x+y);
break;

case '-':
System.out.println(x-y);
break;

case '*':
System.out.println(x*y);
break;
case '/':
System.out.println(x/y);
break;
case '%':
System.out.println(x%y);
break;
default:
System.out.println("no choice");
}
}
}

Wednesday, March 4, 2015

Class with Instance and Method

Write a program where you have to assign a class called Circle is to be defined as illustrated in the class diagram below. It contains two variables: radius (of type double) and color (of type String); and three methods: getRadius(), getColor(), and getArea().
Three instances of Circles called c1, c2, and c3 shall then be constructed with their respective data members, as shown in the instance diagrams.

Source Code:

package crl;
class circle
{
double radius;
String colour;
circle(double r,String c)
{
radius=r;
colour=c;
}
double getRadius()
{
return radius;
}
String getColour()
{
return colour;
}
double getArea()
{
return 3.1416*radius*radius;
}
}
public class CRL
{
public static void main(String[] args)
{
circle c1=new circle(3.4,"Pink");
circle c2=new circle(1.1,"white");
circle c3=new circle(1.1,"blue");
System.out.println("Radius :"+c1.getRadius() + "Colour :"+c1.getColour()+"Area:"+c1.getArea());
System.out.println("Radius :"+c2.getRadius() + "Colour :"+c2.getColour()+"Area:"+c2.getArea());
System.out.println("Radius :"+c3.getRadius() + "Colour :"+c3.getColour()+"Area:"+c3.getArea());
}
}

Tuesday, December 10, 2013

Method with return type in JAVA : Day 4



a) How Method return a value? Write necessary Syntax.

b) Write any JAVA program that takes parameters in a Method.

Method in JAVA : Day 3

a) How to access the instance variable using Method?


b) Write a program to calculate the Volume of a Box using Method.

Sunday, December 8, 2013

Object in JAVA : Day 2


a) What is Object? How to declare an Object in a JAVA program? Explain the Syntax of Object Declaration.

b) Write Syntax to assign an Object Reference Variable.

Friday, December 6, 2013

Class in JAVA : Day 1


  Explain the General Form of a Class.   --------------------------------------------------------------------------------------------------------------------------
Write a program to find the volume of a Box. Define only three instance variables: width, height and depth. Do not use Methods.
-----------------------------------------------------------------------------------------------------------------------------
package volbox;
class Bigbox
{
   double width;
   double depth;
   double height;
}
public class Volbox
{
  public static void main(String[] args)
  {
    Bigbox lbox=new Bigbox();
    lbox.width=15;
    lbox.depth=8;
    lbox.height=20;
    double vol=lbox.width * lbox.depth * lbox.height;
    System.out.println("Volume of box is:" +vol);
  }
}

Tuesday, April 16, 2013

Greatest Common Divisor or GCD : JAVA OOP

Write Java Source Code on Printing the Greatest Common Divisor or GCD in Recursion

Sample Output:
Enter the base number: 100
Enter the power: 45
The GCD of 2 numbers is: 5

Source Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
//java class
public class GCD
{
    public static int gcd(int num1, int num2)
    {
        if(num2 == 0)
        {
            return num1;
        }
        else
        {
            return gcd(num2, num1%num2);
        }
    }
}
//main class
import java.util.Scanner;
public class Main
{
    public static void main(String[] args)
    {
       Scanner input = new Scanner(System.in);
      System.out.print("Enter the base number: ");
      int num1 = input.nextInt();
      System.out.print("Enter the power: ");
      int num2 = input.nextInt();
      GCD access = new GCD();
      System.out.print("The GCD of 2 numbers is: " + access.gcd(num1, num2));
    }
}