Java: Override protected String [closed] - java

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I don't know Java.
Just need a quick fix if possible.
How to override protected String?
I have:
public class Something {
protected String changeMe = "this";
public String viewForm() {
...
return getForm();
}
public String getForm() {
return changeMe;
}
}
myfile:
public class MySomething extends Something {
public String viewForm() {
return super.viewForm();
}
}
How to use changeMe = "that" in class MySomething?
Thanks.

Actually, others have answered your question. In case, you are really new to Java struggling to figure it out, the simplest answer to your question is just put your above mentioned statement in the constructor of the derived class:
Solution one (actually bad solution):
public class MySomething extends Something {
public MySomething() {
changeMe = "that"
}
}
A better solution for your problem is to define a setter method in the class Something as follows (in case you have access to its source code):
public void setChangeMe(String newValue) {
changeMe = newValue;
}
and you can change the value by calling
Something s = new Something();
s.setChangeMe("that");

the word override is a hint for the compiler, with that you let it know that you're writing code that at your own way implements the method of a parent class or the interface.
having said that overriding a variable/attribute/field is a wrong use of the terminology, and makes not much sense
to answer your question: you can access toso the changeMe object because it is not defined as private... so you can change the value directly..
Example:
public static void main(String args[]) {
MySomething ms = new MySomething();
System.out.println(ms.changeMe);
ms.changeMe = "that";
System.out.println(ms.changeMe);
}

Related

How force developers to use constructor without arguments if value supposed to be default? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
public class Student {
public Student(String name){
do_smth(name);
}
public Student(){
this("Mike");
}
}
How force developers to use parameterized constructor only if value differs from default:
not calling new Student("Mike") but use for this new Student()?
The reason: we have constructor with 5 parameters. In most cases parameters are the same. But there are about 5%-10% cases when they differ.
 So in order to avoid duplications, I would like to use such approach.
I know it maybe better to use smth like Builder pattern here. But I don't like it verbosity.
This may be implemented by using additional private constructor with a flag:
public class Student {
public Student(String name) {
this(name, false);
}
public Student() {
this("Mike", true);
}
private Student(String name, boolean defaultUsed) {
if (!defaultUsed && "Mike".equals(name)) {
throw new IllegalArgumentException(
"Tut-tut lil kid, it's pwohibited to set Mike's name outside defauwt constwuctor");
}
do_smth(name); // only if do_smth cannot be overridden in child classes
}
}
Note: method do_smth should be private or final so that it could not be overloaded in subclasses which is far more important than setting a limit on setting a name from specific constructor.

Access control exercise - java [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I need to print the attributes from TestCar class by creating a public hackCar method in class Terminal. The hackCar method needs to take a TestCar as a parameter and print the attributes of TestCar. The caveat for this assignment is that I cannot touch anything in the TestCar class.
I am still struggling with printing the two private attributes in TestCar. How can I print the two private attributes from Test Car class by using the Test Car object as the parameter in the hackCar method?
Story class:
class Story {
public static void main(String args[]) {
TestCar testCar = new TestCar();
Terminal terminal = new Terminal();
terminal.hackCar(testCar);
}
}
class Terminal {
public void hackCar(TestCar other) {
System.out.println(other.doorUnlockCode);
System.out.println(other.hasAirCondition);
System.out.println(other.brand);
System.out.println(other.licensePlate);
}
}
class TestCar {
private int doorUnlockCode = 602413;
protected boolean hasAirCondition = false;
String brand = "TurboCarCompany";
public String licensePlate = "PHP-600";
}
Thanks!
Private fields are called 'private' because there is no way to get them. But you can make public getter for them:
class TestCar {
// Your 4 fields here...
public int getDoorUnlockCode() {
return this.doorUnlockCode;
}
}
Then in hackCar method change
System.out.println(other.doorUnlockCode); to this: System.out.println(other.getDoorUnlockCode());
So now you can access field doorUnlockCode through public getter.
Do the same for protected field hasAirCondition
Your methods Terminal.getdoorUnlockCode() and Terminal.getAirCondition() can't get to fields from another object, they must be in TestCar object

Design pattern - creating an object from different types of data source [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I have been trying to find an appropriate design pattern, if a formal one exists, for the following scenario:
Object A requires an object B. Now, object B can be created using data from different sources, say S_1 or S_2. I don't want A to have to care about creating B, it should just be given it and proceed. So then, is there a nice clean way of creating B? I have thought about factory-type patterns but I do not have polymorphism at play. I was thinking something like:
B obj_b = B.createInstance(type_S_1);
obj_A.doSomething(obj_B);
where I give the type of data soruce to the static method createInstance().
I'm still learning a lot about design patterns, so that's why I ask. I may be over complicating things, so please feel free to say so!
As you realized, the Abstract Factory pattern is overkill for your use case as you do not need polymorphism. Still, the Concrete Factory part of this design pattern make sense. So this could look a bit like:
Datasource ds1 = ...;
Datasource ds2 = ...;
MyObject objectA = ...;
DatasourceBasedFactory factory1 = new DatasourceBasedFactory(ds1);
objectA.doSomething(factory1.create());
Knowing more about what you actually want to do might help to give you a better answer. Your current problem description is extremely abstract ... If you could give us some more details about your domain, that would help to give you a better answer.
I'm not sure, but perhaps the Builder Pattern? You can give it a type to specify what to build.
I would consider 2 differents approaches using generics.
The client will only deal with a common result Object that could be final for example.
No matter what your DataSource is, you can reduce the impact for the client.
Approach 1
Example
public interface DataSourceExtractor<T> {
public DataSourceExtractResult extract(T source);
}
public final ResultSetExtractor implements DataSourceExtractor<ResultSet>{
public DataSourceExtractResult extract(ResulSet source) {
//CODE HERE
return null;
}
}
public final ResultSetExtractor implements DataSourceExtractor<JsonNode>{
public DataSourceExtractResult extract(JsonNode source) {
//CODE HERE
return null;
}
}
But you can also meet the advantage of Abstract Class and Interface.
The advantage is that the client will inherit common methods or you can even implement template methods.
Example
public AbstractDataSourceExtractor<T> implements DataSourceExtractor<T> {
public static final SomeObject commonMethod(DataSourceExtractResult result) {
//CODE HERE
return null;
}
}
public final ResultSetExtractor extends AbstractDataSourceExtractor<ResultSet>{
public DataSourceExtractResult extract(ResulSet source) {
//CODE HERE
return null;
}
}
public final ResultSetExtractor extends AbstractDataSourceExtractor<JsonNode>{
public DataSourceExtractResult extract(JsonNode source) {
//CODE HERE
return null;
}
}
Approach 2
Example
You can also think about a generic Abstract builder, if many elements need to be set for the construction of the Instance.
The advatange of that solution is that you can set a default value, provide internal implementation hiding from the client if necessary.
public abstract class AbstractDataSourceExtractResultBuilder<T>{
private T _source;
public AbstractDataSourceExtractResultBuilder(T source) {
_source = source;
}
public abstract DataSourceExtractResult build();
}
public final class JsonDataSourceExtractBuilder extends AbstractDataSourceExtractResultBuilder<JsonNode> {
private String _name;
private Charset _charset;
public JsonDataSourceExtractBuilder(JsonNode source, String name){
//GUARD CODE
super(source);
_name = name;
_charset = Charset.defaultCharset();
}
public JsonDataSourceExtractBuilder useCharset(Charset charset){
if(charset == null){
throw new IllegalStateException("The charset is null");
}
_charset = charset;
return this;
}
//etc...
public DataSourceExtractResult build(){
//CODE HERE
return null;
}
}

Overriding mutator methods for sake of validation [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I am currently working on an Object Oriented Design project, and would like to know if there is a better way to validate data in mutators of subclasses.
For example, I have a Home class with the subclasses Apartment, Condo, and House. In the Home class, I would like to include the mutators for (private) fields that the subclasses share. Say one of the fields is squareFootage. Is there a way to make the mutator in Home generic enough so that the subclasses can then set their own valid values for squareFootage without having to override the mutator completely? That is, I want different valid ranges for squareFootage for each subclass.
I've tried setting possible range values in Home, then override them in the subclasses. Unfortunately, the mutator in Home still grabs from the Home class and not the subclass.
So, I've resorted to abstracting the mutators, but unfortunately this results in a lot of repeated code, since I can literally copy and paste the mutators in each subclass.
I want to make the possible range values static if possible, and I understand this may be possible with reflection, but I'd really like to avoid using it for this project.
I think is possible by adding an abstract "validator" method that have to be implemented in the subclasses, something like this:
public class Home {
private float squareFootage;
public abstract void validateSquareFootage() throws MyValidationException; // you could throw an exception, runtime exception or return a boolean to indicate if value is valid or not
public void setSquareFootage(float squareFootage) {
validateSquareFootage(squareFootage); // again, throws exception or returns boolean, up to you
this.squareFootage = squareFootage;
}
// ... rest of implementation
}
And in a subclase:
public class Condo extends Home {
#Override
public void validateSquareFootage(float squareFootage) throws MyValidationException {
// ... do validations
}
}
and you don't have to override the mutator at all, just implement the correct validator.
It would probably be best to make the Home class an abstract class and have that extended in your subclasses. That way you can create methods in the home class that will hold true for all your subclasses but you can override them in the subclasses
If I understood your problem correctly, I think you want something like this ?
abstract class Home<T>{
protected T squareFootage;
abstract void setSquareFootage(T t);
}
class Apartment extends Home<String>{
#Override void setSquareFootage(String t) {
//...do something about the parameter
this.squareFootage = t;
}
}
class Condo extends Home<Integer>{
#Override void setSquareFootage(Integer t) {
//...do something about the parameter
this.squareFootage = t;
}
}
class House extends Home<Boolean>{
#Override void setSquareFootage(Boolean t) {
//...do something about the parameter
this.squareFootage = t;
}
}

Design pattern to convert a class to another [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
I have a class called GoogleWeather, I want to convert it to another class CustomWeather.
Is there any design pattern which helps you to convert classes?
In that case I'd use a Mapper class with a bunch of static methods:
public final class Mapper {
public static GoogleWeather from(CustomWeather customWeather) {
GoogleWeather weather = new GoogleWeather();
// set the properties based on customWeather
return weather;
}
public static CustomWeather from(GoogleWeather googleWeather) {
CustomWeather weather = new CustomWeather();
// set the properties based on googleWeather
return weather;
}
}
So you don't have dependencies between the classes.
Sample usage:
CustomWeather weather = Mapper.from(getGoogleWeather());
There is one critical decision to make:
Do you need the object that is generated by the conversion to reflect future changes to the source object?
If you do not need such functionality, then the simplest approach is to use a utility class with static methods that create a new object based on the fields of the source object, as mentioned in other answers.
On the other hand, if you need the converted object to reflect changes to the source object, you would probably need something along the lines of the Adapter design pattern:
public class GoogleWeather {
...
public int getTemperatureCelcius() {
...
}
...
}
public interface CustomWeather {
...
public int getTemperatureKelvin();
...
}
public class GoogleWeatherAdapter implements CustomWeather {
private GoogleWeather weather;
...
public int getTemperatureKelvin() {
return this.weather.getTemperatureCelcius() + 273;
}
...
}
Besides, You can also use new Java8 feature 'Function' from java.util.function'.
More detailed explanation is provided in http://www.leveluplunch.com/java/tutorials/016-transform-object-class-into-another-type-java8/ . Kindly have a look!

Categories

Resources