There is an interface like this:
public interface Person {
public String getName();
}
and then there is a class Student which implements Person:
public class Student implements Person {
private int id;
private String name;
public setId(int id) {
this.id = id;
}
public getId() {
return id;
}
public setName(String name) {
this.name = name;
}
public getName() {
return name;
}
}
What would an instance of Person look like at runtime? How do I instantiate?
You can't instantiate an interface.
What you can do is instantiate an implementation of an interface - in your case, Student.
Person s = new Student();
In this case, s will implement Person and you can check it with:
boolean isPerson = (s instanceof Person);
which will be evaluated to true
You cannot instantiate Person it is interface
you can only instantiate Student like
Person p1= new Student();
or
Student S1 = new Student();
You can never instantiate an interface in java. You can, however, refer to an object that implements an interface by the type of the interface. For example,
Person test = new Student();
As already stated in other answers, Person is an interface so can't be instantiated. Therefore it is useful to include the arguments in the constructor of the implementing class since the latter's setters will not be directly accessible from a Person reference
public Student(int id, String name) {
this.id = id;
this.name = name;
}
so as to initialize
Person s = new Student(1, "Jon Smith");
Related
I have to write a code for example
public class Student {
private int id;
private String name;
public Student (int id, String name) {
this.id=id;
this.name=name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Now, in MAIN CLASS I have to get all values from user
How am I supposed to set value in constructor??
like this?
String name = input.nextLine();
int id = input.nextInt();
Student student = new Student (id, name);
"THE ISSUE WITH THIS METHOD IS THAT, WE CAN'T KEEP THE ATTRIBUTES PRIVATE THEN, BECAUSE THEY ARE NOW LOCAL VARIABLES"
OR
I create a constructor with no parameters and use that object to get values and set in fully parametrized constructor.
Student st = new Student();
student.setName(input.nextLine());
student.setID(input.nextInt());
Student student = new Student (st.getId, st.getName);
I don't know if I was able to explain what I want, but if you get that, do let me know
I would use this approach
Student st = new Student();
st.setName(input.nextLine());
st.setID(input.nextInt());
But both are fine . You don't really need to create the second student object in the second example. Just use the one you created upfront
To access the name and ID later you can do
String name = st.getName();
int id = st.getID();
(Edit - this assumes you do make a no arg constructor)
I am trying to understand java class and object relation but facing one problem.
Here I have one simple java bean class:
public class Student {
int id;
String name;
String marks;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getMarks() {
return marks;
}
public void setMarks(String marks) {
this.marks = marks;
}
}
And one Editor class:
public class EditStudent {
public static void editStd(Student st){
st.setId(10);
st.setName("editAbleName");
st.setMarks("133");
// return st;
}
I am writing this logic for student object in my program class:
public class TestProgram {
public static void main(String args[]){
System.out.println("main");
Student std = new Student();
std.setId(1);
std.setName("zeeshan");
std.setMarks("44");
EditStudent.editStd(std);
System.out.println("id " +std.getId());
System.out.println("name " +std.getName());
System.out.println("marks " +std.getMarks());
}
}
Output:
main
id 10
name editAbleName
marks 133
I supposed that I will get output values of my object that I set on my test program class but getting output values of those which I set on my EditStudent class.
Why this happen even I think there is no relation between my std object and editStudent Class ?
Please explain me logic occurs behind this logic and process!
std is not an Object. It is a reference to an Object. So, when you pass it to the method editStd, you pass the reference to the Object.
Therefore, std and st refer to the same object(as they store the same reference) Thus, any changes to the object pointed by st, is also reflected in std, as they are the same.
EditStudent.editStd(std);-- Even if you are passing modified object of std in editStd method, editStd again modifies std object with values in the method. This is because std and s object refers to same object on heap.
your EditStudent class will get inherit through your argument of student class (st) you have made. You don't need to define the values of Base class (student) in EditStudent class. your testprogram class is correct then it will override the values of EditStudent Class and you will get the output of your derived class(testprogram). So remove the values from EditStudent Class.
You are passing a reference to the Object.
In Edit student
EditStudent.editStd(std); // In java It is a reference
// IN C++ You used to write '&' in your method(function)
but in Java it is not like that. Java doesn't have pointers --> either
Since you are new I will tell you how to write the class properly
public class Student {
// Make them PRIVATE
private int id;
private String name;
private String marks;
// create constructor
Student(){} // empty
Student(int id, String name, Strings marks){
this.id = id;
this.marks = marks;
this.name = name;} // overloaded, If you want
// use Getter and setter for only Private field.. NO need for Public
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getMarks() {
return marks;
}
public void setMarks(String marks) {
this.marks = marks;
}
}
Benefit of overloaded constructor
public class TestProgram {
public static void main(String args[]){
System.out.println("main");
/* Student std = new Student();
std.setId(1);
std.setName("zeeshan");
std.setMarks("44"); */
// benefit of overloaded constructor
Student s = new Student(1,"zeeshan", 44);
// you only need one line
// EditStudent.editStd(std); // Here you are passing the reference to your object to another class.. Which changes the original
// If you want to edit student Make a method in Student class
// I am following your logic
// create an empty student and pass it.
Student s2 = EditStudent.editStd( new Student() );
// return the student from editstd goto method it is below
System.out.println("id " +std.getId());
System.out.println("name " +std.getName());
System.out.println("marks " +std.getMarks());
}
}
public class EditStudent {
public static Student editStd(Student st){
// return type student
st.setId(10);
st.setName("editAbleName");
st.setMarks("133");
return st;
}
I am trying to access class members of different class i.e.,getDetails() from student as well as customer class using Object class Reference variable. But it looks like its not working. Please look into this easy code and help me out how to access the getDetails() using Object class ob[0] and ob[1]
class Customer
{
int custId;
String name;
Customer(String name, int custId)
{
this.custId = custId;
this.name = name;
}
public void getDetails()
{
System.out.println(this.custId+" : "+this.name);
}
}
class Student
{
int roll;
String name;
Student(String name, int roll)
{
this.name = name;
this.roll = roll;
}
public void getDetails()
{
System.out.println(this.roll+" : "+this.name);
}
public static void main(String []args)
{
Object[] ob = new Object[2];
ob[0] = new Student("Vishal", 041);
ob[1] = new Customer("Xyz" , 061);
ob[0].getDetails();
ob[1].getDetails();
}
}
Try creating a common interface that declares the method getDetails. Something like this:
public interface Person {
public void getDetails();
}
Let Student and Customer implement the interface. Then declare the array like this:
Person ent[] ob = new Person[2];
....
As you can see I am stuck in part where I should set a name an owner of ford... Thanks for help.
public class Vehicle {
Person owner;
long motorSerialNo;
String registerNo;
public static void main(String[] args) {
//an example, create an object instance of class Car
Car ford = new Car();
ford.model = "Focus";
ford.motorSerialNo = 123456;
ford.registerNo = "CA-126-65";
//and here is a problem
ford.owner.setName("John Croul");
}
}
class Car extends Vehicle {
String model;
}
class Person {
public Person(String name){
this.name = name;
}
String name;
String lastname;
String address;
String getName() {
return name;
}
void setName() {
this.name = name;
}
}
Firstly, your setter should look like
public void setName(String name) {
this.name = name;
}
Then you have to initialize the instance variable person before calling its method setName(), otherwise you will get the NullPoiterException.
Person owner = new Person();
or in the main method, as you did for other variables
ford.owner = new Person();
I have a basic assignment to do but am very new to OOP and struggling with it. Other online resources are starting to add to my confusion.
I am required to:
Write code for a class Person. A Person object is to have attributes name, age and address.
Write code for a class Dog. A Dog object is to have attributes name and age.
Give any additional code in the Person and Dog classes that is required to setup a bidirectional association between a Person object and a Dog object. A Person object acts as an owner for a Dog object and the Dog object acts as a pet for the Person object.
Modify your Person class so that a Person object can act as owner for up to 20 Dog objects.
Obviously this is a very simple example.
My code so far:
Person Class :
public class Person
{
// instance variables - replace the example below with your own
private String name;
private int age;
private String address;
/**
* Constructor for objects of class Person
*/
public Person()
{
this.name = name;
this.age = age;
this.address = address;
}
//Set Methods:
public void setName () {
this.name = name;
}
public void setAge () {
this.age = age;
}
public void setAddress () {
this.address = address;
}
//Get Methods:
public String getName () {
return name;
}
public int getAge () {
return age;
}
public String getAddress () {
return address;
}
}
Dog Class:
public class Dog
{
// instance variables - replace the example below with your own
private String name;
private int age;
public Dog()
{
this.name = name;
this.age = age;
}
//Set Methods:
public void setName () {
this.name = name;
}
public void setAge () {
this.age = age;
}
//Get Methods:
public String getName () {
return name;
}
public int getAge () {
return age;
}
}
Main:
public class Main
{
//Blank
}
I know this code is currently useless and doesn't do anything but I am unsure of how to 'associate' the objects & where to do it. The assignment spec specifies a person acts as an 'owner' for the dog.
This is where my problem lies. Setting up the relationship between the objects.
The main problem here is consistency: if a Dog d1 is a pet for a Person p1, then p1 must be owner of d1, and vice versa. If, as many suggested, we have 2 methods (Person.addDog() and Dog.setOwner()), then a user can easily make a mistake and fail to call both methods (or call with wrong arguments). Since a Dog can have only one owner, a simple and safe interface would be using single method Dog.setOwner(Person p), where p may be null if we want the dog to have no owner. This method, besides setting the field Dog.owner, must remove this dog from the pet list of previous owner and (if p != null) add itself to the pet list of the new owner. The methods of class Person to add and remove pets should be visible for the class Dog but not visible to the user (they should be package private), while the method Dog.setOwner should be public.
UPDT
We can consider value of Dog.owner as a primary datum, and value of Person.dogs as secondary data, similar to database indexes.
This is a common problem with bidirectional relationships; you can't pass them in the constructor because one will not exist yet when the other is initialised. For this reason you must "wire them up from the outside"
Your mention of 20 dogs suggests they want you to use an array to hold the dogs, but an arraylist would be better. I will use the arraylist but can show you how this would work with an array if you'd like
public class Person
{
ArrayList<Dog> dogs=new ArrayList<Dog>(); //this will hold all the dogs that the Person has as pets
public void giveDog(Dog dog){
dogs.add(dog)
}
.....
.....
Equally the dog class is given an owner
public class Dog
{
Person owner;
public void setOwner(Person owner){
this.owner=owner;
}
.....
.....
Using these two methods you can create the bidirectional relationship.
Notes
This is obviously an assignment so you have no choice but for the future; bidirectional relationships like this can be useful. But they are also dangerous when used incorrectly; the most important thing is that after initialisation an object must work without error. It must not rely on setOwner() or giveDog() being called: in other words a petless person and an ownerless dog must behave "correctly" (what ever that means in this context. Failing to achieve this can lead to bug prone code. If this is impracticle then it must be impossible for ownerless dogs or dogless people to be exposed to the rest of the program; factory methods can be useful for this, but that is beyond the scope of this question
Because both objects can't be created at the same time you can't pass references to each other in the constructor. You must create getter and setter methods so you can create this relationship after the objects are created. An example of this is as follows:
public class Person
Set<Dog> dogs = new HashSet<Dog>();
public void addDog(Dog dog){
if(dogs.size()>20){
throw new IllegalArgumentException("exceeded the limit: ");
}
dogs.add(dog);
}
}
public class Dog
{
Person person;
public void setPerson(Person person){
this.person=person;
}
}
What you are required to do looks like a circular dependency issue. So what you can do is to use the object composition.
Simply add to your classes a instance variable of the second type:
public class Person
{
private Dog myDog;
private String name;
private int age;
private String address;
...etc.
and respectively in the Dog class, every Dog will have its owner:
public class Dog
{
private Person myOwner;
private String name;
private int age;
Don't forget setters and getters.
As for the point 4):
4) Modify your Person class so that a Person object can act as owner for up to 20 Dog objects.
Instead of having every Person object have one Dog member, use an array, or some Collection (List, Set, etc.):
So instead of
private Dog myDog;
do
private Dog[] dogArray = new Dog[20];
OR
private Collection<Dog> dogList = new ArrayList(20); //for example
Try this one:
Person person = new Person();
Dog dog1 = new Dog();
dog1.setAge(12);
Dog dog2 = new Dog();
dog2.setAge(34);
person.addDog(dog1); //dog 1
person.addDog(dog2); //dog 2
person.listDogs(); //list of all dogs
//PERSON
public class Person {
// instance variables - replace the example below with your own
private String name;
private int age;
private String address;
private ArrayList<Dog> dogs = new ArrayList<Dog>();
/**
* Constructor for objects of class Person
*/
public Person()
{
this.name = name;
this.age = age;
this.address = address;
}
public void addDog(Dog dog) {
this.dogs.add(dog);
}
public void listDogs() {
for(Dog item : this.dogs) {
System.out.println(item.getAge());
}
}
//Set Methods:
public void setName () {
this.name = name;
}
public void setAge () {
this.age = age;
}
public void setAddress () {
this.address = address;
}
//Get Methods:
public String getName () {
return name;
}
public int getAge () {
return age;
}
public String getAddress () {
return address;
}
}
//DOG
public class Dog {
// instance variables - replace the example below with your own
private String name;
private int age;
public Dog()
{
this.name = name;
this.age = age;
}
//Set Methods:
public void setName () {
this.name = name;
}
public void setAge (int age) {
this.age = age;
}
//Get Methods:
public String getName () {
return name;
}
public int getAge () {
return age;
}
}