Write a class encapsulating the concept of a file, assuming file has a single at
ID: 3622646 • Letter: W
Question
Write a class encapsulating the concept of a file, assuming file has a single attribute: file name. Include constructor, mutator, accessor, tostring, and equals. Include an instance variable to keep track of the number of the files. Write a method that returns the number of files we have. Also include a method that returns the extension of the file. For example if the filename is text.java, your method will return java. If the file name does not include a dot, your method should return "unknown extension."
public class file
{
private string name;
private string extension;
private static int count = 0;
public File( String n, String e);
{
name = n;
extension = e;
count ++;
}
Explanation / Answer
// save as file.java and run
// private string extension; this variable not required in your code.
public class file
{
private String name;
private static int count=0;
file()
{
}
file(String n)
{
name = n;
count++;
}
public void setFilename(String n)
{
name = n;
count++;
}
public String getFilename()
{
return name;
}
public String toString()
{
return "File name is "+name;
}
public boolean equals(file a)
{
if((this.getFilename()).equals(a.getFilename())) return true;
else
return false;
}
public String getExtension()
{
int k = name.indexOf('.');
if(k>0)
return name.substring(k+1);
else
return "Unkown Extension";
}
public static void main(String[] args)
{
file f1 = new file("king.jpg");
file f2 = new file();
f2.setFilename("matlab.m");
System.out.println("file f2 name is " + f2.getFilename());
System.out.println(f2);
System.out.println(""+ f1.getFilename()+ " Equals? " + f2.getFilename() + " " + f1.equals(f2));
file f3 = new file("hihihi");
System.out.println(f3 + " " + f3.getExtension());
file f4 = new file("king.jpg");
System.out.println(f1.getFilename()+ "Equals? " + f4.getFilename()+ " " + f1.equals(f4));
System.out.println("No of File Objects Till Created "+ f1.count);
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.