I am getting problems with these 2 lines. I need to create a class with an array of Animals using constants to size it. I have to fill the array Animal with Fish and Iterate in 2 different ways through the array executing move() and makeSound().
These are the lines:
1 animals[0] = new Fish()
2 for (Animal animal : animals) {
public class Animals {
public static void main(String[] args) {
final int SIZE = 6;
Animal animal[] = new Animal[SIZE];
animals[0] = new Fish() // 1
for (Animal animal : animals) { // 2
System.out.println("Bubbles");
System.out.println("Swim");
}
}
}
My interface Animal:
public interface Animal {
public void move();
public void makeSound();
}
And my class Fish that implements Animal
public class Fish implements Animal{
#Override
public void move() {
System.out.println("Swim");
}
#Override
public void makeSound() {
System.out.println("Bubbles");
}
private String color;
public String getColor(){
return color;
}
public void setColor(String color){
this.color = color;
//Prefix this.color;
}
}
A couple of syntax errors to fix:
Add a semicolon to the end of animals[0] = new Fish();
Change Animal animal[] = new Animal[SIZE]; to Animal[] animals = new Animal[SIZE];
Also, you should really be doing this in the for loop:
for(Animal animal : animals){
animal.makeSound();
animal.move();
}
Just hard-coding print statements defeats the purpose of having the Animal interface, even if Fish is the only class implementing Animal at the moment.
Related
I'm trying to put together a few things here and it isn't working correctly. I thought that each time through the loop, the loop would update and inherit for each class member. Instead, it is printing the "member" method 4 times.
import java.util.ArrayList;
public class toolband
{
public static void noise()
{
System.out.println("abc");
}
static class member extends toolband
{
public static void noise()
{
System.out.println("xyz");
}
}
static class maynard extends member
{
String namemaynard = "maynard";
public static void noise()
{
System.out.println("pow pow");
}
}
static class adam extends member
{
String nameadam = "adam";
public static void noise()
{
System.out.println("da dun da dun");
}
}
static class danny extends member
{
String namedanny = "danny";
public static void noise()
{
System.out.println("smash smash smash");
}
}
static class justin extends member
{
String namejustin = "justin";
public static void noise()
{
System.out.println("womp wa wa wo wo womp");
}
}
public static void main (String [] args)
{
ArrayList <member> members = new ArrayList <member> (4);
member m = new maynard();
member a = new adam();
member d = new danny();
member j = new justin();
members.add(m);
members.add(a);
members.add(d);
members.add(j);
for (member i : members)
i.noise();
}
}
Can someone help me understand what I am doing incorrectly. Should I be making these all static methods?
The problem is that noise method in toolband is static.In java static method is not overriden.
To make this work change noise method signature to public void noise() and same in the subclasses which override and it works.
public class toolband {
public void noise() {
System.out.println("abc");
}
}
class member extends toolband {
public void noise() {
System.out.println("xyz");
}
}
class maynard extends member {
String namemaynard = "maynard";
public void noise() {
System.out.println("pow pow");
}
}
class adam extends member {
String nameadam = "adam";
public void noise() {
System.out.println("da dun da dun");
}
}
class danny extends member {
String namedanny = "danny";
public void noise() {
System.out.println("smash smash smash");
}
}
class justin extends member {
String namejustin = "justin";
public void noise() {
System.out.println("womp wa wa wo wo womp");
}
}
I recently had an interview,they asked me a small question
the question is follows
There is list of Students
List<Student> students;
Class Student{
String rollNo;
Map<String, Integer> marks ;
}
Stdunt.marks is actually cobination of subject and mark
Should write an method which should return top 10 students array according to the subject.
List<Student> getTop10(String subjectName){
}
The answer i have given is blelow
private static void PrintTop5(ArrayList<Student> list,String subject){
Collections.sort(list, new Comparator<Student>() {
#Override
public int compare(Student st1, Student st2) {
// TODO Auto-generated method stub
return st2.getSubjectMark(subject) - st1.getSubjectMark(subject);
}
});
ArrayList<Student> studentList = new ArrayList<Student>(list.subList(0,5));
for(Student student : studentList){
System.out.println(student.getRollNum() + " MARK : "+student.getSubjectMark(subject));
}
}
Student class look like below
package com.main;
import java.util.HashMap;
public class Student {
private String rollNo;
private HashMap<String, Integer> marks ;
public Student(){
marks = new HashMap<>();
}
public void setRollNumber(String number){
this.rollNo = number;
}
public void setSubjectAndMark(String subName,int mark){
this.marks.put(subName, mark);
}
public HashMap<String, Integer> getAllMarks(){
return marks;
}
public int getSubjectMark(String subject){
return marks.get(subject);
}
public String getRollNum(){
return rollNo;
}
}
In general your idea is correct, to sort the entire list and take top N students, in fact with java 8 it would look cleaner.
private static void PrintTop5(ArrayList<Student> list,String subject){
list.sort(Comparator
.comparing((Student student) -> student.getSubjectMark(subject))
.reversed());
List<Student> studentList = list.stream().limit(5).collect(Collectors.toList());
for(Student student : studentList){
System.out.println(student.getRollNum() + " MARK : "+student.getSubjectMark(subject));
}
}
I understand with toString() methods, their must be a return type, when an external method is called.
The comment block below describes what I'm trying to do.
Later on when I work with setters and getters, this knowledge will most definitely be invaluable.
import java.util.*;
public class Display_ArrayList {
static ArrayList<String> cars = new ArrayList<String>();
public static void main(String[] args) {
cars.add("Nissan Maxima");
cars.add("Toyota Prius");
cars.add("Renault Clio");
cars.add("Ford Focus");
cars.add("Volkwagen Passat");
System.out.println("");
System.out.println("[Standard toString()]:");
System.out.println(cars.toString());
System.out.println("");
System.out.println("[Custom toString()]:");
System.out.println(custom_cars_toString());
}
// Array list displays the car list all on the same line
public static String getCarList() {
return cars.toString();
}
// *************************************************************************
// I want Array list contents to be displayed on their own lines without
// commas or brackets, while at the same allowing this method to be
// retrieved by a toString() method
// *************************************************************************
// public static void getCarList() {
// for (String element : cars)
// System.out.println(element);
// }
public static String custom_cars_toString() {
return "The cars contained are: \n" + getCarList();
}
}
Can't you just make a class that extends ArrayList which overrides the toString method? Then you could make something like this:
public class DisplayArrayList<T> extends ArrayList {
#Override
public String toString() {
String res = "";
for (int i = 0; i < size(); i++) {
res += (i == 0 ? "" : "\n") + get(i).toString();
}
return res;
}
}
Then you can just put your cars in a DisplayArrayList instead of an ArrayList and then when you print that you will get them all on individual lines.
For example this:
DisplayArrayList<String> list = new DisplayArrayList<>();
list.add("test1");
list.add("test2");
list.add("test3");
list.add("test4");
list.add("test5");
System.out.println(list);
Would output this:
test1
test2
test3
test4
test5
Sorry if this doesn't do what you want to, couldn't completely figure out what you want from your post.
I have the following test class
public class Driver
{
public static void main(String [] args)
{
BankAccount[] b1 = {new BankAccount(200), new BankAccount(300), new BankAccount(250), new BankAccount(300), new BankAccount(200)};
BankAccountGroup bag = new BankAccountGroup(b1);
}
And BankAccountGroup:
public class BankAccountGroup
{
private BankAccount bank[];
public BankAccountGroup(BankAccount[]b)
{
for(int i =0; i<5;i++)
{
bank[i] = b[i];
}
}
these are just snippets of the whole code. Im getting a nullpointerexception for these two lines:
- bank[i] = b[i];
- BankAccountGroup bag = new BankAccountGroup(b1);
Please help
When you declare bank[] in the BankAccountGroup class it looks like you forgot to give it a length. Because of this, when you call bank[i] in your for loop, anything after i=0 is probably going to give you an error.
something like
private BankAccount[] bank = new BankAccount[5];
Either initialize your array first(Bad).
Or assign it from the value you pass the constructor.
private BankAccount[] bank;
public BankAccountGroup(BankAccount []){
bank = b;
}
You are not initializing the bank array. You also shouldn't assume that the argument will have a length of 5 elements. I would rewrite the class to something like this:
public class BankAccountGroup
{
private BankAccount bank[];
public BankAccountGroup(BankAccount[]b)
{
if (b != null)
{
bank = new BankAccount[b.length];
for(int i=0; i<b.length;i++)
{
bank[i] = b[i];
}
}
}
}
Consider below example:
public class sample{
private Map myMap;
public Map getMap(){
return myMap;
}
}
In above example, we are returning the map to some other calling class. So my question is how we can say that this class encapsulates/protects its data. The Map that will be returned will be available for modification by other classes.
Thanks,
Rajan
Consider this class Person, which have 2 attributes (name and age).
package app;
/**
*
* #author salathielgenese
*/
public final class Person
{
public Person()
{
setAge(age);
setName(name);
}
public Person(String name, long age)
{
setName(name);
setAge(age);
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public long getAge()
{
return age;
}
public void setAge(long age)
{
this.age = age;
}
private String name;
private long age;
}
Now imagine that some one (let say the calling class) set the age to -19. This will generate inconsistency in your that.
So when you protect your data, your controlling wich kind of action are made possible these data.
You may decide that if the given age is lower than 0 then the age will be set to 0 for example. The code may become...
public void setAge(long age)
{
this.age = age;
if (age < 0)
{
this.age = 0;
}
}
You can do the same with name attribute to prevent setting it to null.
public void setName(String name)
{
this.name = name;
if (name == null || name == "")
{
this.name = "NO NAME";
}
}
We'll say that encapsulation help protecting data.
··························································································
Now let's imagine a class called Carpenter. When you need a table, you just ask it to him. Thus the Carpenter class should provide a method which takes a description of the table you need, and return the build table. Assuming that the method is called buildTable, this method will be declared with public access because it's useful to call it from another Class.
When you ask to the Carpenter to build up your Table, he will need to check some material as well as saw, needle and so on and so far. We (calling class) don't care about this internal mechanism and all methods as well as attributes involved in this process will be declared with private access. i.e to prevents external classes from modifying them, i.e to encapsulate our fields and methods for better protection.
Encapsulating a field let us control access to our data.
Comming back to your code, giving public access to getMap() doesn't prevent calling class to modify its content.
Now look at this Example
Person.java
package app;
/**
*
* #author salathielgenese
*/
public final class Person
{
public Person()
{
setAge(age);
setName(name);
}
public Person(String name, long age)
{
setName(name);
setAge(age);
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
if (name == null || name == "")
{
this.name = "NO NAME";
}
}
public long getAge()
{
return age;
}
public void setAge(long age)
{
this.age = age;
if (age < 0)
{
this.age = 0;
}
}
#Override
public String toString()
{
return "Person{" + "name=" + name + ", age=" + age + '}';
}
private String name;
private long age;
}
Example.java
package app;
/**
*
* #author salathielgenese
*/
public class Example
{
public Example()
{
}
public Example(Person person)
{
this.person = person;
}
public Person getPerson()
{
return person;
}
public void setPerson(Person person)
{
this.person = person;
}
private Person person;
}
**Main class (Loader.java)
package app;
/**
*
* #author salathielgenese
*/
public class Loader
{
/**
* #param args the command line arguments
*/
public static void main(String[] args)
{
// Instantiate an Example with a new created Person
Example example = new Example(new Person("Rajan", 19));
// Retrive person in example and print its description (printing result of implicit call to person.toString() )
Person person = example.getPerson();
System.out.println(person);
// Assigning a new reference to the variable **person** and print its description
person = new Person("Salathiel", 20);
System.out.println(person);
// Print description of Person containning in Example instance
System.out.println(example.getPerson());
}
}
If you look closed this code, you'll understand that you can change attribute of your Map but not the reference to it.
Maybe you can use an unmodifiable map from Java Collection API's :
public class sample{
private Map myMap;
public Map getMap(){
return Collections.unmodifiableMap(myMap));
}
}