In: Computer Science
Need urgently, please do it as soon as possible i have only 40 min for this task ( Doing in Java).
Question no 1: Solve completely.
a) Define the following concepts with proper syntax, where required. Also, write why we use these concepts (for last three bullets).
Execution process of java program
Copy constructor
Instance and class variable
Access specifiers
b) Write a program to print the area of a rectangle by creating a class named 'Area' having two methods. First method named as 'setDim' takes length and breadth of rectangle as parameters and the second method named as 'getArea' returns the area of the rectangle. Length and breadth of rectangle are passed through constructor.
a) Execution process of java program
Java file (for eg: abc.java) is executed as follows:
Copy constructor
public class Data {
String name;
Data( String d_name)
{
name=d_name;
}
//Creating copy constructor that copies the value of oneobject to another.
Data (Data d)
{
name=d.name;
}
//Printing value
void show()
{
System.out.println(" Name: "+name);
}
public static void main(String[] args) {
Data d1=new Data("abc");
//Passing object as parameter
Data d2= new Data(d1);
d1.show();
d2.show();
}
}
Instance and class variable
Instance variable are declared outside method or constructor but inside a class. Changes in variables by one object doesnot reflect other objects.
Class variable is declared with keyword static but outside constructor or method. Class variable is also called static variable. Changes made in variable by one object may change by other object.
Access Specifier
Regulates the accessibilty of class ,constructor and methods.
Four type of access specifier are:
public: Can be accessed outside the class. Constructor or method can also declared as public.
public class File{// public class
public name; //public instance variable
}
private: Can be accessed within class only. Hide data from outside world as encapsulation.
protected: Can be declared with method or constructor but not in class.
public class File{
protected void show(){
System.out.println("abc ");
}
}
default: Can be accessed within package but not outside.
b)
public class Area {
private int len;
private int bd;
//Creating constructor and assigning values
Area(int length, int breadth)
{
len=length;
bd=breadth;
}
//setter to set variables
public void setDim(int length,int breadth)
{
len=length;
bd=breadth;
}
//Function to calculate area of rectangle
public int getArea()
{
return len*bd;
}
public static void main(String[] args) {
//Creating object and passing value to constructor
Area a1=new Area(10,20);
//Printing area by invoking function getArea()
System.out.println("Area of Rectangle is " + a1.getArea());
}
}
Screenshot
Output