question archive create a class Android whose objects have unique data
Subject:Computer SciencePrice:2.84 Bought3
create a class Android whose objects have unique data. The class has the following
attributes:
tag—a static integer that begins at 1 and changes each time an instance is created
name—a string that is unique for each instance of this class
Android has the following methods:
Android—a default constructor that sets the name to "Bob" concatenated with the value
of tag. After setting the name, this constructor changes the value of tag by calling the
private method changeTag.
getName—returns the name portion of the invoking object.
isPrime(n)—a private static method that returns true if n is prime—that is, if it is not
divisible by any number from 2 to n − 1.
changeTag—a private static method that replaces tag with the next prime number
larger than the current value of tag.
class Android { static int tag = 1; String name; public Android() { name = "Bob" + tag; changeTag(); } public String getName() { return name; } public static boolean isPrime(int num) { if (num <= 1) { return false; } for (int i = 2; i <= Math.sqrt(num); i++) { if (num % i == 0) { return false; } } return true; } private static void changeTag() { int current = tag; do { current = current + 1; } while (!isPrime(current)); tag = current; } }
Step-by-step explanation
Android Class (add public if you will save it in a separate file)
class Android { static int tag = 1; String name; public Android() { name = "Bob" + tag; changeTag(); } public String getName() { return name; } public static boolean isPrime(int num) { if (num <= 1) { return false; } for (int i = 2; i <= Math.sqrt(num); i++) { if (num % i == 0) { return false; } } return true; } private static void changeTag() { int current = tag; do { current = current + 1; } while (!isPrime(current)); tag = current; } }
This is the Main class with the main method with sample instances of Android Class
public class Main { public static void main(String[] args) { Android a1 = new Android(); Android a2 = new Android(); Android a3 = new Android(); Android a4 = new Android(); Android a5 = new Android(); System.out.println(a1.getName()); System.out.println(a2.getName()); System.out.println(a3.getName()); System.out.println(a4.getName()); System.out.println(a5.getName()); } }
If you will put both the codes in a class - Main.java
If you will run the code, this will be the output:
Bob1 Bob2 Bob3 Bob5 Bob7