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 9 years ago.
Improve this question
I want to know the exact scenario of using constructor over methods can anyone give me the exact example program for constructors over methods in java
They are not similar things to compare even.
Both serves completely different purposes and even you have to note that constructor wont return anything, not even void :)
If you see a basic tutorial on Constructor, mentioned
Constructor declarations look like method declarations—except that they use the name of the class and have no return type.
So you cannot choose one over them.
If you are looking/talking about setting variables of instance memebers, choose setter methods instead of variables.
Another scenoriao is some objects never complete without providing some basic info. In that cases you have to create a constructor like it should be built when necessary info passed in constructor.
Consider the below scenorio, where to create an employee class, He must have an employee Id
public class Employee {
String empId;
public Employee(String empId) {
this.empId = empId;
}
// Methods
public static void main(String[] args) {
Employee a = new Employee("green");
}
Consider the below scenorio, where to create an empty employee class, later he can assign employee Id
public class Employee {
private String empId;
public Employee() {
}
// Methods
public void setEmpId(String empId) {
this.empId = empId;
}
public static void main(String[] args) {
Employee a = new Employee(); //No error
a.setEmpId("SOMEX007");
}
}
Related
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.
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
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 have a little code that let me register an student (ID, name, age, etc), right now I could do it but just accepting one user, would overwrite if I register a new one, which is what I need now, be able to have more than 1 student.
So I was thinking that if I were using C I would use structs, something like this
struct Students {
int ID[6];
char Name[35];
char Age[2];
} student;
After reading a bit, Java doesn't have this facility.
How to do this in Java ? Is it possible ?
Thanks
Java has no struct.
You can use class as structs with members having public access specifier and no methods
In Java you could make a class for students. Once you get to know java better you should change those properties to either private or protected and use public getter/setter methods.
public class Student{
public int id;
public String name;
public int age;
}
And then in your main code you could create however many students you need:
Student myStudentA = new Student();
It is true that in C you would use structs to embody the information you need for each student.
In object-oriented languages like Java, you would use classes. So the equivalent to the C structure you defined would be something like the following class in Java:
public class Student
{
public int id; // [*]
public String name;
public String age;
//... other things go here, such as constructors and methods ...
}
[*] You defined the id member to be an array of 6 integers. I assume that you probably meant it to be a single integer value that could hold up to 6 digits.
You probably also want to define the age member to be a integer instead of a two-character string.
Note that in Java, String variables do not have a maximum length like null-terminated C character arrays do.
It is absolutely possible to do this in Java. Java is an object oriented programming language so when you are dealing with "things", such as students, it is very easy to implement them into a Java class.
Here is one of many ways you could do this:
public class Students{
private List<Student> students;
public Students(){
this.students = new ArrayList<>();
}
public void addStudent(Student newStudent){
students.add(newStudent);
}
public Student getStudents(){
return this.students;
}
public Student getStudent(int name){
for(Student s : students){
if(s.getName().equalsIgnoreCase(name)){
return student();
}
}
return null;
}
public class Student{
private int id;
private String name;
private int age;
public Student(){
}
public Student(int id, String name, int age){
this.id = id;
this.name = name;
this.age = age;
}
// Getters and Setters for the Students variables
}
}
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
What is the difference between this and .this when calling functions? And, what happens when this or this. is used?
Example:
class reference
{
public void object()
{
reference obj = new reference();
this.obj();
}
}
The Class.this syntax is useful when you have a non-static nested class that needs to refer to its enclosing class's instance.It is only used in cases where there is an inner class, and one needs to refer to the enclosing class
Within an instance method or a constructor, this is a reference to the current object — the object whose method or constructor is being called. You can refer to any member of the current object from within an instance method or a constructor by using this.
A good example
public class TestForThis {
String name;
public void setName(String name){
this.name = name;
}
public String getName() {
return name;
}
class TestForDotThis {
String name ="in";
String getName() {
return TestForThis.this.name;
}
}
public static void main(String[] args) {
TestForThis t = new TestForThis();
t.setName("out");
System.out.println(t.getName());
TestForThis.TestForDotThis t1 = t.new TestForDotThis();
System.out.println(t1.getName());
}
}
Output will be
out
out
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I am new to java in general but I am having a lot of trouble with objects specifically. I have a project to pass an object to another object. I've looked all over the internet for help, my online java textbook doesn't explain objects in detail. So my question is, how would you pass an object to another object.
-Thank you in advance
Messaging between objects is a core concept in object-oriented programming. To "pass an object to another object" generally just means that one object exposes a method which accepts the type of another object as a parameter to that method. It could be something as simple as this:
class Person {
private String name;
public void setName(String name){
this.name=name;
}
public String getName(){
return name;
}
}
class Car {
private Person driver;
public void setDriver(Person driver) {
this.driver = driver;
}
}
Then somewhere in the code, you'd have an instance of a Car and an instance of a Person, and you'd call that method:
carInstance.setDriver(personInstance);
Those instances could have been created lots of different ways. Perhaps even as simple as:
Person personInstance = new Person();
personInstance.setName("David");
Car carInstance = new Car();
You can pass an object o1 to another object o2 through calling a method of o2 (or a constructor of o2's class in particular; constructors as you know are special types of methods).
I suggest you start by figuring out what this code below does.
How many persons are there?
What are their names at different moments of the execution of the program?
How many times and where a Person object is passed to a Person object?
How many times and where a String object is passed to a Person object?
If you digest this, you'll be good for now.
class Person {
private String name;
public Person(String name){
this.name = name;
}
public Person(Person p){
this.name = p.name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public class MainProg {
public static void main(String[] args) {
Person t1 = new Person("Joe");
Person t2 = new Person("John");
System.out.println(t1.getName());
System.out.println(t2.getName());
t1.setName("Mark");
System.out.println(t1.getName());
System.out.println(t2.getName());
Person t3 = new Person(t1);
System.out.println(t3.getName());
}
}