Professional Documents
Culture Documents
Java-2
Java-2
public seven() {
num = 25;
}
Output:
Question 8: Add parameterized constructor.
Code:
public class eight {
int num;
Output:
Question 9: Add copy constructor.
Code:
public class nine {
String name;
Output:
Question 10: Create class Vehicle with required methods, parameters and
constructor.
Code:
public class Vehicle {
private String name, color;
private int cost;
// default constructor
public Vehicle() {
name = "None";
color = "None";
cost = 0;
}
// parameterized constructor
public Vehicle(String n, String col, int price) {
name = n;
color = col;
cost = price;
}
// copy constructor
public Vehicle(Vehicle obj) {
name = obj.name;
color = obj.color;
cost = obj.cost;
}
emptyVehicle.setName("Car-1");
emptyVehicle.setColor("Red");
emptyVehicle.setCost(2000000);
System.out.printf("\nValues after setting property values using methods:\nName: %s,\nColor:
%s,\nCost: %d\n", emptyVehicle.name, emptyVehicle.color, emptyVehicle.cost);
copyVehicle.setName("Car-3");
copyVehicle.setColor("Black");
copyVehicle.setCost(4500000);
System.out.printf("\nValues of Copied Object after setting property values using methods:\nName:
%s,\nColor: %s,\nCost: %d\n", copyVehicle.name, copyVehicle.color, copyVehicle.cost);
}
}
Output:
Question 11: Demonstrate use of this keyword.
Code:
public class Fruit {
private String name;
Fruit(String name) {
this.name = name;
}
newPerson.showDiff("Banana");
}
}
Output:
Question 12: WAP to demonstrate parameterized methods (call by value).
Code:
public class Person {
private Double weight;
newPerson.setWeight(62.4);
System.out.printf("The set weight of the person is %.2fkg.", newPerson.weight);
}
}
Output:
Question 13: Write a Person class with an instance variable and a constructor
that takes an integer as a parameter. The constructor must assign after
confirming that the argument passed is not negative. If a negative argument is
passed, the constructor should set the age to 0 and print "Age is not valid."
In addition, you must write the following instance methods:
• yearPasses(): should increase the instance variable by .
• amIOld(): should perform the following conditional actions:
̉• If age < 13, print "You are young."
• If age > 12 and age < 20, print "You are a teenager."
• Otherwise, print "You are old."
Code:
public class Person {
private int age;
// parameterized constructor
public Person(int n) {
if (n < 0) {
age = 0;
System.out.println("The entered age is invalid.");
return;
}
age = n;
}
newPerson.yearPasses();
System.out.printf("\nA year has passed. Your age is now %d.\n", newPerson.age);
newPerson.amIOld();
}
}
Output: