I would like to know how this code would look like if it was converted to Java c
ID: 3557376 • Letter: I
Question
I would like to know how this code would look like if it was converted to Java code?
#include
#include
using namespace std;
class Ship
{
private:
string name;
string built;
public:
Ship(string n, string y)
{
name = n;
built = y;
}
string getname()
{
return name;
}
string getbuilt()
{
return built;
}
virtual void print()
{
cout<<"Ship Name : "< }
};
class CargoShip: public Ship //Cargoship is derived from the Ship class
{
private:
int tonnage;
public:
CargoShip(string n, string y, int t) : Ship(n,y)
{
tonnage = t;
}
virtual void print()
{
cout<<"Ship Name : "<< getname() << ", Maximum tonnage: " << tonnage << endl;
}
};
class CruiseShip: public Ship //Cruiseship is also derived from ship class
{
private:
int pass;
public:
CruiseShip(string n, string y, int p) : Ship(n,y)
{
pass=p;
}
virtual void print()
{
cout<<"Ship Name : "<< getname() << ", Maximum number passengers: " << pass << endl;
}
};
int main()
{
cout << "WELCOME TO SHIP INFORMATION!" << endl;
cout << "__________________________________________________" << endl;
Ship *ships[3]= {new Ship("Titanic", "1909"),
new CargoShip("Cargo", "2010", 50000),
new CruiseShip("Cruise Ship", "2014", 500)
};
int i;
for(i = 0; i < 3; i++)
ships[i]->print();
return 0;
}
Explanation / Answer
For This We need 4 class's..... 1.Ship class 2. CargoShip 3.CruiseShip 4.Any TestCase Class.
so in java above programme looks like followong
//Ship.java
public class Ship
{
private String name;
private String built;
public Ship(String n, String y)
{
this.name = n;
this.built = y;
}
public String getName()
{
return name;
}
public String getBuilt()
{
return built;
}
public void print()
{
System.out.println("Ship Name : "+name);
}
}
// CargoShip.java
public class CargoShip extends Ship
{
private int tonnage;
public CargoShip(String n, String y, int t)
{
super(n,y);
tonnage = t;
}
public void print()
{
System.out.println("Ship name : "+getName()+", Maximum tonnage: " +tonnage);
}
}
// CruiseShip.java
public class CruiseShip extends Ship
{
private int pass;
public CruiseShip(String n, String y, int t)
{
super(n,y);
pass = t;
}
public void print()
{
System.out.println("Ship name : "+getName()+", Maximum number of passengers: " +pass);
}
}
// TestCase.java
public class Test
{
public static void main(String[] args)
{
System.out.println("WELCOME TO SHIP INFORMATION!" );
System.out.println("_________________________________");
Ship ships[] = {new Ship("Titanic","1909"),new CargoShip("CargoShip","2010",50000), new CruiseShip("CruiseShip","2014",500};
for(int i = 0; i<sh.length;i++)
{
ships[i].print();
}
}
}
TestCase Results :
Ship name : Titanic
Ship name : CargoShip, Maximum tonanage: 50000
Ship name : CruiseShip, Maximum number of passengers: 500