How to override Parent class using new object? - java

I am trying to generate custom XML message via class ParentMessage, I don't
know how to override the fields and the methods.
For this issue there is 3 class.
1 - ParentMessage (source code core), I don't have access to code.
2 - ChildMessage(My class core), I need to override ParentMessage class by creating new object of ParentMessage.
3 – Main(client class), use fields and methods of ChildMessage.
Thanks for any help.
abstract class ParentMessage extends Packet {
// this is source code, current fields library , I can't Change the method or have access to these fields.
public String element = "message";
public String type = "email";
public String body = "";
public String phone = "";
public String from = "";
public String to = "";
pubilc void sendMessage(String element, String type, String body){
// this current method library , I can't Change the method
//build xml format
//send message
//example of format XML message
//<message to='rotem#example.com/LIB'>
// <from>bob#example.com/LIB</from>
// <type>email</type>
// <body>some text body</body>
//</message>
}
}
//
abstract class ChildMessage {
// this my class I want to override the ParentMessage Fields and methods
// and make here the change code.
//example of custom XML message
public String element = "rootmessage"; //override the field
public String element2 = "element2"; //I add new field
public String element3 = "element3"; //I add new field
public String type = "web"; //override the field
public String body2 = "body2"; //I add new field
public String body3 = "body3"; //I add new field
public ParentMessage parentMessage = new ParentMessage();
pubilc void sendMessage(String type, String body, String body2, String body3){
//<rootmessage to='rotem#example.com/LIB'>
// <from>bob#example.com/LIB</from>
// <type>web</type>
// <body>some text body</body>
// <element2>
// <body2>some text body2</body2>
// </element2>
// <element3>
// <body3>some text body3</body3>
// </element3>
//</rootmessage>
//send message
}
}
//
public class Main {
// client class
public String from = "bob#example.com/LIB";
public String to = "rotem#example.com/LIB";
public String type = "android";
public String body = "some text body";
public String body2 = "some text body2";
public String body3 = "some text body3";
public static void main( String ... args ) {
public ChildMessage childMessage = new ChildMessage();
childMessage.sendMessage (type, body, body2, body3){};
}
}

First of all, in order to override methods of a class, your class must extend that class :
abstract class ChildMessage extends ParentMessage
Second of all, fields cannot be overridden. Only methods can.

a very simple example for you:
public abstract class Test1 {
public String element = "message0";
public String element1 = "message1";
}
public class Test2 extends Test1{
public String element = "message2";
public void printMe() {
System.out.println(element);
System.out.println(element1);
}
}
You will see it will print:
message2
message1
Do let me know if it is still not clear

To override a method, you need to have the exact same signature.
This:
public void sendMessage(String type, String body, String body2, String body3);
Does not override this:
public void sendMessage(String element, String type, String body);
because the former accepts 4 parameters and the latter only accepts 3. If you want to override the method, you have to remove the last parameter so that both accept 3 strings.
(However, since you're adding new arguments to the function, chances are you aren't really overriding it and are rather changing the behaviour altogether. Unfortunately I cannot really help you there because I do not know exactly what you are doing)

Related

How to use variable of method from 1 class in 2 class via Java?

public static class One {
#Override
public String interact(String... values) {
String actualTextOne = "test";
return actualTextOne;
}
}
public static class Two {
#Override
public String interact(String... values) {
String actualTextTwo = "test";
/* Here I need to compare actualTextOne and actualTextTwo, but the problem is that I can't find solluction how to use actualTextOne in Two class*/
return actualTextTwo;
}
}
You cannot do that.
Please check variable scope in java.
https://www.codecademy.com/articles/variable-scope-in-java
A possible solution here is to call the method interact from the class One. Something like this
public static class Two {
#Override
public String interact(String... values) {
String actualTextTwo = "test";
One one = new One();
String actualTextOne = one.interact(values);
// compare values here
return actualTextTwo;
}
}
Why in your classes functions have parameters if you dont use it?
You can mark your class with static only if he is nested, else you need do like this:
class Two {
static public String interact(String... values) {
String actualTextTwo = "test";
return actualTextTwo;
}
}
String textOne = One.interact("");
String textTwo = Two.interact("");
System.out.println(textOne==textTwo);

how to make a map of properties using formatted string "Property:Value"

Lets say we created a string formatted like this "Property:Value". How do we put this formatted string into a map in Java like this HashMap<JoystickEnum,String> where Property is an enum and the value is a string. Currently I am working on a project where we recieve input using this formatted string. My enum is called JoystickEnum. The class is called Joystick and it extends the Controller class.NOTE: Since we will be using this abstract class that is going to be implemented in multiple controllers. This class has code,
public String data;
public InputStream dataStream;
private byte[] readBuffer = new byte[400];
public enum InputMode {
POLL,EVENT
};
public InputMode mode = InputMode.EVENT;
public InputHandler(InputStream dataStream) {
this.dataStream = dataStream;
}
#Override
public abstract void serialEvent(SerialPortEvent arg0);
public void setDataMode(InputMode mode) {
this.mode = mode;
}
public abstract void poll();
public abstract Map getData();
#Override
public abstract void run();
// TODO Auto-generated method stub
The InputMode enum just contains POLL,EVENT. Where the code will go is in the extended method getData()
if data is a String of the format "Property:Value" and map an object of type Map<JoystickEnum, String> you can add an entry as follow
String[] dataArray = data.split(":");
map.put(JoystickEnum.valueOf(dataArray[0]), dataArray[1]);
assuming that Property match with an enum value and Value won't contain any ":"

Using an argument as an interface item

In the program I am making, I am trying to get a formatted season name for a given season(formatted so it . I keep the formatted names in an interface, since if I were to use a map, it would be unnecessarily regenerated, since I don't make an instance of TeamBuilder
The Seasons interface:
public interface Seasons {
/*
* Contains a formatted list of seasons.
*
* An interface is being used as an alternative to using a Map in the
* TeamBuilder class, since calling parseTeam would have to build
* mappings for the seasons each time it
* was called. This way, the formatted name can simply be grabbed
*/
final String Skyrise = "Skyrise";
final String Toss_Up = "Toss%20Up";
final String Sack_Attack = "Sack%20Attack";
final String GateWay = "Gateway";
final String Round_Up = "Round%20Up";
final String Clean_Sweep = "Clean%20Sweep";
final String Elevation = "Elevation";
final String Bridge_Battle = "Bridge%20Battle";
final String Nothing_But_Net = "Nothing%20But%20Net";
final String Starstruck = "Starstruck";
final String In_The_Zone = "In%20The%20Zone";
final String Turning_Point = "Turning%20Point";
}
The problem comes when I try to grab these seasons. My TeamBuilder class takes in an argument(String season), which is unformatted. My question is, is there any way that I can use a String argument for a method to get a specific item from an interface? This is the most preferable to using a HashMap, which would needlessly regenerate the same information
All these classes can be found on the Github page for this project.
If you want to do it in a typed way, you can use Enum for this:
enum Season{
Skyrise,Toss_Up, Sack_Attack;
#Override
public String toString() {
switch(this){
case Skyrise: return "Skyrise";
case Toss_Up: return "Toss%20Up";
case Sack_Attack: return "Sack_Attack";
default: return "";
}
}
}
public class main{
public static void printSeason(Seasons seasons){
System.out.println(seasons);
}
public static void main(String[] args) {
Seasons e = Seasons.Skyrise;
printSeason(e);
System.out.println(e);
}
}
Since the compiler internally invokes the toString(), you can pass the argument as a Seasons or a String like my example.
And if you still want to use a map without "unnecessarily regenerated" you can use a static field with static initializer like this:
class Seasons {
private static Map<String,String> map = new HashMap<>();
static {
map.put("Skyrise", "Skyrise");
map.put("Toss_Up", "Toss%20Up");
}
public static String getFormatted(String key){
return map.getOrDefault(key,"");
}
}
class main{
public static void main(String[] args) {
System.out.println(Seasons.getFormatted("Skyrise"));
}
}
Just to integrate on Snoob answer you can have enum with fields, so:
enum Season
{
Skyrise("Skyrise"),
Toss_Up("Toss%20Up"),
Sack_Attack("Sack%20Attack")
;
public final String fancyName;
private Season(String fancyName)
{
this.fancyName = fancyName;
}
}
You really have all the benefits without any drawback.

Writing a method to return the string inside an object in Java

I'm really new to Java and programming in general (~3 weeks of experience) so sorry if this question is obvious for you guys. I tried searching for answers here but couldn't find any that fit my specific problem. And yeah it's for school, I'm not trying to hide it.
Here I'm supposed to write an object method that returns the string contained in the object oj, in reverse. I do know how to print a string in reverse, but I don't know how I should call the object since the method isn't supposed to have any parameters.
import java.util.Random;
public class Oma{
public static void main(String[] args){
final Random r = new Random();
final String[] v = "sininen punainen keltainen musta harmaa valkoinen purppura oranssi ruskea".split(" ");
final String[] e = "etana koira kissa possu sika marsu mursu hamsteri koala kenguru papukaija".split(" ");
OmaMerkkijono oj = new OmaMerkkijono(v[r.nextInt(v.length)] + " " + e[r.nextInt(e.length)]);
String reve = oj.printreverse();
System.out.println(reve);
}
}
class OmaMerkkijono{
private String jono;
public OmaMerkkijono(String jono){
this.jono=jono;
}
public String printreverse(){
//so here is my problem, i tried calling the object in different ways
//but none of them worked
return reversedstringthatdoesnotexist;
}
}
You just need to add this to your "printreverse" method :
new StringBuilder(this.jono).reverse().toString()
With this, when you call the method with the object "oj":
String reve = oj.printreverse();
After the previous line, "reve" must contain the value of the String reversed.
Olet hyvä, moi moi!
To revers a String use StringBuilder and reverse()
public String printreverse(){
return new StringBuilder(jono).reverse().toString();
}
To access private attributes from outside the class you use what are called accessors and mutators, aka getters and setters.
You just need a basic getter that also reverses the string.
public class MyObject {
private String objectName;
MyObject(String objectName) {
this.objectName = objectName;
}
public String getObjectName() {
return objectName; // returns objectName in order
}
public String getReversedObjectName() {
return new StringBuilder(objectName).reverse().toString();
}
public static void main(String[] args) {
MyObject teslaRoadster = new MyObject("Telsa Roadster");
System.out.println(teslaRoadster.getObjectName());
System.out.println(teslaRoadster.getReversedObjectName());
}
}
Output:
Telsa Roadster
retsdaoR asleT

String s1=new String("demo"); While printing why does it give output as the given string?

If we create a String like below and print the value:
String s=new String("demo");
System.out.println(s);
...the output is:
demo
Good. This is the expected output. But here String is a class. Remember that. Below is another example. For example, take a class like this:
class A
{
public static void main (String args[])
{
A a =new A();
A a1=new A("hi"); //we should create a Constructor like A(String name)
System.out.println(a1); //here O/P is address
}
}
My doubt is that I created the A instance in the same way I created the new String object, and I printed that object. So why does it not print the given String for the instance of A?
You need to override the Object#toString() in your class. By default, the toString() method of Object is called.
Also, to print the value, you just need to override the method as internally a call will be made to the toString() method when this statement is executed.
System.out.println(a1);
Sample overriden toString() method.
#Override
public String toString() {
// return a string value
return "The String representation of your class, as per your needs";
}
You have to override toString() method in your class the way you want to print something when call System.out.println();. In String class toString() method has override and you will get out put above due to that.
As pointed out already, you need to override the default toString() method inherited from the Object class. Every class automatically extends the Object class, which has a rather simple toString(), which can't know how to turn your particular object into a String. Why should it, especially if your class is arbitrarily complex? How is it supposed to know how to turn all your class's fields into a "sensible" string representation?
In the toString() of your class, you need to return the string that you want to represent your class with. Here is a simple example:
class A {
String foo;
public A(String foo) {
this.foo = foo;
}
public String toString() {
return foo;
}
}
public class sample {
public static void main(String[] args) {
A a = new A("Hello world!");
System.out.println(a);
}
}
String is a class whose purpose is to hold a string value and will return that value if referenced. When you use other classes, you will usually want to add other behavior. If you want to use the class to hold different values that you can set (on object creation or later in processing) you may want to use "setter" and "getter" methods for such values.
Here is an example:
public class Snippet {
private static final String C_DEFAULT_VALUE = "<default value>";
private String name;
private static Snippet mySnippet;
public Snippet() {
}
public Snippet(String value) {
setName(value);
}
/**
* #param args
*/
public static void main(String[] args) {
if (args != null && args.length > 0) {
mySnippet = new Snippet(args[0]);
} else {
mySnippet = new Snippet(C_DEFAULT_VALUE);
}
System.out.println(mySnippet.getName());
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}

Categories

Resources