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 6 years ago.
Improve this question
I was working on this question and I was wondering I have got it right.
Consider the interface MusicInterface which has a constant data member, TYPE,
which is equal to ‘Nice Music’ and a method play() which displays the TYPE on
console. The class StringedInstrument implements the interface
MusicInstrument.
i) Write the Java code for the interface MusicInstrument.
ii) Implement the abstract class StringedInstrument having variables
numberOfStrings of type integer and name of type String. No
implementation of method play is possible at this point.
iii) Implement the concrete class ElectricGuitar which is a subclass of
StringedInstrument having a constructor that initializes the name and
numberOfStrings and appropriate methods.
MusicInstrument class
public interface MusicInterface {
final String TYPE= "Nice Music";
public void play();
}
StringedInstrument class
public abstract class StringedInstrument implements MusicInterface {
public int numberOfStrings;
public String name;
}
ElectricGuitar class
public class ElectricGuitar extends StringedInstrument{
public ElectricGuitar(int numberOfString, String name){
super();
}
#Override
public void play() {
System.out.println("The type of music is: "+TYPE);
}
}
The question seems to be pretty straightforward so I was wondering if I made any mistake in understanding it.
Some notes for writing conventional Java code:
Change the visibility of the declared fields in your Abstract class StringedInstrument to be at least protected (or package-private). These fields are part of the state of the class and should be properly encapsulated.
Also, your ElectricGuitar constructor is kinda useless. It receives 2 parameters that are never used and the StringedInstrument's respective fields remain uninitialized. You should create a matching constructor in StringedInstrument and initialize the numberOfStrings and name fields in it, something like:
public StringedInstrument(int numberOfString, String name){
this.numberOfStrings = numberOfStrings;
this.name = name;
}
and ElectricGuitar would use this super constructor:
public ElectricGuitar(int numberOfStrings, String name){
super(numberOfStrings, name);
}
There is no particular reason for the class StringedInstrument to be abstract if it does not include any polymorphic abstract methods. I don't think this context would satisfy an appropriate example of abstract inherency.
That being said, whether you make it abstract or not, you should include in StringedInstrument:
public StringedInstrument(int numberOfStrings, String name) {
this.numberOfStrings = numberOfStrings;
this.name = name;
}
and in Electric guitar:
public ElectricGuitar(int numberOfStrings, String name) {
super(numberOfStrings, name);
}
I suppose if you put the TYPE in StringedInstrument you could do:
public abstract String getType();
and then in your specific class (ElectricGuitar) customize what getType() produces which is also a pretty weak use of an interface.
public abstract class StringedInstrument implements MusicInterface {
public int numberOfStrings;
public String name;
public StringedInstrument()
{
// This gets called by ElectricGuitar() constructor
}
#Override
public void play()
{
// I meant, you can also HAVE AN IMPLEMENTATION HERE. My Corrections
// OMITTING THIS METHOD BODY DECLARATION, WON'T CAUSE COMPILE ERRORS
// THAT WAS A BAD JOKE BY ME
System.out.println("The type of music is: "+TYPE + " In " + this.getClass().getSimpleName() );
}
}
Your Code stands solid
Related
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 5 months ago.
Improve this question
This is related to Java Strategy design pattern.
In Strategy pattern, we create objects which represent various strategies and a context object whose behavior varies as per its strategy object.
I have common code logic to be executed for all the strategies which is have implemented using Java Strategy design pattern. Which is the right place to write this common logics(something like validations and other stuffs).
Consider the below code. Here I want to do file validation which is common across any file type . Something like , the file should exist and its size should be greater than zero and file name validation. All these file related common stuff I want to keep in some place. Which could be a right design for this?
//BaseFileParser.java
public abstract class BaseFileParser{
public abstract void parseFile();
}
//XMLFileParser.java
public class XMLFileParser extends BaseFileParser{
public void parseFile(){
//Logic for parsing an XML file goes here
}
}
//CSVFileParser.java
public class CSVFileParser extends BaseFileParser{
public void parseFile(){
//Logic for parsing a CSV file goes here
}
}
//Client.java
public class Client{
private BaseFileParser baseFileParser;
public Client(BaseFileParser baseFileParser){
this.baseFileParser=baseFileParser;
}
public void parseFile(){
baseFileParser.parseFile();
}
public static void main(String args[]){
//Lets say the client needs to parse an XML file
//The file type(XML/CSV) can also be taken as
//input from command line args[]
Client client=new Client(new XMLFileParser());
client.parseFile();
}
}
If you have common behaviour, then abstract class or class is what we can use. So basic idea is to put common logic into some base common strategy class. Then we should create abstract method in abstract class. Why? By doing this, subclasses will have particular logic for concrete strategy.
I am sorry, I am not Java guy, but I've provided comments how it can be implemented in Java. Let me show an example via C#.
This is our abstract class which has common strategy:
public abstract class BaseStrategy
{
// I am not Java guy, but if I am not mistaken, in Java,
// if you do not want method to be overriden, you shoud use `final` keyword
public void CommonBehaviourHere()
{ }
public abstract void
UnCommonBehaviourHereShouldBeImplementedBySubclass();
}
And its concrete implementations:
public class StrategyOneSubclass : BaseStrategy // extends in Java
{
public override void
UnCommonBehaviourHereShouldBeImplementedBySubclass()
{
throw new NotImplementedException();
}
}
public class StrategyTwoSubclass : BaseStrategy // extends in Java
{
public override void
UnCommonBehaviourHereShouldBeImplementedBySubclass()
{
throw new NotImplementedException();
}
}
UPDATE:
This is your abstract class:
public abstract class BaseFileParser
{
// I am not Java guy, but if I am not mistaken, in Java,
// if you do not want method to be overriden, you shoud use `final` keyword
public bool IsValid()
{
return true;
}
public abstract void ParseFile();
}
and its concrete implementations:
public class StrategyOneSubclass : BaseStrategy // extends in Java
{
public override void ParseFile()
{
if (!IsValid())
return;
throw new NotImplementedException();
}
}
public class StrategyTwoSubclass : BaseStrategy // extends in Java
{
public override void ParseFile()
{
if (!IsValid())
return;
throw new NotImplementedException();
}
}
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 1 year ago.
Improve this question
my question is more a personnal mind challenge than a production purpose... which means that despite there are obviously better ways to achieve my goal* , I am curious about how - AND IF - I could do it this way.
*I am thus not interested in other ways atm.
I would like to "register" within a list several classes objects (Foo.class, Bar.class, etc.) sharing a common static method inherited from a common parent class.
Then I want to iterate over this list, and invoke that static method.
The following code is wrong indeed, but it may at least show what I am trying to achieve:
======== Classes definition
public class SomeGenericClass {
public abstract static String getType();
}
public class SomeSpecializedClassA extends SomeGenericClass{
public static String getType(){
return "I am of type A";
}
}
public class SomeSpecializedClassB extends SomeGenericClass{
public static String getType(){
return "I am of type B";
}
}
======== Main
class Main{
void main(){
List<Class<SomeGenericClass>> classes = new ArrayList<Class<SomeGenericClass>> ();
classes.add(SomeSpecializedClassA.class);
classes.add(SomeSpecializedClassB.class);
for((SomeGenericClass.class)Class c : classes){
System.out.println(c.getMethod("getType", null).invoke(null, null));
}
}
}
========
Any idea?
sharing a common static method inherited from a common parent class.
This is impossible; static methods do not 'do' inheritance, hence why they are called static methods. There is NO way to specify that a given class adheres to a spec, where 'the spec' involves 'has static method XYZ'.
Why do you think java has the cliché of having 'factories'? A factory is just a container concept where a single instance of a class is the place you ask questions about the concept of another class: A "PersonFactory" is a class for which usually only a single instance exists and it answers questions about persons in general. Most usually the constructor (which doesn't 'do' specs/interfaces either), but anything else goes too.
Then I want to iterate over this list, and invoke that static method.
Reflection can do this. It'd be horrible code style, hard to maintain, and all around entirely the wrong way to go about it. You're asking me: "May I have a gun because there is an annoying mosquito balanced on my left toe", and that's the bazooka. If you want to take it and let er rip, okay. Your funeral.
So what's the better way?
Why is 'static' important here? It's not. Register 'TypeOracle' objects:
public interface CommandHandlerFactory {
String getCommand();
CommandHandler makeHandler();
}
public interface CommandHandler {
void handleCommand(UserInfo sendingUser, String cmdData);
}
public class WelcomeHandler {
#Override
public void handleCommand(UserInfo sendingUser, String cmdData) {
sendMsg("Well hello there, " + sendingUser.getUserName() + "!");
}
}
channelBot.registerHandler(new CommandHandlerFactory() {
#Override
public String getCommand() {
return "/hello";
}
#Override
public CommandHandler makeHandler() {
return new WelcomeHandler();
}
}
That's how you do it in a non-blow-your-feet-right-off fashion.
NB: A comment on your question suggest using asm. This is an utterly nonsensical comment; ASM has nothing to do with this and can't help you. Ignore this comment.
This question already has answers here:
Implementing two interfaces with two default methods of the same signature in Java 8
(7 answers)
Closed 2 years ago.
Java 8's default methods in an interface can be called from the child class using InterfaceName.super.methodName . Why doesn't Java 8 allow us to use a similar syntax to call the specific class's method name? Can this resolve the Diamond Problem encountered for multiple inheritance?
class Employee {
public static void displayName() {
System.out.println("Employee!");
}
}
class Engineer extends Employee {
public static void displayName() {
System.out.println("Engineer!");
}
}
class Manager extends Employee {
public static void displayName() {
System.out.println("Manager!");
}
}
public class Resource extends Engineer,Manager {
public static void main(String args[]) {
//Insert similar code here like InterfaceName.super.methodName to call any of the above methods to handle multiple inheritance.
}
}
In Java 8, you can not extend (inherit) multiple classes all in one shot. What I mean by this is that if you write:
public class Resource extends Engineer, Manager { //This generates a compiler error.
}
However, you may inherit multiple classes into one, main class by making a chain of inheritance.
public class Master {
public void method1(){};
}
public class Child1 extends Master{
public void method2() {};
}
public class Child2 extends Child1 {
//you can access method 1 and method 2 here by simply calling
method1();
method2();
}
A way you can go about addressing your issue is to write an "EmployeeInterface" and write an "EmployeeClass". To access the methods in "EmployeeClass", you must make an object of the "EmployeeClass" in your main method. You will need to write a constructor to pass the name of the employee in. I will provide an example here:
public interface EmployeeInterface {
public void displayName();
public void setName(String name);
}
The above is an Interface. An interface contains the methods that you want to use in a class, however, you do not yet define them here. You only write the method headers. Think of this as a shopping list. Writing an item such as bread on a shopping list does not mean you will now have bread, it just marks it as an item that needs to be purchased.
Next, you will need to write a class implementing the EmployeeInterface.
public class EmployeeClass implements EmployeeInterface{
private String employeeName;
public EmployeeClass(String name) { //This is a constructor
this.employeeName = name;
}
#Override
/**
* This function will display the name of the employee.
*/
public void displayName() {
System.out.println(employeeName);
}
#Override
/**
* This function with use the given string and change the employee's name.
*/
public void setName(String name) {
this.employeeName = name;
}//end of setName method
}//end of class
Above is the class that implements the EmployeeInterface. It looks at the Interface and says that you must define what these methods do. This is like looking at your shopping list and seeing bread, and going to the store and buying it.
There is also a constructor in this class. A constructor in java is a method that is executed upon the instantiation of an instance of a class. This means that whatever code you write in the constructor, it will be run once and only once when you make an object of the class. Constructors must be spelled the same as the class, is case sensitive, and must be public. You can add as many parameters as you'd like.
We use #Override over the functions in the class because we are overriding (Changing the body) from nothing to our definition from the EmployeeInterface. Depending on your IDE/Compiler, it may work without the #Override tag, but it is highly reccomended that you do this.
In the constructor, you see we use this.employeeName = name; the "this" keyword refers to the field (variable) within the class that we write it in. In this case, it is not necessary, because the name of the variable in the class and the name of the variable being passed in are different. But in the case that variable names are the same, you can use "this.variableName" to specify the class variable.
Finally, to use these classes, you must make a main method in a separate class to execute these functions. Making the main method is like making a sandwich out of the bread that you purchased at the store.
public class Main {
public static void main(String[] args) {
EmployeeInterface manager = new EmployeeClass("Bob");
EmployeeInterface engineer = new EmployeeClass("Mary");
System.out.println("The name of the manager is: ");
manager.displayName();
System.out.println("The name of the engineer is: ");
engineer.displayName();
manager.setName("Jack");
System.out.println("The new manager's name is: ");
manager.displayName();
}//end of method Main
}//end of class Main
Above is the method that executes the methods that you defined in the EmployeeClass using the EmployeeInterface. First, you create an object of the class, of the type that is the name of the Interface.
EmployeeInterface manager = new EmployeeClass("Bob");
This is an object of the EmployeeClass, and we called it manager. We made it of type EmployeeInterface because we want to be able to use the methods we defined in the EmployeeInterface. We write "= new EmployeeClass("Bob");" afterward because we want to make a new Instance of the EmployeeClass, and pass the String "Bob" into our constructor.
Next, we display the name of the manager.
System.out.println("The name of the manager is: ");
manager.displayName();
This will display the name of the manager.
We can also change the name of the manager with our defined "setName()" function.
manager.setName("Jack");
We call the function like this and pass in the String "Jack" which will become the new name for the manager.
Upon execution of the Main method, we get this output:
Image of the output
All in all, this solution does not use inheritance of methods to print the names of different employees, but uses an EmployeeInterface, along with a definition of the Interface, EmployeeClass, to store and display the employee names. Rather than making a new class for every employee, you make a new object with the parameters containing the name of the new employee in the main method.
I hope this answered your question, and please do reply if you require any more clarifications.
Here I also include some articles about the Java concepts I talked about.
Here is a resource for Inheritance and Interfaces.
Interfaces on Oracle
Inheritance on Oracle
Constructors on Oracle
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 5 years ago.
Improve this question
` private member cannot accessible in child class but my below code give successful run but i know that the private member only accessible in that class where its define. parentclass(parent class) and childClass(child class) are two.
public class ParentClass {
public static void main(String[] args) {
// TODO Auto-generated method stub
childClass c=new childClass();
c.display("Hazrat Ali");
System.out.println("My father name is:"+c.getName());
}
}
class childClass extends ParentClass
{
private String Name;
public void display(String n)
{
Name=n;
}
public String getName()
{
return Name;
}
}**
In your code you are setting name as private String :
private String Name;
and accessing it using a public function getName() and returning its value to the caller:
public String getName()
{
return Name;
}
and as your (getter) function getName() has a public access modifier you can
call it using child class object:
childClass c=new childClass();
c.display("Hazrat Ali");
System.out.println("My father name is:"+c.getName());
Encapsulation / Data hiding
To achieve encapsulation in Java −
Declare the variables of a class as private.
Provide public setter and getter methods to modify and view the variables
values.
Benefits of Encapsulation
The fields of a class can be made read-only or write-only.
A class can have total control over what is stored in its fields.
Encapsulation provide control over the data.
private members cannot be accessible directly from outside the class but can be accessed using getters and setters and here you are doing the same. You are using getter to access the Name variable so nothing is wrong in this.
making class attributes hidden from other class is called Encapsulation
To achieve encapsulation in Java −
Declare the variables of a class as private.
Provide public setter and getter methods to modify and view the variables
values.
what you done is field name is accessible in class only as you accessed variable by getter function i assumed that you learned but using java built-in class
for working with private data you should have getter and setter function
public String getName() {
return name;
}
public void setName(String newName) {
name = newName;
}
You're not accessing a private variable of childClass from parentClass - you're calling public methods that access private variables of childClass. There's absolutely nothing wrong with a public method using one of its class's private variables.
Also, your main method is static, so it isn't associated with any particular instance of ParentClass. You could've just easily put this method in childClass (or some other class - it makes no difference whatever). That being said, it's not strictly accurate to say that you're actually accessing it from ParentClass - that class really doesn't have anything to do with anything here.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I am trying to make an abstract algorithm class for informed search with different heuristics. My idea was to have different subclasses overwrite the default heuristic() method, but the dynamic binding seems not to be working when I call the subclasses.
In astar.java:
public interface Astar {
abstract String heuristic();
}
In search.java
public class Search implements Astar {
public String heuristic() { return "default heuristic"; }
}
In EuclidianSearch.java:
public class EuclidianSearch extends Search {
#Override
public String heuristic() { return "Euclidian"; }
}
In ChebyshevSearch.java:
public class ChebyshevSearch extends Search {
#Override
public String heuristic() { return "Chebyshev"; }
}
In main.java:
EuclidianSearch e_search = null; ChebyshevDistance ch_search = null;
Search[] SearchObjects = {e_search, ch_search};
for(Search so : SearchObjects) {
System.out.println(so.heuristic());
}
When run, it displays:
default heuristic
default heuristic
I define the array in terms of Search so I can be flexible: eventually, I want to have five or more different heuristics. Why doesn't the heuristic() method of the subclass override that of the superclass?
You will get NullPointerException for calling so.heuristic() because you don't instance class, use these codes :
EuclidianSearch e_search = new EuclidianSearch();
ChebyshevDistance ch_search = new ChebyshevDistance();
but it is not sufficient to solve you problem, you should implement AStart interface by diffrent classes. don't forget that a class which implement a interface should implement all interface method. otherwise, you should define an abstract class to define only some methods and override remain methods in other classes with extend you previous class.
public class Search implements Astar {
#Override
public String heuristic() { return "default heuristic"; }
}