I use a method
public String introduce()
{
return super.introduce();
}
which returns the value from introduce() method of super class. And assume introduce() method returns
Hey! I'm Steve and I'm 26 years old
In the same class,I also have another method
public String getAlter() {
return alter;
}
Now alter contains the value:
Jobs
Now, the question is how do I return the value
Hey! I'm Steve and I'm 26 years old. I'm also known as Jobs!
from the overridden method, ie
public String introduce()
{
return super.introduce();
}
Just concatinate the strings returned by the two methods:
#Override
public String introduce() {
return super.introduce() + ". I'm also known as " + getAlter() + "!";
}
You have to override the method introduce:
1) call the super class method introduce() -> returns "Hey! I'm Steve and I'm 26 years old"
2) use method getAlter() inside the overridden method introduce()"
public String getAlter() {
return "Jobs";
}
#Override
public String introduce() {
String msg = super.introduce();
String name = this.getAlter();
msg = msg + ". I'm also known as " + name + "!";
return msg;
}
public static void main(String[] args) {
Jobs jobs = new Jobs();
String msg = jobs.introduce();
System.out.println(msg);
}
public String introduce()
{
return super.introduce()+" I'm also known as "+getAlter();
}
You can use the result of super.introduce() to build your final result.
#Override
public String introduce() {
return super.introduce() + ". I'm also known as " + getAlter() + "!";
}
Note the #Override annotation to make it clear that I am hiding the super implementation.
Don't immediately return your call to super:
public String introduce()
{
return super.introduce() + getAlter();
// for clarity, you are essentially performing these operations:
// String response = super.introduce();
// response = response + " I'm also known as ";
// response = response + getAlter();
// return response;
}
Simple way is to append them like:
#Override
public String introduce() {
StringBuilder strBuilder = new StringBuilder();
strBuilder.append(super.introduce());
strBuilder.append(" I'm also known as");
strBuilder.append(getAlter());
return strBuilder.toString();
}
Hope this help!
Related
I am new at java . I have method witch contain some variables with different data type i.e. String and Array
pNumber=rs.getString("pNumber");
userName=rs.getString("userName");
simOperater=rs.getString("simOperater");
AdharNumber=rs.getString("AdharNumber");
rechargeAmount[i]=rs.getString("rechargeAmount");
activeDate[i]=rs.getString("activeDate");
plainDeatils[i]=rs.getString("plainDeatils");
and I want to return all the variables from single method in java so what approach should I use please help
just return a response object
public class MyResponse {
public String pNumber;
public String userName;
//....
}
usage:
public MyResponse yourMethod() {
MyResponse myResponse = new MyResponse();
myResponse.pNumber=rs.getString("pNumber");
myResponse.userName=rs.getString("userName");
//...
return myResponse;
}
If you don't want to write more lines, you can also set the return type of your method to Object and return your variable as you normally would, but then cast the returned object into the right type as it was before.
e.g.
class test {
static Object test_return(int which) {
String s = "This is a string";
int i = 100;
if(which == 0) {
return s;
} else {
return i;
}
}
public static void main(String args[]) {
String s = (String) test_return(0);
int i = (int) test_return(1);
System.out.println("String: " + s + "\nint: " + i);
}
}
output:
String: This is a string
int: 100
edit:
since you are new to java, you might not understand how types exactly work here. so I would suggest you read this and this to learn more about autoboxing and unboxing
Im trying to make a program that allows the client to input a String. The string length should have 3 characters only and should contain the letters .
My program have to pass through this table and check what this string refers to..
Let's say the client passed this String "AUG", my program should show the name of this String which is "Met".
I made a code, and it worked but it has more then 15 if else-if condition.
My question is : Is there any other way to do it without using if else-if (or switch).
And does polymorphism work in this case ?
Have a look at HashMap
You can build your table with:
Map<String, String> table = new HashMap<>();
table.put("AUG", "Met");
table.put(...);
Then access your table using the user's input:
if(table.containsKey(input)){
return table.get(input);
}
I think I'd go about it with an enum personally (provided performance wasn't a significant concern):
public enum Abbreviations {
Ala("GCU", "GCC", "GCA", "GCG"),
Arg("CGU", "CGC", "CGA", "CGG", "AGA", "AGG")
// ...
;
private final List<String> codons;
private Abbreviations(final String... codons) {
this.codons = Arrays.asList(codons);
}
public boolean contains(final String codon) {
return this.codons.contains(codon);
}
}
And then you can find their matching from the String using something like:
public String find(final String codon) {
for (final Abbreviations abb : Abbreviations.values()) {
if (abb.contains(codon)) {
return abb.name();
}
}
throw new IllegalArgumentException("Unknown codon: '" + codon + "'");
}
You could try an Object Oriented Aproach:
//This is your representation of Codon
//Which has a name e.g. Alanine and an Abreviation object.
public class Codon {
private String name;
private Abreviation abreviation;
public Codon(String name, Abreviation abreviation) {
this.name = name;
this.abreviation = abreviation;
this.abreviation.addCodon(this);
}
#Override
public String toString() {
return "Codon [name=" + name + ", abreviation=" + abreviation + "]";
}
}
import java.util.ArrayList;
import java.util.List;
// This is a representation of an abreviation object
// Which has an abreviation: ALA;
// and the name of the abreviation "Alanine".
public class Abreviation {
private String abreviation;
private String name;
private List<Codon> codons = new ArrayList<>();
public Abreviation(String abreviation, String name) {
super();
this.abreviation = abreviation;
this.name = name;
}
public boolean addCodon(Codon codon) {
return this.codons.add(codon);
}
#Override
public String toString() {
return "Abreviation [abreviation=" + abreviation + ", name=" + name + "]";
}
}
// Here is your program, where it's being build all the Codons structure with your respective Abbreviation.
public class App {
public static void main(String[] args) {
// This is abreviation, it'll will associated with the codon
Abreviation alanine = new Abreviation("Ala", "Alanine");
// Here it's being build the codon CGU, which has abreviation alanine
Codon GCU = new Codon("GCU", alanine);
// Then using toString method it prints what have been done
System.out.println(GCU);
}
}
You can put all of your codons into a List, so you can search and retrieve then.
I have created a custom FEST Condition to verify that my actual string either matches or is equal to an expected String
public class StringMatchesOrIsEqualTo extends Condition<String>{
private String expectedStringOrExpression;
public StringMatchesOrIsEqualTo(final String expectedStringorExpression){
this.expectedStringOrExpression = expectedStringorExpression;
}
#Override
public boolean matches(String value) {
return value.matches(expectedStringOrExpression) || value.equals(expectedStringOrExpression);
}
}
Whenever the conditon fails i want it to display a message that shows me what the original and expected String was
currently the display string is
actual value:<'Some String'> should satisfy condition:<StringMatchesOrIsEqualTo>
is there a way that this message also displays what the match is made against ?
I tried overriding the toString method in the class
#Override
public String toString() {
return "string matches or is equal to : " + expectedStringOrExpression;
}
but that does not seem to work.
You want to set the description, which can be done by calling the Condition(String) constructor:
public StringMatchesOrIsEqualTo(final String expectedStringorExpression){
super("A String that matches, or is equal to, '" + expectedStringorExpression "'");
this.expectedStringOrExpression = expectedStringorExpression;
}
Alternatively, you could override description():
#Override
public String description()
{
return "A String that matches, or is equal to, '" + expectedStringorExpression "'");
}
I'm iterating over a ResultSet and save it to a ArrayList.
weatherData = Arrays.asList (
new WeatherInfo(rs.getDate(1), rs.getInt(2)...
When I do a System.out.println(weatherData); I see this in the Eclipse Console:
[com.example.project.view.ChartsData$WeatherInfo#66ee6cea, com.example.project.view.ChartsData$WeatherInfo#757d0531.....
What does it mean? Is it a value I can handle in Java or not?
Is this the actual date and int that I can use in Java?
thanks
You need to override toString() method in WeatherInfo class. What you see is its default implementation that presents its memory location.
This is a typical model object in Java with a toString() method. I used Intellij Idea (recommended!) which has the ability to auto-generate toString() and other methods such as equals() and hashCode(). We find that having these methods on all model objects is very useful for debugging and testing.
Running main() will output:
weatherInfo = WeatherInfo{country='CA', probablyOfPrecipitation=20}
public class WeatherInfo {
public static void main(String [] args) {
WeatherInfo weatherInfo = new WeatherInfo();
weatherInfo.setCountry("CA");
weatherInfo.setProbablyOfPrecipitation(20);
System.out.println("weatherInfo = " + weatherInfo);
}
String country;
int probablyOfPrecipitation;
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public int getProbablyOfPrecipitation() {
return probablyOfPrecipitation;
}
public void setProbablyOfPrecipitation(int probablyOfPrecipitation) {
this.probablyOfPrecipitation = probablyOfPrecipitation;
}
#Override
public String toString() {
return "WeatherInfo{" +
"country='" + country + '\'' +
", probablyOfPrecipitation=" + probablyOfPrecipitation +
'}';
}
}
Top Tip!
We use a library called EqualsVerifier to guarantee that all equals() and hashCode() implementations are correct.
Here is an example of what I am trying to ask
superclass Name.java
public class Name{
protected String first;
protected String last;
public Name(String firstName, String lastName){
this.first = firstName;
this.last = lastName;
}
public String initials(){
String theInitials =
first.substring(0, 1) + ". " +
last.substring(0, 1) + ".";
return theInitials;
}
and then the subclass is ThreeNames.java
public class ThreeNames extends Name{
private String middle;
public ThreeNames(String aFirst, String aMiddle, String aLast){
super(aFirst, aLast);
this.middle = aMiddle;
}
public String initials(){
String theInitials =
super.first.substring(0, 1) + ". " +
middle.substring(0, 1) + ". " +
super.last.substring(0, 1) + ".";
return theInitials;
}
so if i create an Threename object with ThreeNames example1 = new ThreeNames("Bobby", "Sue" "Smith") and then call System.out.println(example1.initials()); I will get B.S.S. I get that.
My question is is there a way to call the initials method that is in the Name class so that my output is just B.S.
no. once you've overridden a method then any invocation of that method from outside will be routed to your overridden method (except of course if its overridden again further down the inheritance chain).
you can only call the super method from inside your own overridden method like so:
public String someMethod() {
String superResult = super.someMethod();
// go on from here
}
but thats not what youre looking for here.
you could maybe turn your method into:
public List<String> getNameAbbreviations() {
//return a list with a single element
}
and then in the subclass do this:
public List<String> getNameAbbreviations() {
List fromSuper = super.getNameAbbreviations();
//add the 3 letter variant and return the list
}
There are many ways to do it. One way: don't override Names#initials() in ThreeNames.
Another way is to add a method to ThreeNames which delegates to Names#initials().
public class ThreeNames extends Name {
// snip...
public String basicInitials() {
return super.initials();
}
}
I would instead leave initials alone in the superclass and introduce a new method that will return the complete initials. So in your code I would simply rename the initials method in ThreeNames to something else. This way your initials method is the same across the implementations of Name