Question

1. What is an abstract method and why are they useful? Illustrate your answer using an...


1. What is an abstract method and why are they useful? Illustrate your answer using an example of where you might use an abstract method.
2. What is the difference between a static variable and a non-static variable? Given the example of a class representing Dogs, give an example of a variable that may be static and another that may non-static.
3. In Java, when you modify a String as shown in the code below, Java makes a new String to contain the result, rather than just adding the item onto the end of the original String. Why does it do this?
String s="Hello";
s = s + ", Pravesh";
4. Explain why the following code returns John, despite Java using pass by reference.
Describe what happens in memory, describing each object created, whether the name points directly to the value or to a pointer to the value, what item is sent to the method, etc.
public static void main(String args[]){
String k = "John";
change(k);
System.out.println(k);
}
public static void change(String k){
k = "Mike";
}

5.An evil jailer has presented two prisoners with a problem. He will put a hat on each of their heads, with each hat being either black or white. There is no other restriction on the hat choice, so the hats could be the same colour or different colours. The jailer will free both prisoners if either prisoner correctly guesses his own hat colour. Note that this means the other prisoner can get his hat colour wrong and still be freed. Each prisoner can see the other ones hat colour but not his own. Before the game starts, the prisoners are allowed to discuss a strategy for guessing.


Find a strategy they can agree on that always gets the prisoners freed in each of the following two scenarios:
(a) Theyareallowedtoguessinturnandthesecondprisonercanhearthefirstprisonersguess. [2 marks]
(b) They must guess simultaneously and so have no information about each others guess. [3 marks]

0 0
Add a comment Improve this question Transcribed image text
Answer #1

1. What is an abstract method and why are they useful? Illustrate your answer using an example of where you might use an abstract method.

Answer: A method without a body or with no implementation is known as an abstract method. An abstract method must always be declared in an abstract class or interface in JAVA, or in other words, you can say that if a class has an abstract method, it should be declared abstract as well. This is how an abstract method looks in java:

example of an abstract method:

public abstract int sum(int n1, int n2);

Sometimes you will want to create a superclass that only defines a generalized form that will be shared by all of its subclasses, leaving it to each subclass to fill in the details. Such a class determines the nature of the methods that the subclasses must implement.

Below example illustrate where we might use an abstract method.

Suppose we were modeling the behavior of animals, by creating a class hierarchy that started with a base class called Animal. Animals are capable of doing different things like flying, digging and walking, but there are some common operations as well as eating and sleeping and making noise. Some common operations are performed by all animals, but in a different way as well. When an operation is performed in a different way, it is a good candidate for an abstract method (forcing subclasses to provide a custom implementation). Let's look at a very primitive Animal base class, which defines an abstract method makenoise() for making a sound (such as a dog barking, a cow mooing, or a pig oinking).

public abstract Animal {

public void sleep{

// sleeping time

}

public void eat(food)

{

//eat something

}

public abstract void makeNoise();

}

public Dog extends Animal {

public void makeNoise() {

System.out.println("Bark! Bark!");

}

}

public Cow extends Animal {

public void makeNoise() {

System.out.println("Moo! Moo!");

}

}

Q2. What is the difference between a static variable and a non-static variable? Given the example of a class representing Dogs, give an example of a variable that may be static and another that may non-static.

Answer:

Non-static variable Static variable These variables are preceded by static keyword These variable should not be preceded by a

class Dogs
{
String name;
int age;
static String Breed_name="BullDog";
}
class StaticDemo
{
public static void main(String args[])
{
Dogs d1=new Dogs();
d1.age=100;
d1.name="Michal";
System.out.println(d1.age);
System.out.println(d1.name);
System.out.println(Dogs.Breed_name); 
//or System.out.println(d1.Breed_name); but first is use in real time.
Dogs  d2=new  Dogs();
d2.age=200;
d2.name="zyx";
System.out.println(d2.age);
System.out.println(s2.name);
System.out.println(Dogs.Breed_name); 
}
}

Q3. In Java, when you modify a String as shown in the code below, Java makes a new String to contain the result, rather than just adding the item onto the end of the original String. Why does it do this?

String s="Hello";

s = s + ", Pravesh";

Answer: In Java string is an object. if the object already exists in the memory it does not create a new Object rather it assigns the same old object to the new instance, that means even though we have two string instances.

Add a comment
Know the answer?
Add Answer to:
1. What is an abstract method and why are they useful? Illustrate your answer using an...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • PRG/421 Week One Analyze Assignment – Analyzing a Java™Program Containing Abstract and Derived Classes 1.    What is...

    PRG/421 Week One Analyze Assignment – Analyzing a Java™Program Containing Abstract and Derived Classes 1.    What is the output of the program as it is written? (Program begins on p. 2) 2. Why would a programmer choose to define a method in an abstract class (such as the Animal constructor method or the getName()method in the code example) vs. defining a method as abstract (such as the makeSound()method in the example)? /********************************************************************** *           Program:          PRG/421 Week 1 Analyze Assignment *           Purpose:         Analyze the coding for...

  • Java Method Resolution : Consider the following example: What is printed on the console if Main...

    Java Method Resolution : Consider the following example: What is printed on the console if Main is executed, and why? How the codes could be improved? public class Main {     public static void main(String[] args) throws Exception {         A obj = null;         obj.foo();     } } public class A {     public void foo() {         System.out.println(“foo in A”);     } }

  • in java Part 1 In this section, we relook at the main method by examining passing...

    in java Part 1 In this section, we relook at the main method by examining passing array as parameters. Often we include options/flags when running programs. On command line, for example, we may do “java MyProgram -a -v". Depending on options, the program may do things differently. For example, "a" may do all things while "-v" display messages verbosely. You can provide options in Eclipse instead of command line: "Run ... Run Configurations ... Arguments". Create a Java class (Main.java)....

  • Question 1[JAVA] Add a method in the Main class named getLines() that takes a filename as...

    Question 1[JAVA] Add a method in the Main class named getLines() that takes a filename as a String and returns each line in the file in an array. Have each element of the array be a String. Do not include the newline at the end of each line. Use a BufferedReader object to read the file contents. Note, the contents of input.txt will be different (including the number of lines) for each test case. Example: getLines( "input.txt" ) returns (an...

  • 1) Consider the following Java program: 1 public class HelloWorld { 2     // My first program!...

    1) Consider the following Java program: 1 public class HelloWorld { 2     // My first program! 3     public static void main(String[] args) { 4         System.out.println("Hello, World!"); 5     } 6 } What is on line 1? a. a variable declaration b. a statement c. a method (subroutine) definition d. a comment e. a class definition 2) Which one of the following does NOT describe an array? a. It can be used in a for-each loop. b. It has a numbered sequence...

  • Answer in JAVA 1. Complete the method definition to output the hours given minutes. Output for...

    Answer in JAVA 1. Complete the method definition to output the hours given minutes. Output for sample program: 3.5 import java.util.Scanner; public class HourToMinConv {    public static void outputMinutesAsHours(double origMinutes) {       /* Your solution goes here */    }    public static void main (String [] args) {       Scanner scnr = new Scanner(System.in);       double minutes;       minutes = scnr.nextDouble();       outputMinutesAsHours(minutes); // Will be run with 210.0, 3600.0, and 0.0.       System.out.println("");    } } 2....

  • USE JAVA PLEASE And answer all questions Question 5.1 1. Write a program that reads in...

    USE JAVA PLEASE And answer all questions Question 5.1 1. Write a program that reads in a number n and then reads n strings. it then reads a string s from the user and gives you the word that was typed in after s. Example input: 4 Joe Steve John Mike Steve Example output: John Example input: 7 Up Down Left Right North South East Right Example output: North 2. Remember to call your class Program Question 5.2 1. Write...

  • java This lab is intended to give you practice creating a class with a constructor method,...

    java This lab is intended to give you practice creating a class with a constructor method, accessor methods, mutator methods, equals method , toString method and a equals method. In this lab you need to create two separate classes, one Student class and other Lab10 class. You need to define your instance variables, accessor methods, mutator methods, constructor, toString method and equals method in Student class. You need to create objects in Lab10 class which will have your main method...

  • // Java Queue LinkedList Assignment // A queue is implemented using a singly linked list. //...

    // Java Queue LinkedList Assignment // A queue is implemented using a singly linked list. // the variable: back "points" at the first node in the linked list // new elements ( enqueued) are added at the back // the variable: front "points" at the last node in the linked list. // elements are removed (dequeued) from the front // // Several queue instance methods are provided for you; do not change these // Other instance methods are left for...

  • The task of this project is to implement in Java Hash Table structure using Linear Probing...

    The task of this project is to implement in Java Hash Table structure using Linear Probing Collision Strategy.   You can assume that no duplicates or allowed and perform lazy deletion (similar to BST). Specification Create a generic class called HashTableLinearProbe <K,V>, where K is the key and V is the value. It should contain a private static class, HashEntry<K,V>. Use this class to create array to represent Hashtable:             HashEntry<K,V> hashtable[]; Implement all methods listed below and test each method...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT